Skip to content

Let callers cancel Python wait_for_review - #111

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

thekarannagpal wants to merge 22 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 and its retry delays count toward the overall deadline. 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 instead of fixed-interval polling and uses a monotonic cutoff. The async client registers its own waiter directly on the event instead of driving the caller's wait() or binding an unset event to the current loop. Sync waits observe the event's own condition and never assign to the caller's set(); the deadline starts at method entry, so an event already set at entry stops before any request even with timeout=0, while a signal first delivered at or after expiry is ignored. Cancellation must be observable through the supplied event's own flag and condition; changing only a backing object is not enough. A late signal does not suppress a read error or override a head mismatch. 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

The cancellation and event-wait regressions in tests/test_http.py now cover:

  • an already-set event stopping before any request;
  • an event set after the real backoff wait starts stopping without another request;
  • an event observed during a read stopping after retaining that last review;
  • an invalid response still propagating when cancellation is set during the read;
  • an event observed just before the next poll retaining the last review;
  • a cancelled read with a mismatched review ID raising the normal invalid-response error;
  • an invalid event type raising TypeError before any request;
  • set-then-clear delivery being latched before the cutoff and ignored after it;
  • an async event being reusable in two separate asyncio.run() calls;
  • an asyncio.Event subclass with a read-only set property;
  • a backing-only flag change not counting as cancellation because it does not notify waiters;
  • overlapping waits keeping independent waiters and not replacing a caller's setter;
  • timer, waiter, and observer registries being unwound after timeouts, external cancellation, and cleanup failures;
  • one notification being stamped once for every deadline watching that signal;
  • both condition hooks being rolled back when setup fails;
  • sync publication sharing the lock used by the final deadline decision;
  • an overridden sync set() being observed even when wait() is inherited;
  • backing conditions being checked both before and after an active wait;
  • a read-only threading.Event.set property exposing the standard setter;
  • async waiters already bound to a different event loop being rejected before registration;
  • registration waiting for a retiring wrapper to be restored before saving an original;
  • a subscriber added during a setter call not inheriting that set/clear pulse;
  • notification timestamps being sampled before any observer can hold the publication lock;
  • one timestamp being reused for every async observer of the same notification;
  • a set/clear between the post-read check and backoff reusing the read latch;
  • backing notifications being stamped when they occur even if the setter resumes late;
  • cached standard setters continuing to wake backoff through the event condition;
  • later async pulses reaching deadlines registered after an earlier set/clear;
  • one deadline retaining its signal watcher across multiple waiter registrations;
  • one timestamp for every subscriber to the same sync setter notification;
  • an unverified early wake not backdating a flag revealed after the deadline;
  • concurrent loops failing atomically instead of registering foreign waiters;
  • an already-set foreign-loop event being rejected before any request;
  • condition-hook observation that never replaces the caller's set() and accepts a getter-only wrapper around the standard setter;
  • a signal delivered during argument validation being ignored with timeout=0, while an event already set at entry still returns STOPPED;
  • async publication being deduplicated per set() dispatch and rearmed after clear();
  • an unverified async wake keeping its observer armed for a later verified signal;
  • sync publication holding the deadline lock and both condition hooks being restored independently after a failure;
  • the initial async loop-ownership check running under the waiter-registration lock;
  • the unchanged no-event polling delays [5, 10, 20, 40, 60, 60, 60, 5].

Async helper tests use a controlled clock and a helper-specific timer so an asyncio.wait_for() watchdog is not intercepted. Tests that deliver signals from server threads use loop.call_soon_threadsafe. The synchronous real-backoff probe now runs in a terminable subprocess, releases its sender only after the blocking waiter is registered, and the async probe reaps its sender without masking an earlier registration failure. The deadlock and restoration-race probes also use terminable subprocesses so a regression cannot hang the suite.

Results

  • Focused cancellation/event-wait tests: 75 passed, 224 deselected in 5.24s.
  • Full suite excluding the known Windows-only flake test_body_stream_deadline_does_not_turn_authority_into_timeout: 311 passed, 4 deselected in 25.72s.
  • That flake failed in isolation on this run: 1 failed, 3 passed. It had also failed in isolation on the untouched baseline and is unrelated to this change, so it remains excluded from the stable full-suite result.
  • 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.
  • git diff --check — passed.
  • python scripts/check.py --prepare — pinned tools installed and wheel prepared. The full scripts/check.py generation gate still 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:57.93): 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 returned 0 serious and 10 new warning findings (12 open warnings total). I addressed all ten in commit 8fc5117: timer cleanup now covers waiter startup and early flag checks, cancellation and waiter registration are synchronized for plain events, the sync backoff rechecks the cutoff after reading the flag, overridden async waits run as tasks, the sender waits in tests are bounded and always joined, and cancellation paths pass head_commit_sha through so head mismatches keep their normal error behavior.

The twelfth review returned 1 serious and 16 warning findings (1 serious and 21 open warnings total). I addressed all seventeen in commit 2efa007: overridden async waits are raced as complete tasks instead of assuming their first yield is a future, signal recording is synchronized with deadline decisions, invalid-response errors are re-raised before cancellation is considered, and the affected tests wait for real waiter registration and always clean up their senders.

The thirteenth review returned 0 serious and 12 warning findings (23 open warnings total). I addressed all twelve in commit d2ecdac: condition tracking now watches only the supplied event's own condition, each future has one delivery hook with independent deadline subscribers, plain async waiters are registered before yielding, subclass waiter tasks are cancelled and drained, inherited condition methods are restored by removing instance overrides, and invalid-response errors keep their normal deadline handling.

The fourteenth review returned 0 serious and 12 warning findings (25 open warnings total). I addressed all twelve in commit 9388498: nested event notifications no longer count as cancellation, the sync condition is released before calling an overridable is_set(), backing conditions are cleaned up when they change, async subclass signals complete a per-wait future, waiter cleanup cannot block the parent indefinitely, affected tests use controlled clocks, and the async helper guard raises immediately when called synchronously.

The fifteenth review returned 1 serious and 19 warning findings (1 serious and 34 open warnings total). I addressed all twenty in commit 63c2476: the resolved bound wait() method is checked before driving a coroutine, notifications verify the event flag when they arrive, hook installation is inside cleanup coverage, unmanageable overridden waiter tasks are rejected, is_set() is checked before starting the race, test timers and watchdogs are separated, post-read cancellation honors the deadline, and the README clarifies validation and late-signal behavior.

The sixteenth review returned 0 serious and 20 warning findings (41 open warnings total). I addressed all twenty in commit 0e4f110: departing deadlines are unregistered from every tracked future, the resolved instance wait() method decides whether the sync fast path is safe, setter timestamps are taken after the original setter, both condition hooks roll back if setup fails, read-phase cancellation is observed through a waiter, overridden waits are observed without spawning subclass waiter tasks, DEADLINE is reset in a nested finally, and the README documents that late signals are ignored.

The seventeenth review was INCOMPLETE because evidence was unavailable. It listed 0 serious and 8 actionable warning findings (43 open warnings total). I fixed all eight in commit c9753b6: the sync clock is read after the flag, setter hooks timestamp observable delivery rather than setter entry, the docs require a cancellation signal observable on the supplied event, hooks are restored only while still installed, waiter cleanup runs even if restoration raises, notification and publication share the deadline lock, each subscriber validates its own event, and waiter futures are cleaned up when hook installation fails.

The eighteenth review returned 2 serious and 18 warning findings (2 serious and 49 open warnings total). I addressed all twenty in commit 4447440: async observation now registers a future directly on the event instead of driving wait() or binding the caller's event to the loop; read-only setters and standard waiter notification work without replacing the setter; sync publication and the final deadline decision share a reentrant lock; one notification timestamp is reused for every deadline watching that event; both condition hooks roll back independently; registry entries are evicted before restoration and cleanup runs even when restoration raises; overridden sync set() is watched even when wait() is inherited; tests use the real backoff with a watchdog and verify the exact futures registries hold; and both docstrings and the README state that a late signal is ignored and does not suppress an otherwise propagating read error. The nineteenth review returned 2 serious and 18 warning findings (2 serious and 47 open warnings total). I addressed all twenty in commit 5b3abb4: read-only standard setters now rely on the condition observer, async waiters from another loop are rejected before registration, registry removal and method restoration are atomic with registration, notification timestamps are sampled at entry and shared by all observers, setter subscribers are snapshotted before delegation, backing notifications are timestamped when they occur and verified at the next checkpoint, and the post-read and backoff phases share one cancellation latch. The affected tests now use a subprocess for the deadlock probe, release senders only after observers and blocking waiters are ready, bound helper cleanup in try/finally, and exercise condition notification while held. The README clarifies cancellation precedence over head mismatches and queues lambda: cancel.set() across threads. The twentieth review returned 0 serious and 20 warning findings and I addressed all twenty in commit d27e21d: every async notification now reaches the deadlines subscribed at that pulse, deadline registrations are refcounted across read and backoff waiters, registration and waiter removal share the loop-ownership lock, registration is transactional and removes empty event watches on failure, a single timestamp is published for each sync setter notification, and sampled notifications are staged before deadline-lock contention. Backing notifications now verify the caller's flag at delivery, an already-set foreign-loop event is rejected before the early return, and the docs qualify cached setters, cancellation precedence, and async event reuse. The affected tests now use terminable subprocesses for the sync and race probes, release senders only after waiters block, restore the real backoff helper with a raising wait() override, and add regressions for each concurrency and timing case. The twenty-first review was INCOMPLETE because MODEL_BUDGET_EXHAUSTED left an environment assessment unavailable. Its code assessment still returned 2 serious and 22 warning actionable findings (2 serious and 65 open warnings across the accumulated set). I addressed all twenty-four in commit c8f64b2: sync observation now uses condition hooks instead of replacing the caller's set(), event attributes are snapshotted under one lock, subscribers registered during a verified notification are included, publication and the final deadline decision share the deadline lock, backing notifications are treated as hints unless the caller's predicate is verifiable, and both condition hooks restore independently. Async publication is deduplicated per dispatch and rearmed after clear(), an unverified wake keeps its observer armed, the loop-ownership check holds the registration lock, and both methods establish the entry deadline before applying an initial cancellation signal. The README and docstrings now spell out that late signals are ignored, head mismatches follow the deadline, and the SDK never assigns to the caller's setter. The new regressions cover each of these cases, and the deadlock-prone probes remain terminable subprocesses.

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