Repository navigation
Let callers cancel Python wait_for_review - #111
Open
thekarannagpal wants to merge 16 commits into
Open
thekarannagpal wants to merge 16 commits into
thekarannagpal wants to merge 16 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. 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 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
Before this change there was no
cancel_eventparameter, 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:STOPPEDwith the last review;TypeErrorbefore any request;asyncio.Eventsubclass's overriddenwait();setcallbacks are recorded by both sync and async waits;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_COMPLETEDand bounds the helper withasyncio.wait_for(). The async tests setasyncio.Eventthroughloop.call_soon_threadsafewhen 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.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.scripts/check.pygeneration 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 inmodels/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
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 has been requested on7533b73and is pending.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.