Repository navigation
Let callers cancel Python wait_for_review - #111
Open
thekarannagpal wants to merge 22 commits into
Open
thekarannagpal wants to merge 22 commits into
thekarannagpal wants to merge 22 commits into
Conversation
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
wait_for_reviewpolls until a terminal review state or its own timeout. A caller that is shutting down, switching work, or handlingSIGINThad 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 cancelwaitForReviewwith anAbortSignal; the Python SDK had no equivalent.Approach
Added an optional
cancel_eventkeyword 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.reviewstill holds that last record in every cancellation path. Passing the wrong event type raisesTypeErrorbefore 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 singlesleep(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'swait()or binding an unset event to the current loop. Sync waits observe the event's own condition and never assign to the caller'sset(); the deadline starts at method entry, so an event already set at entry stops before any request even withtimeout=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
Before this change there was no
cancel_eventparameter, 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.pynow cover:TypeErrorbefore any request;asyncio.run()calls;asyncio.Eventsubclass with a read-onlysetproperty;set()being observed even whenwait()is inherited;threading.Event.setproperty exposing the standard setter;set()and accepts a getter-only wrapper around the standard setter;timeout=0, while an event already set at entry still returnsSTOPPED;set()dispatch and rearmed afterclear();[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 useloop.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
test_body_stream_deadline_does_not_turn_authority_into_timeout: 311 passed, 4 deselected in 25.72s.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 fullscripts/check.pygeneration 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 inmodels/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
ProoflineErrorhandlers,lastis passed into everySTOPPEDreturn, backoff uses a monotonic cutoff and event waits instead of 50 ms polling, the README no longer recommends unsafe directEvent.set()from signal handlers or worker threads, and the async read-phase test sets the event withcall_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 correctloop.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; everySTOPPEDoutcome 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 usesasyncio.timeoutaround a directawait event.wait()so external cancellation propagates; the README no longer replaces or removes an application-ownedSIGINThandler; the docs now say onlyProoflineErroris converted toSTOPPEDduring 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 athreading.Eventdouble 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 momentcancel_eventresolves 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 runsevent.wait()in a task and races it against an absolute cutoff without inspecting coroutine yields, soasyncio.Eventsubclasses 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 becomeSTOPPED; the async waiter checksmonotonic()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 assertingFalse.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'sset, so concurrent waits cannot uninstall each other's wrappers; async waits drive the built-inasyncio.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 passhead_commit_shathrough 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 overridableis_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 boundwait()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 instancewait()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,DEADLINEis reset in a nestedfinally, 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 drivingwait()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 syncset()is watched even whenwait()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 commit5b3abb4: 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 intry/finally, and exercise condition notification while held. The README clarifies cancellation precedence over head mismatches and queueslambda: cancel.set()across threads. The twentieth review returned 0 serious and 20 warning findings and I addressed all twenty in commitd27e21d: 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 raisingwait()override, and add regressions for each concurrency and timing case. The twenty-first review was INCOMPLETE becauseMODEL_BUDGET_EXHAUSTEDleft 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 commitc8f64b2: sync observation now uses condition hooks instead of replacing the caller'sset(), 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 afterclear(), 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 gateon the upstream PR reports that the author needs a seat inprooflinedev’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.