Skip to content

Let callers cancel Python wait_for_review - #111

Open
thekarannagpal wants to merge 16 commits into
prooflinedev:mainfrom
thekarannagpal:cancel-review-wait
Open

thekarannagpal wants to merge 16 commits into
prooflinedev:mainfrom
thekarannagpal:cancel-review-wait

Conversation

@thekarannagpal

@thekarannagpal thekarannagpal commented Nov 24, 2026 •

Copy link
Copy Markdown

Problem

wait_for_review polls until a terminal review state or its own timeout. A caller that is shutting down, switching work, or handling SIGINT had no SDK-level way to stop the poll: the sync call keeps blocking and the async call keeps awaiting reads and backoff. The TypeScript SDK already lets callers cancel waitForReview with an AbortSignal; the Python SDK had no equivalent.

Approach

Added an optional cancel_event keyword to both clients:

  • ProoflineClient.wait_for_review(..., cancel_event=threading.Event())
  • AsyncProoflineClient.wait_for_review(..., cancel_event=asyncio.Event())

The event is checked before the wait starts, before each poll, during the backoff, and after each read. A cancelled wait returns ReviewOutcome(status="STOPPED", reason="The wait was cancelled by the caller."). If a review had already been read, outcome.review still holds that last record in every cancellation path. Passing the wrong event type raises TypeError before any HTTP request.

An in-flight read is not interrupted; it finishes within the client's configured HTTP timeout. With no cancel_event, the existing single sleep(delay) / await async_sleep(delay) path is unchanged, so current callers keep the same polling and backoff behavior. With an event, backoff waits on the event itself rather than polling in 50 ms slices, and uses a monotonic cutoff so a late wakeup cannot extend the deadline. No generated code changed.

Repro

import threading

cancel = threading.Event()
# Set cancel from another thread when the caller no longer needs the result.
outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel)
if outcome.status == "STOPPED":
    print(outcome.reason)
import asyncio
import signal

cancel = asyncio.Event()
asyncio.get_running_loop().add_signal_handler(signal.SIGINT, cancel.set)
outcome = await async_client.wait_for_review(
    organization_id,
    review_id,
    cancel_event=cancel,
)

Before this change there was no cancel_event parameter, so the only options were to wait for the timeout or abandon the blocking call.

Tests

Added 25 cancellation and event-wait tests (7 cases across sync and async, plus 11 helper tests) in tests/test_http.py:

  • an already-set event stops before any request;
  • an event set after the real backoff wait starts stops without another request;
  • an event observed during a read stops after retaining that last review;
  • a cancelled read with a mismatched review ID raises the same invalid-response error as the normal path;
  • an event set during an erroring read returns STOPPED with the last review;
  • an event observed just before the next poll retains the last review;
  • an invalid event type raises TypeError before any request;
  • the async event waiter latches a set-then-clear signal delivered before the cutoff;
  • the async event waiter ignores a signal first delivered after the cutoff while its waiter is still active;
  • the async event waiter latches a signal delivered before the cutoff even if its waiter resumes late;
  • the async event waiter ignores an asyncio.Event subclass's overridden wait();
  • external cancellation propagates through the async event waiter;
  • the sync backoff ignores a signal first set at the absolute deadline;
  • the sync backoff latches a signal sent before the deadline even if its waiter resumes late;
  • captured set callbacks are recorded by both sync and async waits;
  • both waits leave the caller's event setter and condition unwrapped;
  • the async waiter leaves no registered future after a timeout;
  • the no-event backoff test fails if either event-wait helper is called.

The async helper tests use a controlled clock and synchronize delivery with the helper's internal wait so a scheduler pause cannot turn an early signal into a late one. The late-signal test keeps ALL_COMPLETED and bounds the helper with asyncio.wait_for(). The async tests set asyncio.Event through loop.call_soon_threadsafe when the setter is a server thread. The existing backoff test still asserts the unchanged delays [5, 10, 20, 40, 60, 60, 60, 5], guarding against accidental chunking of every sleep.

Results

  • pytest -q -p no:cacheprovider tests/test_http.py -k "cancel_event or cancelled_read or async_wait_for_event or sleep_with_cancel or polling_backoff_and_timeout_keep_review_url_and_last_record" — 25 passed, 202 deselected in 1.69s.
  • Full suite on this Windows host — 243 passed in 28.38s. Earlier runs hit the pre-existing timing-sensitive test_body_stream_deadline_does_not_turn_authority_into_timeout[200-sync]; it fails on the baseline too and passes in isolation. It is unrelated to this change.
  • ruff check . — all checks passed.
  • ruff format --check . — 238 files already formatted.
  • mypy proofline scripts — no issues in 229 source files.
  • scripts/contracts.py — operation and outcome-vocabulary contracts passed.
  • python scripts/check.py --prepare — pinned tools installed and wheel prepared.
  • The full scripts/check.py generation gate cannot pass on this Windows host: the pinned generator writes CRLF and a double-encoded § into generated files, so its byte-for-byte check reports a difference. A byte comparison after CRLF normalization showed only the same § encoding artifact in models/customer_review_detail.py; no generated file changed in this PR.

Walkthrough

Narrated walkthrough (1:58): https://github.com/thekarannagpal/sdk-python/releases/download/walkthrough-v1/walkthrough.mp4

Proofline review

I installed the Proofline GitHub App on my own fork and used the Proofline CLI on this change. Proofline automatically reviewed the fork PR:

The first review returned 7 warnings. I addressed all of them: cancellation is now checked in the ProoflineError handlers, last is passed into every STOPPED return, backoff uses a monotonic cutoff and event waits instead of 50 ms polling, the README no longer recommends unsafe direct Event.set() from signal handlers or worker threads, and the async read-phase test sets the event with call_soon_threadsafe. Two regression tests were added for the erroring-read and pre-poll races.

The second review returned 0 serious and 5 warning findings. I addressed all five in commit 2bf161a: both event-wait adapters now return whether they woke on the event so backoff stops immediately even if the caller clears the flag; both loops pass the original absolute deadline into backoff instead of reconstructing it from a sampled remaining duration; the poll-interval test now exercises the real sync and async wait helpers and asserts an early wakeup; the README uses the correct loop.add_signal_handler(signal.SIGINT, cancel.set) signature; and the async example no longer leaves a SIGINT handler registered after the wait.

The third review returned 0 serious and 5 warning findings. I addressed all five in commit aeee907: the docstring and README now say cancellation waits for the whole read, including transport retries and retry delays, which count toward the overall deadline; every STOPPED outcome now validates the review identity before carrying it; the backoff test signals cancellation only after the real event wait has started; and a new regression test proves a cancelled read with a mismatched review ID raises the same invalid-response error as the normal path.

The fourth review returned 0 serious and 5 warning findings. I addressed all five in commit f2e4288: the async event wait now uses asyncio.timeout around a direct await event.wait() so external cancellation propagates; the README no longer replaces or removes an application-owned SIGINT handler; the docs now say only ProoflineError is converted to STOPPED during a read while other exceptions propagate; and the backoff test now observes the real event waiter and measures its elapsed wait so it cannot pass without entering backoff.

The fifth review returned 0 serious and 2 warning findings. I addressed both in commit 3167ded: the async event wait now races a dedicated waiter task against the timer, prefers a resolved waiter when the timer fires in the same tick, and cancels and reaps any pending tasks; external cancellation still propagates. The sync backoff test now uses a threading.Event double that signals only after a real waiter has registered and released the condition lock, and the async double likewise signals only after registering a waiter. Two regression tests cover the timer/signal race and external cancellation.

The sixth review returned 0 serious and 4 warning findings. I addressed all four in commit 83c1ac9: the async waiter now latches delivery at the moment cancel_event resolves its waiter, so a set-then-clear cannot be lost and a signal first delivered after the cutoff is ignored; the absolute deadline is enforced in both the backoff race and the final cancellation check; the backoff test supervises the poll and setter tasks together and awaits both during cleanup; and the README no longer claims an unset event adds no wakeups.

The seventh review returned 2 serious and 7 warning findings across the open finding set. I addressed all of them in commit cf1208a: the async waiter now runs event.wait() in a task and races it against an absolute cutoff without inspecting coroutine yields, so asyncio.Event subclasses work; a signal first delivered after the cutoff is ignored without rechecking the raw flag; cancellation is checked immediately after a successful read before the deadline, while the final post-loop check still gives the deadline precedence; the sync setter records registration failures, still signals cancellation, and reports the failure on the test thread; and all poll/setter cleanup happens inside the client and server contexts.

The eighth review returned 0 serious and 7 current warning findings, with one earlier warning still listed as open. I addressed the full set in commit 473696c: _async_wait_for_event() now retrieves and propagates a completed waiter exception and always drains a pending waiter; both sync and async backoff check the absolute deadline after a wakeup so a signal set at or after expiry cannot become STOPPED; the async waiter checks monotonic() against the cutoff before latching delivery; the setter now signals only after real waiter registration, uses a separate teardown event to wake and join it, and starts only after the server and client contexts have been entered; and the late-signal test now holds the helper until the signal has actually reached the waiter before asserting False.

The ninth review returned 0 serious and 6 current warning findings, with the same earlier README warning still listed. I addressed all of them in commit 6c684ea: sync and async waits now record the time the cancellation signal is sent and compare that delivery time with the deadline, so a timely set-then-clear is not lost if the waiter resumes late; async cleanup cancels the waiter and attaches a retrieval callback instead of awaiting a task that may ignore cancellation; the no-event backoff test now fails if either event-wait helper is called; and the late-signal test computes its cutoff first and schedules the signal relative to it.

The tenth review returned 1 serious and 10 warning findings, with one earlier warning still listed. I addressed the full set in commit 7533b73: sync waits now track signal delivery through the event's condition instead of replacing the caller's set, so concurrent waits cannot uninstall each other's wrappers; async waits drive the built-in asyncio.Event.wait() coroutine directly, record delivery on that future, and close it without leaving a pending task or waiter; the controlled-clock tests synchronize signal delivery with helper registration; the real-backoff test uses the full backoff timeout and proves the event woke the wait; and the README now states that retained reviews must pass validation and validation errors propagate even when cancellation is set. The eleventh review has been requested on 7533b73 and is pending.

The automatic Proofline gate on the upstream PR reports that the author needs a seat in prooflinedev’s organization. That is an administrator-side setting in the reviewer’s organization, not something the applicant can change. The real review above was run through the CLI on the fork PR, where the GitHub App is installed and my seat is assigned.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant