From 58205cfef3cd6ca71b995f76cce52fe006270333 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Tue, 24 Nov 2026 22:42:50 +0530 Subject: [PATCH 01/22] Add cancellable wait_for_review polling --- README.md | 28 +++++++++++++++ proofline/client.py | 71 ++++++++++++++++++++++++++++++++++-- tests/test_http.py | 87 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 184 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 721949da..6737632b 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,34 @@ if outcome.status != "COMPLETED": `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +## Cancelling a wait + +Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set the event from another thread, task, or signal handler. + +```python +import threading + +cancel = threading.Event() +outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel) +# From another thread, or from a signal handler: cancel.set() +``` + +```python +import asyncio +import signal + +cancel = asyncio.Event() +loop = asyncio.get_running_loop() +loop.add_signal_handler(signal.SIGINT, cancel.set) +outcome = await async_client.wait_for_review( + organization_id, + review_id, + cancel_event=cancel, +) +``` + +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. An in-flight read is not interrupted; it finishes within the client's configured HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. + ## Review exports `export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`. diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..7fe2126e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,6 +3,8 @@ from __future__ import annotations import math +import threading +from asyncio import Event as AsyncEvent from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from string import hexdigits @@ -189,6 +191,41 @@ def _pagination_limit(resource: str = "Review") -> ProoflineError: ) +_CANCEL_POLL_SECONDS = 0.05 +_CANCEL_REASON = "The wait was cancelled by the caller." + + +def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: + return event is not None and event.is_set() + + +def _sleep_with_cancel(delay: float, event: threading.Event | None) -> bool: + """Sleep in short slices when cancellable; return False once cancelled.""" + if event is None: + sleep(delay) + return True + while delay > 0: + if _cancelled(event): + return False + slice_ = min(delay, _CANCEL_POLL_SECONDS) + sleep(slice_) + delay -= slice_ + return not _cancelled(event) + + +async def _async_sleep_with_cancel(delay: float, event: AsyncEvent | None) -> bool: + if event is None: + await async_sleep(delay) + return True + while delay > 0: + if _cancelled(event): + return False + slice_ = min(delay, _CANCEL_POLL_SECONDS) + await async_sleep(slice_) + delay -= slice_ + return not _cancelled(event) + + def _export_page_limit(max_pages: int) -> None: if isinstance(max_pages, bool) or not isinstance(max_pages, int) or not 1 <= max_pages <= 1_000: raise ValueError("Export pagination requires max_pages 1..1000.") @@ -546,6 +583,7 @@ def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + cancel_event: threading.Event | None = None, ) -> ReviewOutcome: """Wait for recorded review completion or return TIMED_OUT. @@ -554,30 +592,45 @@ def wait_for_review( head_commit_sha holds the outcome to that commit. A review pinned to another head ends the wait on that read and is never COMPLETED. + + cancel_event stops the wait before another request. It is checked before + each poll, during the backoff, and after each read; an in-flight read is + not interrupted and finishes within the client's HTTP timeout. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") _head_commit(head_commit_sha) + if cancel_event is not None and not isinstance(cancel_event, threading.Event): + raise TypeError("cancel_event must be a threading.Event.") url = _review_url(self._base_url, organization_id, review_id) + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) last: CustomerReviewDetail | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) interval = 5.0 try: while (_transport.remaining() or 0) > 0: + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result - sleep(min(interval, _transport.remaining() or 0)) + if not _sleep_with_cancel(min(interval, _transport.remaining() or 0), cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) interval = min(60, interval * 2) + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: @@ -941,29 +994,43 @@ async def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + cancel_event: AsyncEvent | None = None, ) -> ReviewOutcome: if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") _head_commit(head_commit_sha) + if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): + raise TypeError("cancel_event must be an asyncio.Event.") url = _review_url(self._base_url, organization_id, review_id) + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) last: CustomerReviewDetail | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) interval = 5.0 try: while (_transport.remaining() or 0) > 0: + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result - await async_sleep(min(interval, _transport.remaining() or 0)) + if not await _async_sleep_with_cancel( + min(interval, _transport.remaining() or 0), cancel_event + ): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) interval = min(60, interval * 2) + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..76e3f9f5 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1414,6 +1414,93 @@ async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( assert len(server.requests) == 8 +@MODES +async def test_wait_for_review_cancel_event_stops_before_any_request( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + event.set() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert server.requests == [] + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review is None + assert clock.delays == [] + + +@MODES +async def test_wait_for_review_cancel_event_interrupts_poll_interval( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + def sleep(delay: float) -> None: + clock.sleep(delay) + if len(clock.delays) == 1: + event.set() + + monkeypatch.setattr(client_module, "sleep", sleep) + if mode == "async": + + async def async_sleep(delay: float) -> None: + sleep(delay) + await asyncio.sleep(0) + + monkeypatch.setattr(client_module, "async_sleep", async_sleep) + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.review.id == REVIEW + assert clock.delays == [0.05] + + +@MODES +async def test_wait_for_review_cancel_event_stops_after_the_read_that_saw_it( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + def respond(request: Request, index: int) -> Reply: + event.set() + return Reply(body=review("RUNNING")) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.review.id == REVIEW + assert clock.delays == [] + + +@MODES +async def test_wait_for_review_rejects_an_unknown_cancel_event_type( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + with pytest.raises(TypeError, match="cancel_event"): + await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=object() + ) + assert server.requests == [] + + @MODES async def test_retry_after_is_bounded_by_wait_deadline( mode: str, monkeypatch: pytest.MonkeyPatch From cccaa6ac9648c375ba456459bc04448d0dffb050 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Tue, 24 Nov 2026 23:40:53 +0530 Subject: [PATCH 02/22] Address Proofline review feedback on cancellation --- README.md | 7 ++-- proofline/client.py | 66 ++++++++++++++++++++++++---------- tests/test_http.py | 87 ++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 131 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 6737632b..7f549b96 100644 --- a/README.md +++ b/README.md @@ -78,14 +78,14 @@ if outcome.status != "COMPLETED": ## Cancelling a wait -Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set the event from another thread, task, or signal handler. +Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(cancel.set)` when the setter is another thread; `loop.add_signal_handler(cancel.set)` is safe because the callback runs on the loop. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. ```python import threading cancel = threading.Event() outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel) -# From another thread, or from a signal handler: cancel.set() +# From another thread: cancel.set() ``` ```python @@ -100,9 +100,10 @@ outcome = await async_client.wait_for_review( review_id, cancel_event=cancel, ) +# From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. An in-flight read is not interrupted; it finishes within the client's configured HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices, so an unset event adds no extra wakeups. An in-flight read is not interrupted; it finishes within the client's configured HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during an erroring read or just before the next poll. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 7fe2126e..293ace83 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -6,6 +6,7 @@ import threading from asyncio import Event as AsyncEvent from asyncio import sleep as async_sleep +from asyncio import wait_for as async_wait_for from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from string import hexdigits from time import monotonic, sleep @@ -191,7 +192,6 @@ def _pagination_limit(resource: str = "Review") -> ProoflineError: ) -_CANCEL_POLL_SECONDS = 0.05 _CANCEL_REASON = "The wait was cancelled by the caller." @@ -199,31 +199,53 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() -def _sleep_with_cancel(delay: float, event: threading.Event | None) -> bool: - """Sleep in short slices when cancellable; return False once cancelled.""" +def _wait_for_event(event: threading.Event, timeout: float) -> None: + event.wait(timeout) + + +async def _async_wait_for_event(event: AsyncEvent, timeout: float) -> None: + try: + await async_wait_for(event.wait(), timeout) + except TimeoutError: + return + + +def _cancel_end(delay: float, cutoff: float | None) -> float: + end = monotonic() + delay + return min(end, cutoff) if cutoff is not None else end + + +def _sleep_with_cancel( + delay: float, event: threading.Event | None, cutoff: float | None = None +) -> bool: + """Wait on the event until the delay or cutoff, returning False if cancelled.""" if event is None: sleep(delay) return True - while delay > 0: + end = _cancel_end(delay, cutoff) + while True: if _cancelled(event): return False - slice_ = min(delay, _CANCEL_POLL_SECONDS) - sleep(slice_) - delay -= slice_ - return not _cancelled(event) + remaining = end - monotonic() + if remaining <= 0: + return not _cancelled(event) + _wait_for_event(event, remaining) -async def _async_sleep_with_cancel(delay: float, event: AsyncEvent | None) -> bool: +async def _async_sleep_with_cancel( + delay: float, event: AsyncEvent | None, cutoff: float | None = None +) -> bool: if event is None: await async_sleep(delay) return True - while delay > 0: + end = _cancel_end(delay, cutoff) + while True: if _cancelled(event): return False - slice_ = min(delay, _CANCEL_POLL_SECONDS) - await async_sleep(slice_) - delay -= slice_ - return not _cancelled(event) + remaining = end - monotonic() + if remaining <= 0: + return not _cancelled(event) + await _async_wait_for_event(event, remaining) def _export_page_limit(max_pages: int) -> None: @@ -612,10 +634,12 @@ def wait_for_review( try: while (_transport.remaining() or 0) > 0: if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise @@ -626,7 +650,9 @@ def wait_for_review( result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result - if not _sleep_with_cancel(min(interval, _transport.remaining() or 0), cancel_event): + remaining = _transport.remaining() or 0 + cutoff = monotonic() + remaining + if not _sleep_with_cancel(min(interval, remaining), cancel_event, cutoff): return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) interval = min(60, interval * 2) if _cancelled(cancel_event): @@ -1010,10 +1036,12 @@ async def wait_for_review( try: while (_transport.remaining() or 0) > 0: if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: + if _cancelled(cancel_event): + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise @@ -1024,8 +1052,10 @@ async def wait_for_review( result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result + remaining = _transport.remaining() or 0 + cutoff = monotonic() + remaining if not await _async_sleep_with_cancel( - min(interval, _transport.remaining() or 0), cancel_event + min(interval, remaining), cancel_event, cutoff ): return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) interval = min(60, interval * 2) diff --git a/tests/test_http.py b/tests/test_http.py index 76e3f9f5..6f28780d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -117,6 +117,15 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(_transport, "sleep", self.sleep) monkeypatch.setattr(client_module, "async_sleep", self.async_sleep) monkeypatch.setattr(_transport, "async_sleep", self.async_sleep) + monkeypatch.setattr(client_module, "_wait_for_event", self.wait_for_event) + monkeypatch.setattr(client_module, "_async_wait_for_event", self.async_wait_for_event) + + def wait_for_event(self, event: Any, timeout: float) -> None: + self.sleep(timeout) + + async def async_wait_for_event(self, event: Any, timeout: float) -> None: + self.sleep(timeout) + await asyncio.sleep(0) def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -1440,19 +1449,19 @@ async def test_wait_for_review_cancel_event_interrupts_poll_interval( clock = Clock(monkeypatch) event = asyncio.Event() if mode == "async" else threading.Event() - def sleep(delay: float) -> None: - clock.sleep(delay) + def wait_for_event(wait_event: Any, timeout: float) -> None: + clock.sleep(timeout) if len(clock.delays) == 1: event.set() - monkeypatch.setattr(client_module, "sleep", sleep) + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) if mode == "async": - async def async_sleep(delay: float) -> None: - sleep(delay) + async def async_wait_for_event(wait_event: Any, timeout: float) -> None: + wait_for_event(wait_event, timeout) await asyncio.sleep(0) - monkeypatch.setattr(client_module, "async_sleep", async_sleep) + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session(mode, server.url) as client: @@ -1462,7 +1471,7 @@ async def async_sleep(delay: float) -> None: assert len(server.requests) == 1 assert result.status == "STOPPED" assert result.review.id == REVIEW - assert clock.delays == [0.05] + assert clock.delays == [5.0] @MODES @@ -1471,9 +1480,13 @@ async def test_wait_for_review_cancel_event_stops_after_the_read_that_saw_it( ) -> None: clock = Clock(monkeypatch) event = asyncio.Event() if mode == "async" else threading.Event() + loop = asyncio.get_running_loop() if mode == "async" else None def respond(request: Request, index: int) -> Reply: - event.set() + if loop is None: + event.set() + else: + loop.call_soon_threadsafe(event.set) return Reply(body=review("RUNNING")) with Server(respond) as server: @@ -1487,6 +1500,64 @@ def respond(request: Request, index: int) -> Reply: assert clock.delays == [] +@MODES +async def test_wait_for_review_cancel_event_during_erroring_read_keeps_last_record( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + body = review("RUNNING") + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + real_get_review = client.get_review + calls = 0 + + def get_review(*args: Any, **kwargs: Any) -> Any: + nonlocal calls + calls += 1 + if calls == 2: + event.set() + raise ProoflineError(503, "urn:proofline:sdk:test", "boom") + return real_get_review(*args, **kwargs) + + monkeypatch.setattr(client, "get_review", get_review) + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review is not None + assert result.review.id == REVIEW + + +@MODES +async def test_wait_for_review_cancel_before_next_poll_keeps_last_record( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + calls = 0 + + def cancelled(wait_event: Any) -> bool: + nonlocal calls + calls += 1 + return calls == 7 + + monkeypatch.setattr(client_module, "_cancelled", cancelled) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.review is not None + assert result.review.id == REVIEW + assert clock.delays == [5.0] + + @MODES async def test_wait_for_review_rejects_an_unknown_cancel_event_type( mode: str, monkeypatch: pytest.MonkeyPatch From 2bf161ad9777ff81d307cdda53981660520be673 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 00:29:54 +0530 Subject: [PATCH 03/22] Address second Proofline review findings --- README.md | 4 +--- proofline/client.py | 29 ++++++++++++++---------- tests/test_http.py | 55 +++++++++++++++++++++++++-------------------- 3 files changed, 49 insertions(+), 39 deletions(-) diff --git a/README.md b/README.md index 7f549b96..b970c823 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ if outcome.status != "COMPLETED": ## Cancelling a wait -Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(cancel.set)` when the setter is another thread; `loop.add_signal_handler(cancel.set)` is safe because the callback runs on the loop. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. +Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(cancel.set)` when the setter is another thread. If you register a signal handler with `loop.add_signal_handler(signal.SIGINT, cancel.set)`, remove it in a `finally` block with `loop.remove_signal_handler(signal.SIGINT)` so a later Ctrl-C is not swallowed. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. ```python import threading @@ -90,11 +90,9 @@ outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel ```python import asyncio -import signal cancel = asyncio.Event() loop = asyncio.get_running_loop() -loop.add_signal_handler(signal.SIGINT, cancel.set) outcome = await async_client.wait_for_review( organization_id, review_id, diff --git a/proofline/client.py b/proofline/client.py index 293ace83..5860e99f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -199,15 +199,18 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() -def _wait_for_event(event: threading.Event, timeout: float) -> None: - event.wait(timeout) +def _wait_for_event(event: threading.Event, timeout: float) -> bool: + """Return True when the event woke the wait, False when it timed out.""" + return event.wait(timeout) -async def _async_wait_for_event(event: AsyncEvent, timeout: float) -> None: +async def _async_wait_for_event(event: AsyncEvent, timeout: float) -> bool: + """Return True when the event woke the wait, False when it timed out.""" try: await async_wait_for(event.wait(), timeout) + return True except TimeoutError: - return + return False def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -229,7 +232,8 @@ def _sleep_with_cancel( remaining = end - monotonic() if remaining <= 0: return not _cancelled(event) - _wait_for_event(event, remaining) + if _wait_for_event(event, remaining): + return False async def _async_sleep_with_cancel( @@ -245,7 +249,8 @@ async def _async_sleep_with_cancel( remaining = end - monotonic() if remaining <= 0: return not _cancelled(event) - await _async_wait_for_event(event, remaining) + if await _async_wait_for_event(event, remaining): + return False def _export_page_limit(max_pages: int) -> None: @@ -629,7 +634,8 @@ def wait_for_review( if _cancelled(cancel_event): return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) last: CustomerReviewDetail | None = None - deadline = _transport.DEADLINE.set(monotonic() + timeout) + deadline_at = monotonic() + timeout + deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 try: while (_transport.remaining() or 0) > 0: @@ -651,8 +657,7 @@ def wait_for_review( if result is not None: return result remaining = _transport.remaining() or 0 - cutoff = monotonic() + remaining - if not _sleep_with_cancel(min(interval, remaining), cancel_event, cutoff): + if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) interval = min(60, interval * 2) if _cancelled(cancel_event): @@ -1031,7 +1036,8 @@ async def wait_for_review( if _cancelled(cancel_event): return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) last: CustomerReviewDetail | None = None - deadline = _transport.DEADLINE.set(monotonic() + timeout) + deadline_at = monotonic() + timeout + deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 try: while (_transport.remaining() or 0) > 0: @@ -1053,9 +1059,8 @@ async def wait_for_review( if result is not None: return result remaining = _transport.remaining() or 0 - cutoff = monotonic() + remaining if not await _async_sleep_with_cancel( - min(interval, remaining), cancel_event, cutoff + min(interval, remaining), cancel_event, deadline_at ): return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) interval = min(60, interval * 2) diff --git a/tests/test_http.py b/tests/test_http.py index 6f28780d..bc4710dd 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -120,12 +120,14 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(client_module, "_wait_for_event", self.wait_for_event) monkeypatch.setattr(client_module, "_async_wait_for_event", self.async_wait_for_event) - def wait_for_event(self, event: Any, timeout: float) -> None: + def wait_for_event(self, event: Any, timeout: float) -> bool: self.sleep(timeout) + return bool(event.is_set()) - async def async_wait_for_event(self, event: Any, timeout: float) -> None: + async def async_wait_for_event(self, event: Any, timeout: float) -> bool: self.sleep(timeout) await asyncio.sleep(0) + return bool(event.is_set()) def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -1443,35 +1445,40 @@ async def test_wait_for_review_cancel_event_stops_before_any_request( @MODES -async def test_wait_for_review_cancel_event_interrupts_poll_interval( - mode: str, monkeypatch: pytest.MonkeyPatch -) -> None: - clock = Clock(monkeypatch) - event = asyncio.Event() if mode == "async" else threading.Event() +async def test_wait_for_review_cancel_event_wakes_real_backoff(mode: str) -> None: + body = review("RUNNING") + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + thread: threading.Thread | None = None + if mode == "sync": + event: Any = threading.Event() - def wait_for_event(wait_event: Any, timeout: float) -> None: - clock.sleep(timeout) - if len(clock.delays) == 1: + def set_event() -> None: + time.sleep(0.05) event.set() - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - if mode == "async": - - async def async_wait_for_event(wait_event: Any, timeout: float) -> None: - wait_for_event(wait_event, timeout) - await asyncio.sleep(0) + thread = threading.Thread(target=set_event, daemon=True) + thread.start() + else: + event = asyncio.Event() + asyncio.get_running_loop().call_later(0.05, event.set) - monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) + started = time.monotonic() + try: + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert len(server.requests) == 1 + finally: + if thread is not None: + thread.join() + elapsed = time.monotonic() - started - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session(mode, server.url) as client: - result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event - ) - assert len(server.requests) == 1 + assert elapsed < 2.0 assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." assert result.review.id == REVIEW - assert clock.delays == [5.0] @MODES From aeee907c42f2afafac4673c20fd94478ce2bd72b Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 01:24:17 +0530 Subject: [PATCH 04/22] Address third Proofline review findings --- README.md | 2 +- proofline/client.py | 39 +++++++++++++++++----------- tests/test_http.py | 62 ++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 84 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index b970c823..fb27835b 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices, so an unset event adds no extra wakeups. An in-flight read is not interrupted; it finishes within the client's configured HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during an erroring read or just before the next poll. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices, so an unset event adds no extra wakeups. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during an erroring read or just before the next poll. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 5860e99f..0c6fa6ce 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -78,7 +78,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient -from .outcomes import ReviewOutcome, outcome +from .outcomes import ReviewOutcome, _validate, outcome T = TypeVar("T") AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 @@ -199,6 +199,13 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() +def _stopped(url: str, last: CustomerReviewDetail | None, review_id: UUID) -> ReviewOutcome: + """Build a STOPPED outcome, validating any review it carries.""" + if last is not None: + _validate(last, review_id) + return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + + def _wait_for_event(event: threading.Event, timeout: float) -> bool: """Return True when the event woke the wait, False when it timed out.""" return event.wait(timeout) @@ -621,8 +628,10 @@ def wait_for_review( another head ends the wait on that read and is never COMPLETED. cancel_event stops the wait before another request. It is checked before - each poll, during the backoff, and after each read; an in-flight read is - not interrupted and finishes within the client's HTTP timeout. + each poll, during the backoff, and after each read. An in-flight read is + not interrupted: cancellation waits for that read to finish, including + transport retries and their delays. Those delays count toward the overall + wait deadline rather than a single HTTP timeout. """ if not math.isfinite(timeout) or timeout < 0: @@ -632,7 +641,7 @@ def wait_for_review( raise TypeError("cancel_event must be a threading.Event.") url = _review_url(self._base_url, organization_id, review_id) if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) + return _stopped(url, None, review_id) last: CustomerReviewDetail | None = None deadline_at = monotonic() + timeout deadline = _transport.DEADLINE.set(deadline_at) @@ -640,17 +649,17 @@ def wait_for_review( try: while (_transport.remaining() or 0) > 0: if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) @@ -658,10 +667,10 @@ def wait_for_review( return result remaining = _transport.remaining() or 0 if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) interval = min(60, interval * 2) if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: @@ -1034,7 +1043,7 @@ async def wait_for_review( raise TypeError("cancel_event must be an asyncio.Event.") url = _review_url(self._base_url, organization_id, review_id) if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) + return _stopped(url, None, review_id) last: CustomerReviewDetail | None = None deadline_at = monotonic() + timeout deadline = _transport.DEADLINE.set(deadline_at) @@ -1042,17 +1051,17 @@ async def wait_for_review( try: while (_transport.remaining() or 0) > 0: if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) @@ -1062,10 +1071,10 @@ async def wait_for_review( if not await _async_sleep_with_cancel( min(interval, remaining), cancel_event, deadline_at ): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) interval = min(60, interval * 2) if _cancelled(cancel_event): - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) + return _stopped(url, last, review_id) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: diff --git a/tests/test_http.py b/tests/test_http.py index bc4710dd..00c1c399 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1445,22 +1445,48 @@ async def test_wait_for_review_cancel_event_stops_before_any_request( @MODES -async def test_wait_for_review_cancel_event_wakes_real_backoff(mode: str) -> None: +async def test_wait_for_review_cancel_event_wakes_real_backoff( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: body = review("RUNNING") body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) thread: threading.Thread | None = None + task: asyncio.Task[None] | None = None + entered: Any + if mode == "sync": event: Any = threading.Event() + entered = threading.Event() + real_wait = client_module._wait_for_event + + def wait_for_event(wait_event: Any, timeout: float) -> bool: + entered.set() + return real_wait(wait_event, timeout) + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) def set_event() -> None: - time.sleep(0.05) + assert entered.wait(2.0) event.set() thread = threading.Thread(target=set_event, daemon=True) thread.start() else: event = asyncio.Event() - asyncio.get_running_loop().call_later(0.05, event.set) + entered = asyncio.Event() + real_async_wait = client_module._async_wait_for_event + + async def async_wait_for_event(wait_event: Any, timeout: float) -> bool: + entered.set() + return await real_async_wait(wait_event, timeout) + + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) + + async def set_event() -> None: + await asyncio.wait_for(entered.wait(), 2.0) + event.set() + + task = asyncio.create_task(set_event()) started = time.monotonic() try: @@ -1473,8 +1499,11 @@ def set_event() -> None: finally: if thread is not None: thread.join() + if task is not None: + task.cancel() elapsed = time.monotonic() - started + assert entered.is_set() assert elapsed < 2.0 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." @@ -1507,6 +1536,33 @@ def respond(request: Request, index: int) -> Reply: assert clock.delays == [] +@MODES +async def test_wait_for_review_cancelled_read_rejects_wrong_review_id( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + loop = asyncio.get_running_loop() if mode == "async" else None + body = review("RUNNING") + body["id"] = str(UUID(int=1)) + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + + def respond(request: Request, index: int) -> Reply: + if loop is None: + event.set() + else: + loop.call_soon_threadsafe(event.set) + return Reply(body=body) + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert "invalid identity" in raised.value.detail + assert len(server.requests) == 1 + + @MODES async def test_wait_for_review_cancel_event_during_erroring_read_keeps_last_record( mode: str, monkeypatch: pytest.MonkeyPatch From f2e4288189a64a74ac3b97ae7d0973c658894678 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 02:15:43 +0530 Subject: [PATCH 05/22] Address fourth Proofline review findings --- README.md | 4 ++-- proofline/client.py | 5 +++-- tests/test_http.py | 55 ++++++++++++++++++++++++++++++++------------- 3 files changed, 45 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index fb27835b..78305e15 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ if outcome.status != "COMPLETED": ## Cancelling a wait -Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(cancel.set)` when the setter is another thread. If you register a signal handler with `loop.add_signal_handler(signal.SIGINT, cancel.set)`, remove it in a `finally` block with `loop.remove_signal_handler(signal.SIGINT)` so a later Ctrl-C is not swallowed. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. +Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(cancel.set)` when the setter is another thread. If your application already owns `SIGINT` handling, route cancellation through that handler instead of replacing it with `loop.add_signal_handler`. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. ```python import threading @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices, so an unset event adds no extra wakeups. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during an erroring read or just before the next poll. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices, so an unset event adds no extra wakeups. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 0c6fa6ce..cfa58965 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -6,7 +6,7 @@ import threading from asyncio import Event as AsyncEvent from asyncio import sleep as async_sleep -from asyncio import wait_for as async_wait_for +from asyncio import timeout as async_timeout from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from string import hexdigits from time import monotonic, sleep @@ -214,7 +214,8 @@ def _wait_for_event(event: threading.Event, timeout: float) -> bool: async def _async_wait_for_event(event: AsyncEvent, timeout: float) -> bool: """Return True when the event woke the wait, False when it timed out.""" try: - await async_wait_for(event.wait(), timeout) + async with async_timeout(timeout): + await event.wait() return True except TimeoutError: return False diff --git a/tests/test_http.py b/tests/test_http.py index 00c1c399..54130527 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1452,43 +1452,68 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) thread: threading.Thread | None = None task: asyncio.Task[None] | None = None - entered: Any + wait_elapsed: list[float] = [] + event: Any if mode == "sync": - event: Any = threading.Event() - entered = threading.Event() + + class SignallingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.waiter_registered = threading.Event() + + def wait(self, timeout: float | None = None) -> bool: + self.waiter_registered.set() + return super().wait(timeout) + + event = SignallingEvent() real_wait = client_module._wait_for_event def wait_for_event(wait_event: Any, timeout: float) -> bool: - entered.set() - return real_wait(wait_event, timeout) + started = time.monotonic() + try: + return real_wait(wait_event, timeout) + finally: + wait_elapsed.append(time.monotonic() - started) monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) def set_event() -> None: - assert entered.wait(2.0) + assert event.waiter_registered.wait(10.0) event.set() thread = threading.Thread(target=set_event, daemon=True) thread.start() else: - event = asyncio.Event() - entered = asyncio.Event() + + class SignallingEventAsync(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.waiter_registered = asyncio.Event() + + async def wait(self) -> None: + waiter = asyncio.ensure_future(super().wait()) + self.waiter_registered.set() + await waiter + + event = SignallingEventAsync() real_async_wait = client_module._async_wait_for_event async def async_wait_for_event(wait_event: Any, timeout: float) -> bool: - entered.set() - return await real_async_wait(wait_event, timeout) + started = time.monotonic() + try: + return await real_async_wait(wait_event, timeout) + finally: + wait_elapsed.append(time.monotonic() - started) monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) async def set_event() -> None: - await asyncio.wait_for(entered.wait(), 2.0) + await asyncio.wait_for(event.waiter_registered.wait(), 10.0) event.set() task = asyncio.create_task(set_event()) - started = time.monotonic() try: with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: @@ -1501,10 +1526,10 @@ async def set_event() -> None: thread.join() if task is not None: task.cancel() - elapsed = time.monotonic() - started - assert entered.is_set() - assert elapsed < 2.0 + assert event.waiter_registered.is_set() + assert wait_elapsed + assert wait_elapsed[0] < 2.0 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." assert result.review.id == REVIEW From 3167ded64cbb7868971bb10196aaffc7e2c6284f Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 03:08:20 +0530 Subject: [PATCH 06/22] Address fifth Proofline review findings --- proofline/client.py | 25 ++++++++-- tests/test_http.py | 116 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 131 insertions(+), 10 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index cfa58965..85b9354c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -4,9 +4,12 @@ import math import threading +from asyncio import FIRST_COMPLETED from asyncio import Event as AsyncEvent +from asyncio import create_task as async_create_task +from asyncio import gather as async_gather from asyncio import sleep as async_sleep -from asyncio import timeout as async_timeout +from asyncio import wait as async_wait from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from string import hexdigits from time import monotonic, sleep @@ -213,12 +216,24 @@ def _wait_for_event(event: threading.Event, timeout: float) -> bool: async def _async_wait_for_event(event: AsyncEvent, timeout: float) -> bool: """Return True when the event woke the wait, False when it timed out.""" + waiter = async_create_task(event.wait()) + timer = async_create_task(async_sleep(timeout)) try: - async with async_timeout(timeout): - await event.wait() - return True - except TimeoutError: + await async_wait((waiter, timer), return_when=FIRST_COMPLETED) + if not waiter.done(): + # A set event can resolve its waiter just as the timer fires. Let + # that already-scheduled waiter finish before treating it as a + # timeout, so a set-then-clear signal is not lost. + await async_sleep(0) + if waiter.done(): + return waiter.result() return False + finally: + pending = [task for task in (waiter, timer) if not task.done()] + for task in pending: + task.cancel() + if pending: + await async_gather(*pending, return_exceptions=True) def _cancel_end(delay: float, cutoff: float | None) -> float: diff --git a/tests/test_http.py b/tests/test_http.py index 54130527..1052282b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1425,6 +1425,65 @@ async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( assert len(server.requests) == 8 +async def test_async_wait_for_event_prefers_resolved_waiter_when_timer_wins( + monkeypatch: pytest.MonkeyPatch, +) -> None: + loop = asyncio.get_running_loop() + real_sleep = asyncio.sleep + timer_gate: asyncio.Future[None] = loop.create_future() + + async def fake_sleep(delay: float) -> None: + if delay == 0: + await real_sleep(0) + else: + await timer_gate + + monkeypatch.setattr(client_module, "async_sleep", fake_sleep) + + class GatedEvent: + def __init__(self) -> None: + self._flag = False + self._waiter: asyncio.Future[bool] = loop.create_future() + + def is_set(self) -> bool: + return self._flag + + def set(self) -> None: + self._flag = True + if not self._waiter.done(): + self._waiter.set_result(True) + + def clear(self) -> None: + self._flag = False + + async def wait(self) -> bool: + result = await self._waiter + self._waiter = loop.create_future() + return result + + event = GatedEvent() + task = asyncio.create_task(client_module._async_wait_for_event(event, 5)) + await real_sleep(0) + + # The timer wins, then the signal arrives and is cleared before the event + # waiter resumes. The resolved waiter must still beat the timeout. + timer_gate.set_result(None) + await real_sleep(0) + event.set() + event.clear() + + assert await asyncio.wait_for(task, 1.0) is True + + +async def test_async_wait_for_event_propagates_external_cancellation() -> None: + event = asyncio.Event() + task = asyncio.create_task(client_module._async_wait_for_event(event, 10)) + await asyncio.sleep(0) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + @MODES async def test_wait_for_review_cancel_event_stops_before_any_request( mode: str, monkeypatch: pytest.MonkeyPatch @@ -1458,13 +1517,45 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( if mode == "sync": class SignallingEvent(threading.Event): + """A threading.Event that exposes real waiter registration.""" + def __init__(self) -> None: super().__init__() + self._condition = threading.Condition(threading.Lock()) + self._waiters = 0 self.waiter_registered = threading.Event() + def is_set(self) -> bool: + with self._condition: + return self._flag + + def set(self) -> None: + with self._condition: + self._flag = True + self._condition.notify_all() + + def clear(self) -> None: + with self._condition: + self._flag = False + def wait(self, timeout: float | None = None) -> bool: - self.waiter_registered.set() - return super().wait(timeout) + deadline = None if timeout is None else time.monotonic() + timeout + with self._condition: + if self._flag: + return True + self._waiters += 1 + # Setting this under the condition lock means set() cannot + # run until this waiter has released the lock in wait(). + self.waiter_registered.set() + try: + while not self._flag: + remaining = None if deadline is None else deadline - time.monotonic() + if remaining is not None and remaining <= 0: + return False + self._condition.wait(remaining) + return True + finally: + self._waiters -= 1 event = SignallingEvent() real_wait = client_module._wait_for_event @@ -1487,14 +1578,29 @@ def set_event() -> None: else: class SignallingEventAsync(asyncio.Event): + """An Event double that signals once it has a registered waiter.""" + def __init__(self) -> None: super().__init__() self.waiter_registered = asyncio.Event() + self._registered: set[asyncio.Future[bool]] = set() - async def wait(self) -> None: - waiter = asyncio.ensure_future(super().wait()) + async def wait(self) -> bool: + if self.is_set(): + return True + waiter = asyncio.get_running_loop().create_future() + self._registered.add(waiter) self.waiter_registered.set() - await waiter + try: + return await waiter + finally: + self._registered.discard(waiter) + + def set(self) -> None: + super().set() + for waiter in tuple(self._registered): + if not waiter.done(): + waiter.set_result(True) event = SignallingEventAsync() real_async_wait = client_module._async_wait_for_event From 83c1ac917d58a7959c5ae7fd1c5ddbbd53bd3bf6 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 12:31:48 +0530 Subject: [PATCH 07/22] Address sixth Proofline review findings --- README.md | 2 +- proofline/client.py | 66 +++++++++++++++++++------------- tests/test_http.py | 92 ++++++++++++++++++--------------------------- 3 files changed, 77 insertions(+), 83 deletions(-) diff --git a/README.md b/README.md index 78305e15..1cc2e8f6 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices, so an unset event adds no extra wakeups. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 85b9354c..cdd27a9b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -4,10 +4,8 @@ import math import threading -from asyncio import FIRST_COMPLETED from asyncio import Event as AsyncEvent -from asyncio import create_task as async_create_task -from asyncio import gather as async_gather +from asyncio import Future as AsyncFuture from asyncio import sleep as async_sleep from asyncio import wait as async_wait from collections.abc import AsyncIterator, Awaitable, Callable, Iterator @@ -214,26 +212,40 @@ def _wait_for_event(event: threading.Event, timeout: float) -> bool: return event.wait(timeout) -async def _async_wait_for_event(event: AsyncEvent, timeout: float) -> bool: - """Return True when the event woke the wait, False when it timed out.""" - waiter = async_create_task(event.wait()) - timer = async_create_task(async_sleep(timeout)) +async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: + """Return True when the event is delivered before cutoff, False on timeout.""" + waiter = event.wait() + future: AsyncFuture[bool] | None = None + finished = False + delivered = False try: - await async_wait((waiter, timer), return_when=FIRST_COMPLETED) - if not waiter.done(): - # A set event can resolve its waiter just as the timer fires. Let - # that already-scheduled waiter finish before treating it as a - # timeout, so a set-then-clear signal is not lost. - await async_sleep(0) - if waiter.done(): - return waiter.result() + try: + future = waiter.send(None) + except StopIteration as stop: + finished = True + return bool(stop.value) and monotonic() <= cutoff + + original_set_result = future.set_result + + def set_result(result: bool) -> None: + nonlocal delivered + if monotonic() <= cutoff: + delivered = True + original_set_result(result) + + future.set_result = set_result # type: ignore[method-assign] + + await async_wait((future,), timeout=max(0.0, cutoff - monotonic())) + if delivered and future.done() and not future.cancelled(): + try: + waiter.send(None) + except StopIteration as stop: + finished = True + return bool(stop.value) return False finally: - pending = [task for task in (waiter, timer) if not task.done()] - for task in pending: - task.cancel() - if pending: - await async_gather(*pending, return_exceptions=True) + if not finished: + waiter.close() def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -272,7 +284,7 @@ async def _async_sleep_with_cancel( remaining = end - monotonic() if remaining <= 0: return not _cancelled(event) - if await _async_wait_for_event(event, remaining): + if await _async_wait_for_event(event, end): return False @@ -674,10 +686,10 @@ def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if _cancelled(cancel_event): - return _stopped(url, last, review_id) if (_transport.remaining() or 0) <= 0: break + if _cancelled(cancel_event): + return _stopped(url, last, review_id) result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result @@ -685,7 +697,7 @@ def wait_for_review( if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): return _stopped(url, last, review_id) interval = min(60, interval * 2) - if _cancelled(cancel_event): + if (_transport.remaining() or 0) > 0 and _cancelled(cancel_event): return _stopped(url, last, review_id) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) @@ -1076,10 +1088,10 @@ async def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if _cancelled(cancel_event): - return _stopped(url, last, review_id) if (_transport.remaining() or 0) <= 0: break + if _cancelled(cancel_event): + return _stopped(url, last, review_id) result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result @@ -1089,7 +1101,7 @@ async def wait_for_review( ): return _stopped(url, last, review_id) interval = min(60, interval * 2) - if _cancelled(cancel_event): + if (_transport.remaining() or 0) > 0 and _cancelled(cancel_event): return _stopped(url, last, review_id) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) diff --git a/tests/test_http.py b/tests/test_http.py index 1052282b..c18b64f9 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -124,8 +124,8 @@ def wait_for_event(self, event: Any, timeout: float) -> bool: self.sleep(timeout) return bool(event.is_set()) - async def async_wait_for_event(self, event: Any, timeout: float) -> bool: - self.sleep(timeout) + async def async_wait_for_event(self, event: Any, cutoff: float) -> bool: + self.sleep(max(0.0, cutoff - self.now)) await asyncio.sleep(0) return bool(event.is_set()) @@ -1425,59 +1425,21 @@ async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( assert len(server.requests) == 8 -async def test_async_wait_for_event_prefers_resolved_waiter_when_timer_wins( - monkeypatch: pytest.MonkeyPatch, -) -> None: - loop = asyncio.get_running_loop() - real_sleep = asyncio.sleep - timer_gate: asyncio.Future[None] = loop.create_future() - - async def fake_sleep(delay: float) -> None: - if delay == 0: - await real_sleep(0) - else: - await timer_gate - - monkeypatch.setattr(client_module, "async_sleep", fake_sleep) - - class GatedEvent: - def __init__(self) -> None: - self._flag = False - self._waiter: asyncio.Future[bool] = loop.create_future() - - def is_set(self) -> bool: - return self._flag - - def set(self) -> None: - self._flag = True - if not self._waiter.done(): - self._waiter.set_result(True) - - def clear(self) -> None: - self._flag = False - - async def wait(self) -> bool: - result = await self._waiter - self._waiter = loop.create_future() - return result +async def test_async_wait_for_event_latches_a_set_then_clear() -> None: + event = asyncio.Event() + asyncio.get_running_loop().call_later(0.01, lambda: (event.set(), event.clear())) + assert await client_module._async_wait_for_event(event, time.monotonic() + 1.0) is True - event = GatedEvent() - task = asyncio.create_task(client_module._async_wait_for_event(event, 5)) - await real_sleep(0) - # The timer wins, then the signal arrives and is cleared before the event - # waiter resumes. The resolved waiter must still beat the timeout. - timer_gate.set_result(None) - await real_sleep(0) +async def test_async_wait_for_event_ignores_a_signal_after_cutoff() -> None: + event = asyncio.Event() + assert await client_module._async_wait_for_event(event, time.monotonic() - 1.0) is False event.set() - event.clear() - - assert await asyncio.wait_for(task, 1.0) is True async def test_async_wait_for_event_propagates_external_cancellation() -> None: event = asyncio.Event() - task = asyncio.create_task(client_module._async_wait_for_event(event, 10)) + task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) await asyncio.sleep(0) task.cancel() with pytest.raises(asyncio.CancelledError): @@ -1511,6 +1473,7 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) thread: threading.Thread | None = None task: asyncio.Task[None] | None = None + poll_task: asyncio.Task[Any] | None = None wait_elapsed: list[float] = [] event: Any @@ -1605,10 +1568,10 @@ def set(self) -> None: event = SignallingEventAsync() real_async_wait = client_module._async_wait_for_event - async def async_wait_for_event(wait_event: Any, timeout: float) -> bool: + async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: started = time.monotonic() try: - return await real_async_wait(wait_event, timeout) + return await real_async_wait(wait_event, cutoff) finally: wait_elapsed.append(time.monotonic() - started) @@ -1623,15 +1586,34 @@ async def set_event() -> None: try: with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: - result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event - ) + if task is None: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + else: + poll_task = asyncio.create_task( + call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + cancel_event=event, + ) + ) + await asyncio.wait((poll_task, task), return_when=asyncio.FIRST_COMPLETED) + await task + result = await asyncio.wait_for(poll_task, 5.0) assert len(server.requests) == 1 finally: if thread is not None: thread.join() - if task is not None: - task.cancel() + supervised = [item for item in (poll_task, task) if item is not None] + for item in supervised: + if not item.done(): + item.cancel() + if supervised: + await asyncio.gather(*supervised, return_exceptions=True) assert event.waiter_registered.is_set() assert wait_elapsed From cf1208ab7d525f3086e4e39b686f61fe89ab7c6b Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 12:40:34 +0530 Subject: [PATCH 08/22] Address seventh Proofline review findings --- proofline/client.py | 68 +++++++++++++++++---------------- tests/test_http.py | 93 +++++++++++++++++++++++++++++---------------- 2 files changed, 96 insertions(+), 65 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index cdd27a9b..801854b3 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -4,8 +4,12 @@ import math import threading +from asyncio import FIRST_COMPLETED from asyncio import Event as AsyncEvent from asyncio import Future as AsyncFuture +from asyncio import create_task as async_create_task +from asyncio import gather as async_gather +from asyncio import get_running_loop as async_get_running_loop from asyncio import sleep as async_sleep from asyncio import wait as async_wait from collections.abc import AsyncIterator, Awaitable, Callable, Iterator @@ -214,38 +218,34 @@ def _wait_for_event(event: threading.Event, timeout: float) -> bool: async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: """Return True when the event is delivered before cutoff, False on timeout.""" - waiter = event.wait() - future: AsyncFuture[bool] | None = None - finished = False + loop = async_get_running_loop() + timer: AsyncFuture[None] = loop.create_future() delivered = False + expired = False + + def expire() -> None: + nonlocal expired + expired = True + if not timer.done(): + timer.set_result(None) + + handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), expire) + + async def wait_for_signal() -> None: + nonlocal delivered + await event.wait() + if not expired: + delivered = True + + waiter = async_create_task(wait_for_signal()) try: - try: - future = waiter.send(None) - except StopIteration as stop: - finished = True - return bool(stop.value) and monotonic() <= cutoff - - original_set_result = future.set_result - - def set_result(result: bool) -> None: - nonlocal delivered - if monotonic() <= cutoff: - delivered = True - original_set_result(result) - - future.set_result = set_result # type: ignore[method-assign] - - await async_wait((future,), timeout=max(0.0, cutoff - monotonic())) - if delivered and future.done() and not future.cancelled(): - try: - waiter.send(None) - except StopIteration as stop: - finished = True - return bool(stop.value) - return False + await async_wait((waiter, timer), return_when=FIRST_COMPLETED) + return delivered finally: - if not finished: - waiter.close() + handle.cancel() + if not waiter.done(): + waiter.cancel() + await async_gather(waiter, return_exceptions=True) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -286,6 +286,8 @@ async def _async_sleep_with_cancel( return not _cancelled(event) if await _async_wait_for_event(event, end): return False + if monotonic() >= end: + return True def _export_page_limit(max_pages: int) -> None: @@ -686,10 +688,10 @@ def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if (_transport.remaining() or 0) <= 0: - break if _cancelled(cancel_event): return _stopped(url, last, review_id) + if (_transport.remaining() or 0) <= 0: + break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result @@ -1088,10 +1090,10 @@ async def wait_for_review( if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if (_transport.remaining() or 0) <= 0: - break if _cancelled(cancel_event): return _stopped(url, last, review_id) + if (_transport.remaining() or 0) <= 0: + break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result diff --git a/tests/test_http.py b/tests/test_http.py index c18b64f9..c21e8d06 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1433,8 +1433,19 @@ async def test_async_wait_for_event_latches_a_set_then_clear() -> None: async def test_async_wait_for_event_ignores_a_signal_after_cutoff() -> None: event = asyncio.Event() - assert await client_module._async_wait_for_event(event, time.monotonic() - 1.0) is False - event.set() + asyncio.get_running_loop().call_later(0.02, event.set) + assert await client_module._async_wait_for_event(event, time.monotonic() + 0.01) is False + + +async def test_async_wait_for_event_accepts_subclass_that_yields_none() -> None: + class YieldingEvent(asyncio.Event): + async def wait(self) -> bool: + await asyncio.sleep(0) + return await super().wait() + + event = YieldingEvent() + asyncio.get_running_loop().call_later(0.01, event.set) + assert await client_module._async_wait_for_event(event, time.monotonic() + 1.0) is True async def test_async_wait_for_event_propagates_external_cancellation() -> None: @@ -1475,6 +1486,7 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( task: asyncio.Task[None] | None = None poll_task: asyncio.Task[Any] | None = None wait_elapsed: list[float] = [] + failures: list[BaseException] = [] event: Any if mode == "sync": @@ -1533,7 +1545,8 @@ def wait_for_event(wait_event: Any, timeout: float) -> bool: monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) def set_event() -> None: - assert event.waiter_registered.wait(10.0) + if not event.waiter_registered.wait(10.0): + failures.append(AssertionError("waiter registration timed out")) event.set() thread = threading.Thread(target=set_event, daemon=True) @@ -1586,34 +1599,39 @@ async def set_event() -> None: try: with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: - if task is None: - result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event - ) - else: - poll_task = asyncio.create_task( - call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=100, - cancel_event=event, + try: + if task is None: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event ) - ) - await asyncio.wait((poll_task, task), return_when=asyncio.FIRST_COMPLETED) - await task - result = await asyncio.wait_for(poll_task, 5.0) + else: + poll_task = asyncio.create_task( + call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + cancel_event=event, + ) + ) + await asyncio.wait((poll_task, task), return_when=asyncio.FIRST_COMPLETED) + await task + result = await asyncio.wait_for(poll_task, 5.0) + finally: + supervised = [item for item in (poll_task, task) if item is not None] + for item in supervised: + if not item.done(): + item.cancel() + if supervised: + await asyncio.gather(*supervised, return_exceptions=True) assert len(server.requests) == 1 finally: if thread is not None: thread.join() - supervised = [item for item in (poll_task, task) if item is not None] - for item in supervised: - if not item.done(): - item.cancel() - if supervised: - await asyncio.gather(*supervised, return_exceptions=True) + + if failures: + raise failures[0] assert event.waiter_registered.is_set() assert wait_elapsed @@ -1714,14 +1732,25 @@ async def test_wait_for_review_cancel_before_next_poll_keeps_last_record( ) -> None: clock = Clock(monkeypatch) event = asyncio.Event() if mode == "async" else threading.Event() - calls = 0 - def cancelled(wait_event: Any) -> bool: - nonlocal calls - calls += 1 - return calls == 7 + if mode == "async": + + async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: + clock.sleep(max(0.0, cutoff - clock.now)) + wait_event.set() + await asyncio.sleep(0) + return False + + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) + else: + + def wait_for_event(wait_event: Any, timeout: float) -> bool: + clock.sleep(timeout) + wait_event.set() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - monkeypatch.setattr(client_module, "_cancelled", cancelled) with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session(mode, server.url) as client: result = await call( From 473696ca53c33ddd4a8e36e4a7671a541a20115f Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 12:52:56 +0530 Subject: [PATCH 09/22] Address eighth Proofline review findings --- proofline/client.py | 15 ++-- tests/test_http.py | 189 +++++++++++++++++++++++++++++++++----------- 2 files changed, 154 insertions(+), 50 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 801854b3..0ba5416c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -234,18 +234,20 @@ def expire() -> None: async def wait_for_signal() -> None: nonlocal delivered await event.wait() - if not expired: + if not expired and monotonic() <= cutoff: delivered = True waiter = async_create_task(wait_for_signal()) try: await async_wait((waiter, timer), return_when=FIRST_COMPLETED) + if waiter.done(): + waiter.result() return delivered finally: handle.cancel() if not waiter.done(): waiter.cancel() - await async_gather(waiter, return_exceptions=True) + await async_gather(waiter, return_exceptions=True) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -262,12 +264,13 @@ def _sleep_with_cancel( return True end = _cancel_end(delay, cutoff) while True: + if monotonic() >= end: + return True if _cancelled(event): return False - remaining = end - monotonic() - if remaining <= 0: - return not _cancelled(event) - if _wait_for_event(event, remaining): + if _wait_for_event(event, end - monotonic()): + if monotonic() >= end: + return True return False diff --git a/tests/test_http.py b/tests/test_http.py index c21e8d06..7a257a9e 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1431,10 +1431,48 @@ async def test_async_wait_for_event_latches_a_set_then_clear() -> None: assert await client_module._async_wait_for_event(event, time.monotonic() + 1.0) is True -async def test_async_wait_for_event_ignores_a_signal_after_cutoff() -> None: - event = asyncio.Event() +async def test_async_wait_for_event_ignores_a_signal_after_cutoff( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_async_wait = client_module.async_wait + late_signal_delivered = False + + # Keep the helper alive until the late signal has reached the waiter task, + # so this test cannot pass merely because the helper returned too early. + async def wait_for_both(aws: Any, **kwargs: Any) -> Any: + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await real_async_wait(aws, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", wait_for_both) + + class RecordingEvent(asyncio.Event): + async def wait(self) -> bool: + nonlocal late_signal_delivered + result = await super().wait() + late_signal_delivered = True + return result + + event = RecordingEvent() asyncio.get_running_loop().call_later(0.02, event.set) assert await client_module._async_wait_for_event(event, time.monotonic() + 0.01) is False + assert late_signal_delivered is True + + +def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + + def wait_for_event(wait_event: Any, timeout: float) -> bool: + clock.sleep(timeout) + wait_event.set() + return True + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + assert clock.delays == [1.0] async def test_async_wait_for_event_accepts_subclass_that_yields_none() -> None: @@ -1448,6 +1486,15 @@ async def wait(self) -> bool: assert await client_module._async_wait_for_event(event, time.monotonic() + 1.0) is True +async def test_async_wait_for_event_propagates_waiter_exception() -> None: + class FailingEvent(asyncio.Event): + async def wait(self) -> bool: + raise RuntimeError("wait failed") + + with pytest.raises(RuntimeError, match="wait failed"): + await client_module._async_wait_for_event(FailingEvent(), time.monotonic() + 1.0) + + async def test_async_wait_for_event_propagates_external_cancellation() -> None: event = asyncio.Event() task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) @@ -1488,6 +1535,8 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( wait_elapsed: list[float] = [] failures: list[BaseException] = [] event: Any + release: Any + abort: Any if mode == "sync": @@ -1533,24 +1582,37 @@ def wait(self, timeout: float | None = None) -> bool: self._waiters -= 1 event = SignallingEvent() + release = threading.Event() + abort = threading.Event() real_wait = client_module._wait_for_event def wait_for_event(wait_event: Any, timeout: float) -> bool: started = time.monotonic() + deadline = started + timeout try: - return real_wait(wait_event, timeout) + while True: + if abort.is_set(): + raise failures[0] + remaining = deadline - time.monotonic() + if remaining <= 0: + return False + if real_wait(wait_event, min(remaining, 0.01)): + return True finally: wait_elapsed.append(time.monotonic() - started) monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) def set_event() -> None: - if not event.waiter_registered.wait(10.0): - failures.append(AssertionError("waiter registration timed out")) - event.set() - - thread = threading.Thread(target=set_event, daemon=True) - thread.start() + deadline = time.monotonic() + 10.0 + while not event.waiter_registered.is_set() and not release.is_set(): + if time.monotonic() >= deadline: + failures.append(AssertionError("waiter registration timed out")) + abort.set() + return + release.wait(0.01) + if not release.is_set() and event.waiter_registered.is_set(): + event.set() else: class SignallingEventAsync(asyncio.Event): @@ -1579,56 +1641,95 @@ def set(self) -> None: waiter.set_result(True) event = SignallingEventAsync() + release = asyncio.Event() + abort = asyncio.Event() real_async_wait = client_module._async_wait_for_event async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: started = time.monotonic() try: - return await real_async_wait(wait_event, cutoff) + if abort.is_set(): + raise failures[0] + wait_task = asyncio.create_task(real_async_wait(wait_event, cutoff)) + abort_task = asyncio.create_task(abort.wait()) + try: + await asyncio.wait((wait_task, abort_task), return_when=asyncio.FIRST_COMPLETED) + if abort_task.done(): + raise failures[0] + return wait_task.result() + finally: + supervised = (wait_task, abort_task) + for item in supervised: + if not item.done(): + item.cancel() + await asyncio.gather(*supervised, return_exceptions=True) finally: wait_elapsed.append(time.monotonic() - started) monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) async def set_event() -> None: - await asyncio.wait_for(event.waiter_registered.wait(), 10.0) - event.set() - - task = asyncio.create_task(set_event()) + registration = asyncio.create_task(event.waiter_registered.wait()) + teardown = asyncio.create_task(release.wait()) + try: + await asyncio.wait( + (registration, teardown), + timeout=10.0, + return_when=asyncio.FIRST_COMPLETED, + ) + if release.is_set(): + return + if not registration.done(): + failures.append(AssertionError("waiter registration timed out")) + abort.set() + return + event.set() + finally: + for item in (registration, teardown): + if not item.done(): + item.cancel() + await asyncio.gather(registration, teardown, return_exceptions=True) - try: - with Server(lambda request, index: Reply(body=body)) as server: - async with session(mode, server.url) as client: - try: - if task is None: - result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event - ) - else: - poll_task = asyncio.create_task( - call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=100, - cancel_event=event, - ) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + try: + if mode == "sync": + thread = threading.Thread(target=set_event, daemon=True) + thread.start() + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + else: + poll_task = asyncio.create_task( + call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + cancel_event=event, ) - await asyncio.wait((poll_task, task), return_when=asyncio.FIRST_COMPLETED) + ) + task = asyncio.create_task(set_event()) + await asyncio.wait((poll_task, task), return_when=asyncio.FIRST_COMPLETED) + if task.done(): await task + if failures: + raise failures[0] result = await asyncio.wait_for(poll_task, 5.0) - finally: - supervised = [item for item in (poll_task, task) if item is not None] - for item in supervised: - if not item.done(): - item.cancel() - if supervised: - await asyncio.gather(*supervised, return_exceptions=True) - assert len(server.requests) == 1 - finally: - if thread is not None: - thread.join() + else: + result = poll_task.result() + finally: + release.set() + if thread is not None: + thread.join() + supervised = [item for item in (poll_task, task) if item is not None] + for item in supervised: + if not item.done(): + item.cancel() + if supervised: + await asyncio.gather(*supervised, return_exceptions=True) + assert len(server.requests) == 1 if failures: raise failures[0] From 6c684eadb4d83d5968cfdf96be44768740fe2c36 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 13:04:39 +0530 Subject: [PATCH 10/22] Address ninth Proofline review findings --- proofline/client.py | 72 +++++++++++++++++++++++++++-------- tests/test_http.py | 93 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 148 insertions(+), 17 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 0ba5416c..1ff5f80f 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -8,7 +8,6 @@ from asyncio import Event as AsyncEvent from asyncio import Future as AsyncFuture from asyncio import create_task as async_create_task -from asyncio import gather as async_gather from asyncio import get_running_loop as async_get_running_loop from asyncio import sleep as async_sleep from asyncio import wait as async_wait @@ -217,15 +216,27 @@ def _wait_for_event(event: threading.Event, timeout: float) -> bool: async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: - """Return True when the event is delivered before cutoff, False on timeout.""" + """Return True when the event is signalled before cutoff, False on timeout.""" loop = async_get_running_loop() timer: AsyncFuture[None] = loop.create_future() - delivered = False - expired = False + delivered = event.is_set() and monotonic() < cutoff + original_set: Any = None + wrapped_set = False + try: + original_set = event.set + + def set_with_delivery_time() -> None: + nonlocal delivered + if monotonic() < cutoff: + delivered = True + original_set() + + event.set = set_with_delivery_time # type: ignore[method-assign] + wrapped_set = True + except (AttributeError, TypeError): + pass def expire() -> None: - nonlocal expired - expired = True if not timer.done(): timer.set_result(None) @@ -234,10 +245,17 @@ def expire() -> None: async def wait_for_signal() -> None: nonlocal delivered await event.wait() - if not expired and monotonic() <= cutoff: + # A subclass may complete its waiter directly instead of through set(). + if not delivered and monotonic() < cutoff: delivered = True waiter = async_create_task(wait_for_signal()) + + def retrieve(task: Any) -> None: + if not task.cancelled(): + task.exception() + + waiter.add_done_callback(retrieve) try: await async_wait((waiter, timer), return_when=FIRST_COMPLETED) if waiter.done(): @@ -245,9 +263,10 @@ async def wait_for_signal() -> None: return delivered finally: handle.cancel() + if wrapped_set: + event.set = original_set # type: ignore[method-assign] if not waiter.done(): waiter.cancel() - await async_gather(waiter, return_exceptions=True) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -263,15 +282,38 @@ def _sleep_with_cancel( sleep(delay) return True end = _cancel_end(delay, cutoff) - while True: - if monotonic() >= end: - return True - if _cancelled(event): - return False - if _wait_for_event(event, end - monotonic()): + signalled_at: float | None = None + original_set: Any = None + wrapped_set = False + try: + original_set = event.set + + def set_with_delivery_time() -> None: + nonlocal signalled_at + now = monotonic() + if signalled_at is None and now < end: + signalled_at = now + original_set() + + event.set = set_with_delivery_time # type: ignore[method-assign] + wrapped_set = True + except (AttributeError, TypeError): + pass + try: + while True: + if signalled_at is not None: + return False if monotonic() >= end: return True - return False + if _cancelled(event): + return False + if _wait_for_event(event, end - monotonic()): + if signalled_at is not None: + return False + return True + finally: + if wrapped_set: + event.set = original_set # type: ignore[method-assign] async def _async_sleep_with_cancel( diff --git a/tests/test_http.py b/tests/test_http.py index 7a257a9e..2dbd7d86 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1408,6 +1408,16 @@ async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( clock = Clock(monkeypatch) body = review("RUNNING") body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + + def unexpected_event_wait(*args: Any, **kwargs: Any) -> bool: + raise AssertionError("event wait called without cancel_event") + + async def unexpected_async_event_wait(*args: Any, **kwargs: Any) -> bool: + raise AssertionError("async event wait called without cancel_event") + + monkeypatch.setattr(client_module, "_wait_for_event", unexpected_event_wait) + monkeypatch.setattr(client_module, "_async_wait_for_event", unexpected_async_event_wait) + with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0) @@ -1453,11 +1463,73 @@ async def wait(self) -> bool: return result event = RecordingEvent() - asyncio.get_running_loop().call_later(0.02, event.set) - assert await client_module._async_wait_for_event(event, time.monotonic() + 0.01) is False + cutoff = time.monotonic() + 0.01 + delay = max(0.0, cutoff - time.monotonic()) + 0.01 + + def send_late_signal() -> None: + event.set() + + asyncio.get_running_loop().call_later(delay, send_late_signal) + assert await client_module._async_wait_for_event(event, cutoff) is False assert late_signal_delivered is True +async def test_async_wait_for_event_latches_delivery_before_a_late_resume() -> None: + class SlowResumeEvent(asyncio.Event): + async def wait(self) -> bool: + result = await super().wait() + await asyncio.sleep(0.1) + return result + + event = SlowResumeEvent() + cutoff = time.monotonic() + 0.05 + delay = max(0.0, cutoff - time.monotonic()) / 2 + + def send_early_signal() -> None: + event.set() + + asyncio.get_running_loop().call_later(delay, send_early_signal) + assert await client_module._async_wait_for_event(event, cutoff) is True + + +async def test_async_wait_for_event_does_not_join_a_persistent_waiter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class PersistentEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.stop = False + + async def wait(self) -> bool: + try: + await super().wait() + except asyncio.CancelledError: + while not self.stop: + await asyncio.sleep(0.01) + return False + + created: list[asyncio.Task[Any]] = [] + real_create_task = client_module.async_create_task + + def create_task(coro: Any) -> asyncio.Task[Any]: + task = real_create_task(coro) + created.append(task) + return task + + monkeypatch.setattr(client_module, "async_create_task", create_task) + + event = PersistentEvent() + task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 0.01)) + try: + assert await asyncio.wait_for(task, 1.0) is False + finally: + event.stop = True + for item in created: + item.cancel() + if created: + await asyncio.gather(*created, return_exceptions=True) + + def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -1475,6 +1547,23 @@ def wait_for_event(wait_event: Any, timeout: float) -> bool: assert clock.delays == [1.0] +def test_sleep_with_cancel_latches_delivery_before_a_late_resume( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + + def wait_for_event(wait_event: Any, timeout: float) -> bool: + wait_event.set() + clock.sleep(timeout) + return True + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert clock.delays == [1.0] + + async def test_async_wait_for_event_accepts_subclass_that_yields_none() -> None: class YieldingEvent(asyncio.Event): async def wait(self) -> bool: From 7533b7347504ead1e3ad0388817f99e32475d666 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 13:36:45 +0530 Subject: [PATCH 11/22] Address tenth Proofline review findings --- README.md | 2 +- proofline/client.py | 154 +++++++++++++++---------- tests/test_http.py | 274 +++++++++++++++++++++++++++----------------- 3 files changed, 266 insertions(+), 164 deletions(-) diff --git a/README.md b/README.md index 1cc2e8f6..1cd86613 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors propagate even when cancellation is set. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 1ff5f80f..932e343d 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,9 +5,9 @@ import math import threading from asyncio import FIRST_COMPLETED +from asyncio import CancelledError as AsyncCancelledError from asyncio import Event as AsyncEvent from asyncio import Future as AsyncFuture -from asyncio import create_task as async_create_task from asyncio import get_running_loop as async_get_running_loop from asyncio import sleep as async_sleep from asyncio import wait as async_wait @@ -199,6 +199,65 @@ def _pagination_limit(resource: str = "Review") -> ProoflineError: _CANCEL_REASON = "The wait was cancelled by the caller." +class _SignalDeadline: + def __init__(self, end: float) -> None: + self.end = end + self.signalled_at: float | None = None + + def record(self, now: float) -> None: + if self.signalled_at is None and now < self.end: + self.signalled_at = now + + +class _NotifyAllTracker: + def __init__(self, condition: Any) -> None: + self.condition = condition + self.original = condition.notify_all + self.deadlines: set[_SignalDeadline] = set() + condition.notify_all = self.notify_all + + def notify_all(self) -> None: + now = monotonic() + with _notify_lock: + deadlines = tuple(self.deadlines) + for deadline in deadlines: + deadline.record(now) + self.original() + + +_notify_lock = threading.Lock() +_notify_trackers: dict[int, _NotifyAllTracker] = {} + + +def _track_thread_signal(event: threading.Event, end: float) -> _SignalDeadline: + deadline = _SignalDeadline(end) + condition = getattr(event, "_cond", None) + if not isinstance(condition, threading.Condition): + return deadline + key = id(condition) + with _notify_lock: + tracker = _notify_trackers.get(key) + if tracker is None: + tracker = _NotifyAllTracker(condition) + _notify_trackers[key] = tracker + tracker.deadlines.add(deadline) + return deadline + + +def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: + condition = getattr(event, "_cond", None) + if not isinstance(condition, threading.Condition): + return + with _notify_lock: + tracker = _notify_trackers.get(id(condition)) + if tracker is None: + return + tracker.deadlines.discard(deadline) + if not tracker.deadlines: + tracker.condition.notify_all = tracker.original + del _notify_trackers[id(condition)] + + def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() @@ -220,53 +279,47 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: loop = async_get_running_loop() timer: AsyncFuture[None] = loop.create_future() delivered = event.is_set() and monotonic() < cutoff - original_set: Any = None - wrapped_set = False - try: - original_set = event.set - - def set_with_delivery_time() -> None: - nonlocal delivered - if monotonic() < cutoff: - delivered = True - original_set() - - event.set = set_with_delivery_time # type: ignore[method-assign] - wrapped_set = True - except (AttributeError, TypeError): - pass + handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) - def expire() -> None: - if not timer.done(): - timer.set_result(None) + # Drive the built-in Event.wait coroutine so subclasses cannot override the + # wait primitive or leave a task behind when they suppress cancellation. + waiter = AsyncEvent.wait(event) + try: + future = cast(AsyncFuture[bool], waiter.send(None)) + except StopIteration as stop: + handle.cancel() + return bool(stop.value) and monotonic() < cutoff - handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), expire) + original_set_result = future.set_result - async def wait_for_signal() -> None: + def set_result(result: bool) -> None: nonlocal delivered - await event.wait() - # A subclass may complete its waiter directly instead of through set(). - if not delivered and monotonic() < cutoff: + if monotonic() < cutoff: delivered = True + original_set_result(result) - waiter = async_create_task(wait_for_signal()) - - def retrieve(task: Any) -> None: - if not task.cancelled(): - task.exception() - - waiter.add_done_callback(retrieve) + future.set_result = set_result # type: ignore[method-assign] + resumed = False try: - await async_wait((waiter, timer), return_when=FIRST_COMPLETED) - if waiter.done(): - waiter.result() + await async_wait((future, timer), return_when=FIRST_COMPLETED) + if future.done() and not future.cancelled(): + try: + waiter.send(None) + except StopIteration: + pass + resumed = True return delivered finally: handle.cancel() - if wrapped_set: - event.set = original_set # type: ignore[method-assign] - if not waiter.done(): - waiter.cancel() + future.set_result = original_set_result # type: ignore[method-assign] + if not resumed: + if not future.done(): + future.cancel() + try: + waiter.throw(AsyncCancelledError()) + except (StopIteration, AsyncCancelledError): + pass + waiter.close() def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -282,38 +335,21 @@ def _sleep_with_cancel( sleep(delay) return True end = _cancel_end(delay, cutoff) - signalled_at: float | None = None - original_set: Any = None - wrapped_set = False - try: - original_set = event.set - - def set_with_delivery_time() -> None: - nonlocal signalled_at - now = monotonic() - if signalled_at is None and now < end: - signalled_at = now - original_set() - - event.set = set_with_delivery_time # type: ignore[method-assign] - wrapped_set = True - except (AttributeError, TypeError): - pass + deadline = _track_thread_signal(event, end) try: while True: - if signalled_at is not None: + if deadline.signalled_at is not None: return False if monotonic() >= end: return True if _cancelled(event): return False if _wait_for_event(event, end - monotonic()): - if signalled_at is not None: + if deadline.signalled_at is not None: return False return True finally: - if wrapped_set: - event.set = original_set # type: ignore[method-assign] + _untrack_thread_signal(event, deadline) async def _async_sleep_with_cancel( diff --git a/tests/test_http.py b/tests/test_http.py index 2dbd7d86..fa9d60bd 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -106,6 +106,11 @@ async def collect(client: Client, **kwargs: Any) -> list[Any]: return list(iterator) +async def wait_for_all(aws: Any, **kwargs: Any) -> Any: + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await asyncio.wait(aws, **kwargs) + + class Clock: def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 @@ -1435,99 +1440,128 @@ async def unexpected_async_event_wait(*args: Any, **kwargs: Any) -> bool: assert len(server.requests) == 8 -async def test_async_wait_for_event_latches_a_set_then_clear() -> None: +async def test_async_wait_for_event_latches_a_set_then_clear( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() + + async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: + registered.set() + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await asyncio.wait(aws, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) event = asyncio.Event() - asyncio.get_running_loop().call_later(0.01, lambda: (event.set(), event.clear())) - assert await client_module._async_wait_for_event(event, time.monotonic() + 1.0) is True + cutoff = clock.now + 0.01 + + async def send_signal() -> None: + await registered.wait() + event.set() + event.clear() + clock.now = cutoff + 1.0 + + sender = asyncio.create_task(send_signal()) + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await sender async def test_async_wait_for_event_ignores_a_signal_after_cutoff( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_async_wait = client_module.async_wait - late_signal_delivered = False + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() + observed: list[Any] = [] - # Keep the helper alive until the late signal has reached the waiter task, - # so this test cannot pass merely because the helper returned too early. - async def wait_for_both(aws: Any, **kwargs: Any) -> Any: + async def wait_for_all_and_record(aws: Any, **kwargs: Any) -> Any: + observed.append(aws) + registered.set() kwargs["return_when"] = asyncio.ALL_COMPLETED - return await real_async_wait(aws, **kwargs) + return await asyncio.wait(aws, **kwargs) - monkeypatch.setattr(client_module, "async_wait", wait_for_both) - - class RecordingEvent(asyncio.Event): - async def wait(self) -> bool: - nonlocal late_signal_delivered - result = await super().wait() - late_signal_delivered = True - return result + monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_record) - event = RecordingEvent() - cutoff = time.monotonic() + 0.01 - delay = max(0.0, cutoff - time.monotonic()) + 0.01 + event = asyncio.Event() + cutoff = clock.now + 0.01 + signal_sent = False - def send_late_signal() -> None: + async def send_late_signal() -> None: + nonlocal signal_sent + await registered.wait() + clock.now = cutoff + 1.0 event.set() + signal_sent = True - asyncio.get_running_loop().call_later(delay, send_late_signal) - assert await client_module._async_wait_for_event(event, cutoff) is False - assert late_signal_delivered is True + sender = asyncio.create_task(send_late_signal()) + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False + await sender + assert signal_sent is True + assert any(item.done() for item in observed[0]) -async def test_async_wait_for_event_latches_delivery_before_a_late_resume() -> None: - class SlowResumeEvent(asyncio.Event): - async def wait(self) -> bool: - result = await super().wait() - await asyncio.sleep(0.1) - return result +async def test_async_wait_for_event_latches_delivery_before_a_late_resume( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() - event = SlowResumeEvent() - cutoff = time.monotonic() + 0.05 - delay = max(0.0, cutoff - time.monotonic()) / 2 + async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: + registered.set() + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await asyncio.wait(aws, **kwargs) - def send_early_signal() -> None: + monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + event = asyncio.Event() + cutoff = clock.now + 0.01 + + async def send_signal() -> None: + await registered.wait() event.set() + clock.now = cutoff + 1.0 - asyncio.get_running_loop().call_later(delay, send_early_signal) - assert await client_module._async_wait_for_event(event, cutoff) is True + sender = asyncio.create_task(send_signal()) + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await sender -async def test_async_wait_for_event_does_not_join_a_persistent_waiter( +async def test_async_wait_for_event_ignores_subclass_wait_overrides( monkeypatch: pytest.MonkeyPatch, ) -> None: - class PersistentEvent(asyncio.Event): + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() + + async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: + registered.set() + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await asyncio.wait(aws, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + + class OverriddenEvent(asyncio.Event): def __init__(self) -> None: super().__init__() - self.stop = False + self.wait_calls = 0 async def wait(self) -> bool: - try: - await super().wait() - except asyncio.CancelledError: - while not self.stop: - await asyncio.sleep(0.01) - return False - - created: list[asyncio.Task[Any]] = [] - real_create_task = client_module.async_create_task + self.wait_calls += 1 + raise RuntimeError("subclass wait must not be used") - def create_task(coro: Any) -> asyncio.Task[Any]: - task = real_create_task(coro) - created.append(task) - return task + event = OverriddenEvent() + cutoff = clock.now + 0.01 - monkeypatch.setattr(client_module, "async_create_task", create_task) + async def send_signal() -> None: + await registered.wait() + event.set() + clock.now = cutoff + 1.0 - event = PersistentEvent() - task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 0.01)) - try: - assert await asyncio.wait_for(task, 1.0) is False - finally: - event.stop = True - for item in created: - item.cancel() - if created: - await asyncio.gather(*created, return_exceptions=True) + sender = asyncio.create_task(send_signal()) + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await sender + assert event.wait_calls == 0 def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( @@ -1564,24 +1598,69 @@ def wait_for_event(wait_event: Any, timeout: float) -> bool: assert clock.delays == [1.0] -async def test_async_wait_for_event_accepts_subclass_that_yields_none() -> None: - class YieldingEvent(asyncio.Event): - async def wait(self) -> bool: - await asyncio.sleep(0) - return await super().wait() +def test_sleep_with_cancel_records_a_captured_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + setter = event.set - event = YieldingEvent() - asyncio.get_running_loop().call_later(0.01, event.set) - assert await client_module._async_wait_for_event(event, time.monotonic() + 1.0) is True + def wait_for_event(wait_event: Any, timeout: float) -> bool: + setter() + clock.sleep(timeout) + return True + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) -async def test_async_wait_for_event_propagates_waiter_exception() -> None: - class FailingEvent(asyncio.Event): - async def wait(self) -> bool: - raise RuntimeError("wait failed") + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert clock.delays == [1.0] + + +async def test_async_wait_for_event_records_a_captured_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() + + async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: + registered.set() + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await asyncio.wait(aws, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + event = asyncio.Event() + setter = event.set + cutoff = clock.now + 0.01 + + async def send_signal() -> None: + await registered.wait() + setter() + clock.now = cutoff + 1.0 - with pytest.raises(RuntimeError, match="wait failed"): - await client_module._async_wait_for_event(FailingEvent(), time.monotonic() + 1.0) + sender = asyncio.create_task(send_signal()) + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await sender + + +def test_sleep_with_cancel_does_not_replace_the_event_setter() -> None: + event = threading.Event() + setter = event.set + condition = event._cond + notify_all = condition.notify_all + + assert client_module._sleep_with_cancel(0, event) is True + assert event.set == setter + assert condition.notify_all == notify_all + + +async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: + event = asyncio.Event() + setter = event.set + + assert await client_module._async_wait_for_event(event, time.monotonic() - 1.0) is False + assert event.set == setter + assert not event._waiters async def test_async_wait_for_event_propagates_external_cancellation() -> None: @@ -1622,6 +1701,7 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( task: asyncio.Task[None] | None = None poll_task: asyncio.Task[Any] | None = None wait_elapsed: list[float] = [] + wait_results: list[bool] = [] failures: list[BaseException] = [] event: Any release: Any @@ -1677,16 +1757,12 @@ def wait(self, timeout: float | None = None) -> bool: def wait_for_event(wait_event: Any, timeout: float) -> bool: started = time.monotonic() - deadline = started + timeout try: - while True: - if abort.is_set(): - raise failures[0] - remaining = deadline - time.monotonic() - if remaining <= 0: - return False - if real_wait(wait_event, min(remaining, 0.01)): - return True + woke = real_wait(wait_event, timeout) + wait_results.append(woke) + if abort.is_set() and failures: + raise failures[0] + return woke finally: wait_elapsed.append(time.monotonic() - started) @@ -1697,6 +1773,7 @@ def set_event() -> None: while not event.waiter_registered.is_set() and not release.is_set(): if time.monotonic() >= deadline: failures.append(AssertionError("waiter registration timed out")) + event.set() abort.set() return release.wait(0.01) @@ -1705,29 +1782,15 @@ def set_event() -> None: else: class SignallingEventAsync(asyncio.Event): - """An Event double that signals once it has a registered waiter.""" + """An Event double that signals once the built-in wait registers.""" def __init__(self) -> None: super().__init__() self.waiter_registered = asyncio.Event() - self._registered: set[asyncio.Future[bool]] = set() - async def wait(self) -> bool: - if self.is_set(): - return True - waiter = asyncio.get_running_loop().create_future() - self._registered.add(waiter) + def _get_loop(self) -> Any: self.waiter_registered.set() - try: - return await waiter - finally: - self._registered.discard(waiter) - - def set(self) -> None: - super().set() - for waiter in tuple(self._registered): - if not waiter.done(): - waiter.set_result(True) + return super()._get_loop() event = SignallingEventAsync() release = asyncio.Event() @@ -1745,7 +1808,9 @@ async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: await asyncio.wait((wait_task, abort_task), return_when=asyncio.FIRST_COMPLETED) if abort_task.done(): raise failures[0] - return wait_task.result() + result = wait_task.result() + wait_results.append(result) + return result finally: supervised = (wait_task, abort_task) for item in supervised: @@ -1826,6 +1891,7 @@ async def set_event() -> None: assert event.waiter_registered.is_set() assert wait_elapsed assert wait_elapsed[0] < 2.0 + assert wait_results[0] is True assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." assert result.review.id == REVIEW From 8fc51171dc9447cb81834c4b2e13a33f47f5689b Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 13:55:16 +0530 Subject: [PATCH 12/22] Address eleventh Proofline review findings --- README.md | 2 +- proofline/client.py | 261 +++++++++++++++++++++++++++++--------------- tests/test_http.py | 177 ++++++++++++++++++++++++++---- 3 files changed, 332 insertions(+), 108 deletions(-) diff --git a/README.md b/README.md index 1cd86613..89f7cdef 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors propagate even when cancellation is set. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 932e343d..be02fc49 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -82,7 +82,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient -from .outcomes import ReviewOutcome, _validate, outcome +from .outcomes import ReviewOutcome, outcome T = TypeVar("T") AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 @@ -203,123 +203,202 @@ class _SignalDeadline: def __init__(self, end: float) -> None: self.end = end self.signalled_at: float | None = None + self.conditions: tuple[threading.Condition, ...] = () def record(self, now: float) -> None: if self.signalled_at is None and now < self.end: self.signalled_at = now -class _NotifyAllTracker: - def __init__(self, condition: Any) -> None: +class _ConditionSignalTracker: + def __init__(self, condition: threading.Condition) -> None: self.condition = condition - self.original = condition.notify_all + self.original_notify_all = condition.notify_all + self.original_notify = condition.notify self.deadlines: set[_SignalDeadline] = set() - condition.notify_all = self.notify_all + condition.notify_all = self.notify_all # type: ignore[method-assign] + condition.notify = self.notify # type: ignore[method-assign] - def notify_all(self) -> None: + def record(self) -> None: now = monotonic() with _notify_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: deadline.record(now) - self.original() + + def notify_all(self) -> None: + self.record() + self.original_notify_all() + + def notify(self, *args: Any, **kwargs: Any) -> None: + self.record() + self.original_notify(*args, **kwargs) _notify_lock = threading.Lock() -_notify_trackers: dict[int, _NotifyAllTracker] = {} +_notify_trackers: dict[int, _ConditionSignalTracker] = {} + +def _thread_conditions(event: threading.Event) -> tuple[threading.Condition, ...]: + conditions: list[threading.Condition] = [] + seen: set[int] = set() + candidates = [getattr(event, "_cond", None), *vars(event).values()] + for candidate in candidates: + if isinstance(candidate, threading.Condition) and id(candidate) not in seen: + seen.add(id(candidate)) + conditions.append(candidate) + return tuple(conditions) -def _track_thread_signal(event: threading.Event, end: float) -> _SignalDeadline: - deadline = _SignalDeadline(end) - condition = getattr(event, "_cond", None) - if not isinstance(condition, threading.Condition): - return deadline - key = id(condition) + +def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: + deadline.conditions = _thread_conditions(event) with _notify_lock: - tracker = _notify_trackers.get(key) - if tracker is None: - tracker = _NotifyAllTracker(condition) - _notify_trackers[key] = tracker - tracker.deadlines.add(deadline) + for condition in deadline.conditions: + key = id(condition) + tracker = _notify_trackers.get(key) + if tracker is None: + tracker = _ConditionSignalTracker(condition) + _notify_trackers[key] = tracker + tracker.deadlines.add(deadline) return deadline def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: - condition = getattr(event, "_cond", None) - if not isinstance(condition, threading.Condition): - return with _notify_lock: - tracker = _notify_trackers.get(id(condition)) - if tracker is None: - return - tracker.deadlines.discard(deadline) - if not tracker.deadlines: - tracker.condition.notify_all = tracker.original - del _notify_trackers[id(condition)] + for condition in deadline.conditions: + key = id(condition) + tracker = _notify_trackers.get(key) + if tracker is None: + continue + tracker.deadlines.discard(deadline) + if not tracker.deadlines: + tracker.condition.notify_all = tracker.original_notify_all # type: ignore[method-assign] + tracker.condition.notify = tracker.original_notify # type: ignore[method-assign] + del _notify_trackers[key] def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() -def _stopped(url: str, last: CustomerReviewDetail | None, review_id: UUID) -> ReviewOutcome: - """Build a STOPPED outcome, validating any review it carries.""" - if last is not None: - _validate(last, review_id) - return ReviewOutcome("STOPPED", url, last, reason=_CANCEL_REASON) +def _stopped( + url: str, + last: CustomerReviewDetail | None, + review_id: UUID, + head_commit_sha: str | None = None, +) -> ReviewOutcome: + """Build a STOPPED outcome, validating any review and keeping its gaps.""" + if last is None: + return ReviewOutcome("STOPPED", url, reason=_CANCEL_REASON) + result = outcome( + last, + url, + "STOPPED", + review_id=review_id, + head_commit_sha=head_commit_sha, + ) + assert result is not None + return ReviewOutcome("STOPPED", url, last, result.gaps, _CANCEL_REASON) -def _wait_for_event(event: threading.Event, timeout: float) -> bool: +def _wait_for_event( + event: threading.Event, timeout: float, deadline: _SignalDeadline | None = None +) -> bool: """Return True when the event woke the wait, False when it timed out.""" - return event.wait(timeout) + if deadline is None: + return event.wait(timeout) + conditions = deadline.conditions + if conditions: + # Install the tracker and check the flag under the same condition lock, + # so a set/clear between the check and waiter registration is recorded. + with conditions[0]: + _track_thread_signal(event, deadline) + if deadline.signalled_at is not None: + return True + if getattr(event, "_flag", False) is True: + deadline.record(monotonic()) + return True + now = monotonic() + remaining = min(timeout, deadline.end - now) + if remaining <= 0: + return False + woke = event.wait(remaining) + if woke and deadline.signalled_at is None: + # A subclass may notify through a primitive we cannot observe. A + # successful wait is evidence that its signal reached the wait primitive + # after this call began, which is before the absolute cutoff. + deadline.record(now) + return woke async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: """Return True when the event is signalled before cutoff, False on timeout.""" loop = async_get_running_loop() + if monotonic() >= cutoff: + return False timer: AsyncFuture[None] = loop.create_future() - delivered = event.is_set() and monotonic() < cutoff handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) - - # Drive the built-in Event.wait coroutine so subclasses cannot override the - # wait primitive or leave a task behind when they suppress cancellation. - waiter = AsyncEvent.wait(event) + delivered = event.is_set() and monotonic() < cutoff + waiter: Any = None + future: AsyncFuture[Any] | None = None + original_set_result: Any = None + started = False + resumed = False try: - future = cast(AsyncFuture[bool], waiter.send(None)) - except StopIteration as stop: - handle.cancel() - return bool(stop.value) and monotonic() < cutoff - - original_set_result = future.set_result + # Drive the event's public wait() coroutine directly. It honors + # subclasses that delegate to a backing event while still letting us + # observe the future that carries the signal. + waiter = event.wait() + started = True + try: + awaited = waiter.send(None) + except StopIteration as stop: + resumed = True + if stop.value and monotonic() < cutoff: + delivered = True + return delivered + except BaseException: + # A coroutine that raises during startup is already closed. + resumed = True + raise + future = cast(AsyncFuture[Any], awaited) + original_set_result = future.set_result - def set_result(result: bool) -> None: - nonlocal delivered - if monotonic() < cutoff: - delivered = True - original_set_result(result) + def set_result(result: Any) -> None: + nonlocal delivered + if monotonic() < cutoff: + delivered = True + original_set_result(result) - future.set_result = set_result # type: ignore[method-assign] - resumed = False - try: + future.set_result = set_result # type: ignore[method-assign] await async_wait((future, timer), return_when=FIRST_COMPLETED) - if future.done() and not future.cancelled(): + if future.done(): + # Mark this before resuming: a failed send closes the coroutine, and + # cleanup must not throw into it again. + resumed = True try: waiter.send(None) - except StopIteration: + except (StopIteration, AsyncCancelledError): pass - resumed = True return delivered finally: handle.cancel() - future.set_result = original_set_result # type: ignore[method-assign] - if not resumed: - if not future.done(): - future.cancel() - try: - waiter.throw(AsyncCancelledError()) - except (StopIteration, AsyncCancelledError): - pass - waiter.close() + if future is not None and original_set_result is not None: + future.set_result = original_set_result # type: ignore[method-assign] + if waiter is not None: + if started and not resumed: + if future is not None and not future.done(): + future.cancel() + try: + waiter.throw(AsyncCancelledError()) + except (StopIteration, AsyncCancelledError): + pass + if future is not None and future.done() and not future.cancelled(): + try: + future.exception() + except AsyncCancelledError: + pass + waiter.close() def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -335,18 +414,27 @@ def _sleep_with_cancel( sleep(delay) return True end = _cancel_end(delay, cutoff) - deadline = _track_thread_signal(event, end) + deadline = _track_thread_signal(event, _SignalDeadline(end)) try: while True: if deadline.signalled_at is not None: return False - if monotonic() >= end: + now = monotonic() + if now >= end: return True if _cancelled(event): - return False - if _wait_for_event(event, end - monotonic()): + # Read the flag before the final cutoff check: a signal at or + # after the cutoff cannot turn a timeout into a stop. + if monotonic() < end: + deadline.record(monotonic()) + return False + return True + if not _wait_for_event(event, end - now, deadline): if deadline.signalled_at is not None: return False + if monotonic() < end and _cancelled(event): + deadline.record(monotonic()) + return False return True finally: _untrack_thread_signal(event, deadline) @@ -360,11 +448,8 @@ async def _async_sleep_with_cancel( return True end = _cancel_end(delay, cutoff) while True: - if _cancelled(event): - return False - remaining = end - monotonic() - if remaining <= 0: - return not _cancelled(event) + if monotonic() >= end: + return True if await _async_wait_for_event(event, end): return False if monotonic() >= end: @@ -752,7 +837,7 @@ def wait_for_review( raise TypeError("cancel_event must be a threading.Event.") url = _review_url(self._base_url, organization_id, review_id) if _cancelled(cancel_event): - return _stopped(url, None, review_id) + return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None deadline_at = monotonic() + timeout deadline = _transport.DEADLINE.set(deadline_at) @@ -760,17 +845,17 @@ def wait_for_review( try: while (_transport.remaining() or 0) > 0: if _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: if _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise if _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) @@ -778,10 +863,10 @@ def wait_for_review( return result remaining = _transport.remaining() or 0 if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) if (_transport.remaining() or 0) > 0 and _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: @@ -1154,7 +1239,7 @@ async def wait_for_review( raise TypeError("cancel_event must be an asyncio.Event.") url = _review_url(self._base_url, organization_id, review_id) if _cancelled(cancel_event): - return _stopped(url, None, review_id) + return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None deadline_at = monotonic() + timeout deadline = _transport.DEADLINE.set(deadline_at) @@ -1162,17 +1247,17 @@ async def wait_for_review( try: while (_transport.remaining() or 0) > 0: if _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: if _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise if _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) @@ -1182,10 +1267,10 @@ async def wait_for_review( if not await _async_sleep_with_cancel( min(interval, remaining), cancel_event, deadline_at ): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) if (_transport.remaining() or 0) > 0 and _cancelled(cancel_event): - return _stopped(url, last, review_id) + return _stopped(url, last, review_id, head_commit_sha) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: diff --git a/tests/test_http.py b/tests/test_http.py index fa9d60bd..2de5882d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -111,6 +111,15 @@ async def wait_for_all(aws: Any, **kwargs: Any) -> Any: return await asyncio.wait(aws, **kwargs) +async def finish_sender(sender: asyncio.Task[Any]) -> None: + """Bound and reap a test signal task even when an assertion fails.""" + try: + await asyncio.wait_for(sender, 1.0) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + + class Clock: def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 @@ -125,9 +134,15 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(client_module, "_wait_for_event", self.wait_for_event) monkeypatch.setattr(client_module, "_async_wait_for_event", self.async_wait_for_event) - def wait_for_event(self, event: Any, timeout: float) -> bool: + def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None) -> bool: + woke = bool(event.is_set()) + if woke and deadline is not None: + deadline.record(self.now) self.sleep(timeout) - return bool(event.is_set()) + if event.is_set() and deadline is not None and self.now < deadline.end: + deadline.record(self.now) + woke = True + return woke async def async_wait_for_event(self, event: Any, cutoff: float) -> bool: self.sleep(max(0.0, cutoff - self.now)) @@ -1464,7 +1479,7 @@ async def send_signal() -> None: sender = asyncio.create_task(send_signal()) assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await sender + await finish_sender(sender) async def test_async_wait_for_event_ignores_a_signal_after_cutoff( @@ -1496,7 +1511,7 @@ async def send_late_signal() -> None: sender = asyncio.create_task(send_late_signal()) assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False - await sender + await finish_sender(sender) assert signal_sent is True assert any(item.done() for item in observed[0]) @@ -1524,10 +1539,10 @@ async def send_signal() -> None: sender = asyncio.create_task(send_signal()) assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await sender + await finish_sender(sender) -async def test_async_wait_for_event_ignores_subclass_wait_overrides( +async def test_async_wait_for_event_honors_a_delegating_wait_override( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event @@ -1541,16 +1556,20 @@ async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) - class OverriddenEvent(asyncio.Event): + class DelegatingEvent(asyncio.Event): def __init__(self) -> None: super().__init__() + self.backing = asyncio.Event() self.wait_calls = 0 async def wait(self) -> bool: self.wait_calls += 1 - raise RuntimeError("subclass wait must not be used") + return await self.backing.wait() + + def set(self) -> None: + self.backing.set() - event = OverriddenEvent() + event = DelegatingEvent() cutoff = clock.now + 0.01 async def send_signal() -> None: @@ -1559,9 +1578,13 @@ async def send_signal() -> None: clock.now = cutoff + 1.0 sender = asyncio.create_task(send_signal()) - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await sender - assert event.wait_calls == 0 + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await asyncio.wait_for(sender, 1.0) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + assert event.wait_calls == 1 def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( @@ -1570,7 +1593,7 @@ def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( clock = Clock(monkeypatch) event = threading.Event() - def wait_for_event(wait_event: Any, timeout: float) -> bool: + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: clock.sleep(timeout) wait_event.set() return True @@ -1587,8 +1610,10 @@ def test_sleep_with_cancel_latches_delivery_before_a_late_resume( clock = Clock(monkeypatch) event = threading.Event() - def wait_for_event(wait_event: Any, timeout: float) -> bool: + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: wait_event.set() + if deadline is not None: + deadline.record(clock.now) clock.sleep(timeout) return True @@ -1605,8 +1630,10 @@ def test_sleep_with_cancel_records_a_captured_setter( event = threading.Event() setter = event.set - def wait_for_event(wait_event: Any, timeout: float) -> bool: + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: setter() + if deadline is not None: + deadline.record(clock.now) clock.sleep(timeout) return True @@ -1640,7 +1667,7 @@ async def send_signal() -> None: sender = asyncio.create_task(send_signal()) assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await sender + await finish_sender(sender) def test_sleep_with_cancel_does_not_replace_the_event_setter() -> None: @@ -1654,6 +1681,83 @@ def test_sleep_with_cancel_does_not_replace_the_event_setter() -> None: assert condition.notify_all == notify_all +def test_sleep_with_cancel_records_a_set_clear_before_wait_registration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class SetClearEvent(threading.Event): + def wait(self, timeout: float | None = None) -> bool: + self.set() + self.clear() + return False + + event = SetClearEvent() + condition = event._cond + notify_all = condition.notify_all + setter = event.set + + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert event.set == setter + assert condition.notify_all == notify_all + + +async def test_async_wait_for_event_cancels_timer_on_wait_startup_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + loop = asyncio.get_running_loop() + handles: list[asyncio.TimerHandle] = [] + real_call_at = loop.call_at + + def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: + handle = real_call_at(when, callback, *args) + handles.append(handle) + return handle + + monkeypatch.setattr(loop, "call_at", record_call_at) + foreign = asyncio.new_event_loop() + try: + event = asyncio.Event() + event._loop = foreign + with pytest.raises(RuntimeError): + await real_wait(event, loop.time() + 100.0) + finally: + foreign.close() + assert handles + assert all(handle.cancelled() for handle in handles) + + +async def test_async_wait_for_event_propagates_wait_failure_and_cancels_timer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + loop = asyncio.get_running_loop() + handles: list[asyncio.TimerHandle] = [] + real_call_at = loop.call_at + + def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: + handle = real_call_at(when, callback, *args) + handles.append(handle) + return handle + + monkeypatch.setattr(loop, "call_at", record_call_at) + + class FailingEvent(asyncio.Event): + async def wait(self) -> bool: + failed: asyncio.Future[bool] = asyncio.get_running_loop().create_future() + failed.set_exception(RuntimeError("wait failed")) + await failed + return True + + with pytest.raises(RuntimeError, match="wait failed"): + await real_wait(FailingEvent(), loop.time() + 100.0) + assert handles + assert all(handle.cancelled() for handle in handles) + + async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: event = asyncio.Event() setter = event.set @@ -1755,10 +1859,10 @@ def wait(self, timeout: float | None = None) -> bool: abort = threading.Event() real_wait = client_module._wait_for_event - def wait_for_event(wait_event: Any, timeout: float) -> bool: + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: started = time.monotonic() try: - woke = real_wait(wait_event, timeout) + woke = real_wait(wait_event, timeout, deadline) wait_results.append(woke) if abort.is_set() and failures: raise failures[0] @@ -1923,6 +2027,41 @@ def respond(request: Request, index: int) -> Reply: assert clock.delays == [] +@MODES +async def test_wait_for_review_cancellation_keeps_the_head_commit_gap( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + loop = asyncio.get_running_loop() if mode == "async" else None + body = review_at(OTHER_HEAD, "RUNNING") + + def respond(request: Request, index: int) -> Reply: + if loop is None: + event.set() + else: + loop.call_soon_threadsafe(event.set) + return Reply(body=body) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + head_commit_sha=HEAD, + cancel_event=event, + ) + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review is not None + assert result.review.head_commit_sha.lower() == OTHER_HEAD.lower() + assert PINNED_ELSEWHERE in gap_facts(result) + + @MODES async def test_wait_for_review_cancelled_read_rejects_wrong_review_id( mode: str, monkeypatch: pytest.MonkeyPatch @@ -2000,7 +2139,7 @@ async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) else: - def wait_for_event(wait_event: Any, timeout: float) -> bool: + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: clock.sleep(timeout) wait_event.set() return False From 2efa007c99bc5a62738cecc92bbf15a924f2de7a Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 14:18:17 +0530 Subject: [PATCH 13/22] Address twelfth Proofline review findings --- proofline/client.py | 202 +++++++++++++++++++++++++++----------------- tests/test_http.py | 201 ++++++++++++++++++++++++++++++++++--------- 2 files changed, 287 insertions(+), 116 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index be02fc49..bb5ec1ad 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,7 +5,6 @@ import math import threading from asyncio import FIRST_COMPLETED -from asyncio import CancelledError as AsyncCancelledError from asyncio import Event as AsyncEvent from asyncio import Future as AsyncFuture from asyncio import get_running_loop as async_get_running_loop @@ -221,10 +220,11 @@ def __init__(self, condition: threading.Condition) -> None: def record(self) -> None: now = monotonic() + # Record while holding the same lock used to read the latch, then call + # the original notification after releasing it to avoid lock inversion. with _notify_lock: - deadlines = tuple(self.deadlines) - for deadline in deadlines: - deadline.record(now) + for deadline in tuple(self.deadlines): + deadline.record(now) def notify_all(self) -> None: self.record() @@ -281,6 +281,10 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() +def _invalid_response(error: ProoflineError) -> bool: + return error.type == "urn:proofline:sdk:invalid-response" + + def _stopped( url: str, last: CustomerReviewDetail | None, @@ -301,36 +305,80 @@ def _stopped( return ReviewOutcome("STOPPED", url, last, result.gaps, _CANCEL_REASON) +def _sync_deadline_state(deadline: _SignalDeadline) -> tuple[float | None, float]: + """Read the latch and clock under the lock that records notifications.""" + with _notify_lock: + return deadline.signalled_at, monotonic() + + def _wait_for_event( event: threading.Event, timeout: float, deadline: _SignalDeadline | None = None ) -> bool: """Return True when the event woke the wait, False when it timed out.""" if deadline is None: return event.wait(timeout) - conditions = deadline.conditions - if conditions: - # Install the tracker and check the flag under the same condition lock, - # so a set/clear between the check and waiter registration is recorded. - with conditions[0]: + if type(event) is threading.Event and deadline.conditions: + condition = deadline.conditions[0] + # A plain Event's flag and waiters share this condition. Setting and + # clearing between the flag check and waiter registration therefore + # cannot hide a notification from this wait. + with condition: _track_thread_signal(event, deadline) - if deadline.signalled_at is not None: + if _sync_deadline_state(deadline)[0] is not None: return True if getattr(event, "_flag", False) is True: deadline.record(monotonic()) return True - now = monotonic() + remaining = min(timeout, deadline.end - monotonic()) + if remaining <= 0: + return False + condition.wait(remaining) + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return True + if getattr(event, "_flag", False) is True and now < deadline.end: + deadline.record(now) + return True + return False + if deadline.conditions: + with deadline.conditions[0]: + _track_thread_signal(event, deadline) + if _sync_deadline_state(deadline)[0] is not None: + return True + if getattr(event, "_flag", False) is True: + deadline.record(monotonic()) + return True + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return True remaining = min(timeout, deadline.end - now) if remaining <= 0: return False woke = event.wait(remaining) - if woke and deadline.signalled_at is None: - # A subclass may notify through a primitive we cannot observe. A - # successful wait is evidence that its signal reached the wait primitive - # after this call began, which is before the absolute cutoff. - deadline.record(now) + # Subclasses can wake through a primitive we cannot wrap. Only an observed + # wake before the cutoff counts; a tracked late notification stays late. + if woke and _sync_deadline_state(deadline)[0] is None and monotonic() < deadline.end: + deadline.record(monotonic()) return woke +def _async_event_graph(event: AsyncEvent) -> list[AsyncEvent]: + events: list[AsyncEvent] = [] + seen: set[int] = set() + pending = [event] + while pending: + current = pending.pop() + if id(current) in seen: + continue + seen.add(id(current)) + if isinstance(current, AsyncEvent): + events.append(current) + pending.extend( + value for value in vars(current).values() if isinstance(value, AsyncEvent) + ) + return events + + async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: """Return True when the event is signalled before cutoff, False on timeout.""" loop = async_get_running_loop() @@ -338,67 +386,57 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: return False timer: AsyncFuture[None] = loop.create_future() handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) - delivered = event.is_set() and monotonic() < cutoff + delivered = False + wrapped: list[tuple[AsyncFuture[Any], Any]] = [] waiter: Any = None - future: AsyncFuture[Any] | None = None - original_set_result: Any = None - started = False - resumed = False + + def watch_waiters() -> None: + for candidate in _async_event_graph(event): + for future in tuple(getattr(candidate, "_waiters", ())): + if not isinstance(future, AsyncFuture) or any( + future is item[0] for item in wrapped + ): + continue + original = future.set_result + + def set_result(result: Any, original: Any = original) -> None: + nonlocal delivered + if monotonic() < cutoff: + delivered = True + original(result) + + future.set_result = set_result # type: ignore[method-assign] + wrapped.append((future, original)) + + def on_waiter_done(task: Any) -> None: + nonlocal delivered + if task.cancelled() or task.exception() is not None: + return + if task.result() and monotonic() < cutoff: + delivered = True + try: - # Drive the event's public wait() coroutine directly. It honors - # subclasses that delegate to a backing event while still letting us - # observe the future that carries the signal. - waiter = event.wait() - started = True - try: - awaited = waiter.send(None) - except StopIteration as stop: - resumed = True - if stop.value and monotonic() < cutoff: - delivered = True - return delivered - except BaseException: - # A coroutine that raises during startup is already closed. - resumed = True - raise - future = cast(AsyncFuture[Any], awaited) - original_set_result = future.set_result - - def set_result(result: Any) -> None: - nonlocal delivered - if monotonic() < cutoff: + # Run the public wait() as a task so subclasses may suspend any number + # of times, including through sleep(0) or a delegated Task. + waiter = loop.create_task(event.wait()) + waiter.add_done_callback(on_waiter_done) + for _ in range(4): + await async_sleep(0) + watch_waiters() + if wrapped or waiter.done(): + break + await async_wait((waiter, timer), return_when=FIRST_COMPLETED) + if waiter.done() and not waiter.cancelled(): + if waiter.result() and not delivered and monotonic() < cutoff: delivered = True - original_set_result(result) - - future.set_result = set_result # type: ignore[method-assign] - await async_wait((future, timer), return_when=FIRST_COMPLETED) - if future.done(): - # Mark this before resuming: a failed send closes the coroutine, and - # cleanup must not throw into it again. - resumed = True - try: - waiter.send(None) - except (StopIteration, AsyncCancelledError): - pass return delivered finally: handle.cancel() - if future is not None and original_set_result is not None: - future.set_result = original_set_result # type: ignore[method-assign] - if waiter is not None: - if started and not resumed: - if future is not None and not future.done(): - future.cancel() - try: - waiter.throw(AsyncCancelledError()) - except (StopIteration, AsyncCancelledError): - pass - if future is not None and future.done() and not future.cancelled(): - try: - future.exception() - except AsyncCancelledError: - pass - waiter.close() + for future, original in wrapped: + future.set_result = original # type: ignore[method-assign] + if waiter is not None and not waiter.done(): + waiter.cancel() + waiter.add_done_callback(lambda task: None if task.cancelled() else task.exception()) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -417,23 +455,27 @@ def _sleep_with_cancel( deadline = _track_thread_signal(event, _SignalDeadline(end)) try: while True: - if deadline.signalled_at is not None: + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: return False - now = monotonic() if now >= end: return True if _cancelled(event): # Read the flag before the final cutoff check: a signal at or # after the cutoff cannot turn a timeout into a stop. - if monotonic() < end: - deadline.record(monotonic()) + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return False + if now < end: + deadline.record(now) return False return True if not _wait_for_event(event, end - now, deadline): - if deadline.signalled_at is not None: + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: return False - if monotonic() < end and _cancelled(event): - deadline.record(monotonic()) + if now < end and _cancelled(event): + deadline.record(now) return False return True finally: @@ -849,6 +891,8 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: + if _invalid_response(error): + raise if _cancelled(cancel_event): return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: @@ -1251,6 +1295,8 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: + if _invalid_response(error): + raise if _cancelled(cancel_event): return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: diff --git a/tests/test_http.py b/tests/test_http.py index 2de5882d..d83d6ea8 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1478,8 +1478,12 @@ async def send_signal() -> None: clock.now = cutoff + 1.0 sender = asyncio.create_task(send_signal()) - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) async def test_async_wait_for_event_ignores_a_signal_after_cutoff( @@ -1510,10 +1514,17 @@ async def send_late_signal() -> None: signal_sent = True sender = asyncio.create_task(send_late_signal()) - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False - await finish_sender(sender) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) assert signal_sent is True - assert any(item.done() for item in observed[0]) + assert len(observed) == 1 + waiter, timer = observed[0] + assert waiter.done() and waiter.result() is True + assert timer.done() async def test_async_wait_for_event_latches_delivery_before_a_late_resume( @@ -1538,8 +1549,54 @@ async def send_signal() -> None: clock.now = cutoff + 1.0 sender = asyncio.create_task(send_signal()) - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + + +async def test_async_wait_for_event_handles_a_subclass_that_yields_none_first( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() + + async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: + registered.set() + kwargs["return_when"] = asyncio.ALL_COMPLETED + return await asyncio.wait(aws, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + + class YieldFirstEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.suspensions = 0 + + async def wait(self) -> bool: + self.suspensions += 1 + await asyncio.sleep(0) + return await super().wait() + + event = YieldFirstEvent() + cutoff = clock.now + 0.01 + + async def send_signal() -> None: + await registered.wait() + event.set() + clock.now = cutoff + 1.0 + + sender = asyncio.create_task(send_signal()) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + assert event.suspensions == 1 async def test_async_wait_for_event_honors_a_delegating_wait_override( @@ -1564,7 +1621,7 @@ def __init__(self) -> None: async def wait(self) -> bool: self.wait_calls += 1 - return await self.backing.wait() + return await asyncio.create_task(self.backing.wait()) def set(self) -> None: self.backing.set() @@ -1590,57 +1647,60 @@ async def send_signal() -> None: def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - event = threading.Event() - - def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - clock.sleep(timeout) - wait_event.set() - return True + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + class DeadlineSignalEvent(threading.Event): + def wait(self, timeout: float | None = None) -> bool: + clock.now = 101.0 + self.set() + return True + event = DeadlineSignalEvent() assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True - assert clock.delays == [1.0] + assert clock.delays == [] def test_sleep_with_cancel_latches_delivery_before_a_late_resume( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - event = threading.Event() - - def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - wait_event.set() - if deadline is not None: - deadline.record(clock.now) - clock.sleep(timeout) - return True + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + class LateResumeEvent(threading.Event): + def wait(self, timeout: float | None = None) -> bool: + clock.now = 100.5 + self.set() + clock.now = 102.0 + return True + event = LateResumeEvent() assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - assert clock.delays == [1.0] + assert clock.delays == [] def test_sleep_with_cancel_records_a_captured_setter( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - event = threading.Event() - setter = event.set + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - setter() - if deadline is not None: - deadline.record(clock.now) - clock.sleep(timeout) - return True + class CapturedSetterEvent(threading.Event): + setter: Any = None - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + def wait(self, timeout: float | None = None) -> bool: + clock.now = 100.5 + self.setter() + clock.now = 102.0 + return True + event = CapturedSetterEvent() + event.setter = event.set assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - assert clock.delays == [1.0] + assert clock.delays == [] async def test_async_wait_for_event_records_a_captured_setter( @@ -1666,8 +1726,12 @@ async def send_signal() -> None: clock.now = cutoff + 1.0 sender = asyncio.create_task(send_signal()) - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) def test_sleep_with_cancel_does_not_replace_the_event_setter() -> None: @@ -1704,6 +1768,66 @@ def wait(self, timeout: float | None = None) -> bool: assert condition.notify_all == notify_all +def test_sleep_with_cancel_records_a_plain_event_set_clear_before_the_wait( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + event = threading.Event() + setter = event.set + clearer = event.clear + condition = event._cond + notify_all = condition.notify_all + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + setter() + clearer() + return real_wait(wait_event, timeout, deadline) + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert event.set == setter + assert condition.notify_all == notify_all + + +async def test_async_wait_for_event_restores_waiter_after_cutoff_without_a_signal() -> None: + real_wait = client_module._async_wait_for_event + + class TrackedEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.futures: list[asyncio.Future[bool]] = [] + self.originals: list[Any] = [] + + async def wait(self) -> bool: + future = asyncio.get_running_loop().create_future() + self._waiters.append(future) + self.futures.append(future) + self.originals.append(future.set_result) + try: + return await future + finally: + self._waiters.remove(future) + + event = TrackedEvent() + task = asyncio.create_task(real_wait(event, time.monotonic() + 0.05)) + try: + for _ in range(100): + if event.futures: + break + await asyncio.sleep(0) + assert event.futures + assert event.futures[0].set_result is not event.originals[0] + assert await asyncio.wait_for(task, 1.0) is False + assert event.futures[0].set_result == event.originals[0] + assert event.futures[0].cancelled() + assert not event._waiters + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + async def test_async_wait_for_event_cancels_timer_on_wait_startup_failure( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -2086,6 +2210,7 @@ def respond(request: Request, index: int) -> Reply: await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) assert raised.value.type == "urn:proofline:sdk:invalid-response" assert "invalid identity" in raised.value.detail + assert event.is_set() assert len(server.requests) == 1 From d2ecdac0d81210c8ae0d9b47e6b0c4ef88e22bf4 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Wed, 25 Nov 2026 14:52:53 +0530 Subject: [PATCH 14/22] Address thirteenth Proofline review findings --- proofline/client.py | 305 ++++++++++++++++++++++++++++++++------------ tests/test_http.py | 282 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 506 insertions(+), 81 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index bb5ec1ad..766031ac 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import math import threading from asyncio import FIRST_COMPLETED @@ -210,8 +211,15 @@ def record(self, now: float) -> None: class _ConditionSignalTracker: + """Watch one condition, preserving whether overrides were instance attributes.""" + def __init__(self, condition: threading.Condition) -> None: self.condition = condition + attributes = vars(condition) + self.had_notify_all = "notify_all" in attributes + self.saved_notify_all: Any = attributes.get("notify_all") + self.had_notify = "notify" in attributes + self.saved_notify: Any = attributes.get("notify") self.original_notify_all = condition.notify_all self.original_notify = condition.notify self.deadlines: set[_SignalDeadline] = set() @@ -220,8 +228,8 @@ def __init__(self, condition: threading.Condition) -> None: def record(self) -> None: now = monotonic() - # Record while holding the same lock used to read the latch, then call - # the original notification after releasing it to avoid lock inversion. + # Latch under the lock readers use, then notify after releasing it so a + # waiter holding the condition lock cannot deadlock this tracker. with _notify_lock: for deadline in tuple(self.deadlines): deadline.record(now) @@ -234,19 +242,39 @@ def notify(self, *args: Any, **kwargs: Any) -> None: self.record() self.original_notify(*args, **kwargs) + def restore(self) -> None: + if self.had_notify_all: + self.condition.notify_all = self.saved_notify_all # type: ignore[method-assign] + else: + del self.condition.notify_all + if self.had_notify: + self.condition.notify = self.saved_notify # type: ignore[method-assign] + else: + del self.condition.notify + _notify_lock = threading.Lock() _notify_trackers: dict[int, _ConditionSignalTracker] = {} def _thread_conditions(event: threading.Event) -> tuple[threading.Condition, ...]: + """Collect conditions owned by this event or backing events it references.""" conditions: list[threading.Condition] = [] - seen: set[int] = set() - candidates = [getattr(event, "_cond", None), *vars(event).values()] - for candidate in candidates: - if isinstance(candidate, threading.Condition) and id(candidate) not in seen: - seen.add(id(candidate)) - conditions.append(candidate) + seen_events: set[int] = set() + seen_conditions: set[int] = set() + pending = [event] + while pending: + current = pending.pop() + if id(current) in seen_events: + continue + seen_events.add(id(current)) + condition = getattr(current, "_cond", None) + if isinstance(condition, threading.Condition) and id(condition) not in seen_conditions: + seen_conditions.add(id(condition)) + conditions.append(condition) + pending.extend( + value for value in vars(current).values() if isinstance(value, threading.Event) + ) return tuple(conditions) @@ -272,8 +300,7 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> continue tracker.deadlines.discard(deadline) if not tracker.deadlines: - tracker.condition.notify_all = tracker.original_notify_all # type: ignore[method-assign] - tracker.condition.notify = tracker.original_notify # type: ignore[method-assign] + tracker.restore() del _notify_trackers[key] @@ -317,11 +344,12 @@ def _wait_for_event( """Return True when the event woke the wait, False when it timed out.""" if deadline is None: return event.wait(timeout) - if type(event) is threading.Event and deadline.conditions: - condition = deadline.conditions[0] - # A plain Event's flag and waiters share this condition. Setting and - # clearing between the flag check and waiter registration therefore - # cannot hide a notification from this wait. + inherited = type(event).wait is threading.Event.wait + condition = getattr(event, "_cond", None) if inherited else None + if isinstance(condition, threading.Condition): + # Plain events and subclasses that inherit Event.wait() share this + # condition for the flag and the waiter list. Checking and waiting under + # it makes a set/clear between those steps observable. with condition: _track_thread_signal(event, deadline) if _sync_deadline_state(deadline)[0] is not None: @@ -345,7 +373,7 @@ def _wait_for_event( _track_thread_signal(event, deadline) if _sync_deadline_state(deadline)[0] is not None: return True - if getattr(event, "_flag", False) is True: + if event.is_set(): deadline.record(monotonic()) return True signalled_at, now = _sync_deadline_state(deadline) @@ -362,21 +390,125 @@ def _wait_for_event( return woke -def _async_event_graph(event: AsyncEvent) -> list[AsyncEvent]: - events: list[AsyncEvent] = [] - seen: set[int] = set() - pending = [event] - while pending: - current = pending.pop() - if id(current) in seen: - continue - seen.add(id(current)) - if isinstance(current, AsyncEvent): - events.append(current) - pending.extend( - value for value in vars(current).values() if isinstance(value, AsyncEvent) - ) - return events +_async_set_lock = threading.Lock() +_async_future_lock = threading.Lock() +_async_set_watches: dict[int, _AsyncSetWatch] = {} +_async_future_watches: dict[int, _AsyncFutureWatch] = {} + + +class _AsyncSetWatch: + """One shared hook on an event's public set(), with independent observers.""" + + def __init__(self, event: AsyncEvent) -> None: + self.event = event + attributes = _instance_attributes(event) + self.had_instance = "set" in attributes + self.saved: Any = attributes.get("set") + self.original = event.set + self.deadlines: set[_SignalDeadline] = set() + + def set_event(*args: Any, **kwargs: Any) -> Any: + result = self.original(*args, **kwargs) + now = monotonic() + with _async_set_lock: + deadlines = tuple(self.deadlines) + for deadline in deadlines: + deadline.record(now) + return result + + event.set = set_event # type: ignore[method-assign] + + def restore(self) -> None: + if self.had_instance: + self.event.set = self.saved # type: ignore[method-assign] + else: + del self.event.set + + +class _AsyncFutureWatch: + """One shared hook on a waiter future, with independent observers.""" + + def __init__(self, future: AsyncFuture[Any], event: AsyncEvent) -> None: + self.future = future + self.event = event + attributes = _instance_attributes(future) + self.had_instance = "set_result" in attributes + self.saved: Any = attributes.get("set_result") + self.original = future.set_result + self.deadlines: set[_SignalDeadline] = set() + + def set_result(result: Any) -> None: + now = monotonic() + if _event_is_set(event): + with _async_future_lock: + deadlines = tuple(self.deadlines) + for deadline in deadlines: + deadline.record(now) + self.original(result) + + future.set_result = set_result # type: ignore[method-assign] + + def restore(self) -> None: + if self.had_instance: + self.future.set_result = self.saved # type: ignore[method-assign] + else: + del self.future.set_result + + +def _instance_attributes(value: Any) -> dict[str, Any]: + return getattr(value, "__dict__", {}) + + +def _event_is_set(event: AsyncEvent) -> bool: + try: + return event.is_set() + except Exception: + return False + + +def _watch_async_set(event: AsyncEvent, deadline: _SignalDeadline) -> None: + with _async_set_lock: + watch = _async_set_watches.get(id(event)) + if watch is None: + watch = _AsyncSetWatch(event) + _async_set_watches[id(event)] = watch + watch.deadlines.add(deadline) + + +def _unwatch_async_set(event: AsyncEvent, deadline: _SignalDeadline) -> None: + with _async_set_lock: + watch = _async_set_watches.get(id(event)) + if watch is None: + return + watch.deadlines.discard(deadline) + if not watch.deadlines: + watch.restore() + del _async_set_watches[id(event)] + + +def _watch_async_future( + future: AsyncFuture[Any], event: AsyncEvent, deadline: _SignalDeadline +) -> None: + with _async_future_lock: + watch = _async_future_watches.get(id(future)) + if watch is None: + watch = _AsyncFutureWatch(future, event) + _async_future_watches[id(future)] = watch + watch.deadlines.add(deadline) + + +def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) -> bool: + """Remove one observer; return True when the future has no observers left.""" + with _async_future_lock: + watch = _async_future_watches.get(id(future)) + if watch is None: + return False + watch.deadlines.discard(deadline) + if not watch.deadlines: + watch.restore() + del _async_future_watches[id(future)] + return True + return False async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: @@ -384,59 +516,70 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: loop = async_get_running_loop() if monotonic() >= cutoff: return False + deadline = _SignalDeadline(cutoff) timer: AsyncFuture[None] = loop.create_future() handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) - delivered = False - wrapped: list[tuple[AsyncFuture[Any], Any]] = [] - waiter: Any = None - - def watch_waiters() -> None: - for candidate in _async_event_graph(event): - for future in tuple(getattr(candidate, "_waiters", ())): - if not isinstance(future, AsyncFuture) or any( - future is item[0] for item in wrapped - ): - continue - original = future.set_result - - def set_result(result: Any, original: Any = original) -> None: - nonlocal delivered - if monotonic() < cutoff: - delivered = True - original(result) + coro: Any = None + child: asyncio.Task[Any] | None = None + future: AsyncFuture[Any] | None = None + resumed = False + try: + if type(event) is asyncio.Event: + # The built-in Event.wait() always suspends once on a registered + # future. Driving it directly registers that waiter before yielding. + coro = event.wait() + try: + awaited = coro.send(None) + except StopIteration as stop: + resumed = True + if stop.value: + deadline.record(monotonic()) + return deadline.signalled_at is not None + future = cast(AsyncFuture[Any], awaited) + _watch_async_future(future, event, deadline) + await async_wait((future, timer), return_when=FIRST_COMPLETED) + if future.done() and not future.cancelled(): + resumed = True + try: + coro.send(None) + except StopIteration: + pass + return deadline.signalled_at is not None - future.set_result = set_result # type: ignore[method-assign] - wrapped.append((future, original)) + # Subclasses own their suspension sequence, so only their public set() + # is treated as verified cancellation; nested gates are not signals. + _watch_async_set(event, deadline) - def on_waiter_done(task: Any) -> None: - nonlocal delivered - if task.cancelled() or task.exception() is not None: - return - if task.result() and monotonic() < cutoff: - delivered = True + def on_waiter_done(task: asyncio.Task[Any]) -> None: + if task.cancelled() or task.exception() is not None: + return + if task.result() and _event_is_set(event): + deadline.record(monotonic()) - try: - # Run the public wait() as a task so subclasses may suspend any number - # of times, including through sleep(0) or a delegated Task. - waiter = loop.create_task(event.wait()) - waiter.add_done_callback(on_waiter_done) - for _ in range(4): - await async_sleep(0) - watch_waiters() - if wrapped or waiter.done(): - break - await async_wait((waiter, timer), return_when=FIRST_COMPLETED) - if waiter.done() and not waiter.cancelled(): - if waiter.result() and not delivered and monotonic() < cutoff: - delivered = True - return delivered + child = loop.create_task(event.wait()) + child.add_done_callback(on_waiter_done) + await async_wait((child, timer), return_when=FIRST_COMPLETED) + if child.done() and not child.cancelled(): + if child.result() and deadline.signalled_at is None and _event_is_set(event): + deadline.record(monotonic()) + return deadline.signalled_at is not None finally: handle.cancel() - for future, original in wrapped: - future.set_result = original # type: ignore[method-assign] - if waiter is not None and not waiter.done(): - waiter.cancel() - waiter.add_done_callback(lambda task: None if task.cancelled() else task.exception()) + _unwatch_async_set(event, deadline) + if future is not None: + last_observer = _unwatch_async_future(future, deadline) + # A future shared by overlapping waits belongs to the remaining + # observers until the last one leaves. + if last_observer: + if future.done() and not future.cancelled(): + future.exception() + else: + future.cancel() + if coro is not None and not resumed: + coro.close() + if child is not None and not child.done(): + child.cancel() + await asyncio.gather(child, return_exceptions=True) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -891,9 +1034,9 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if _invalid_response(error): - raise if _cancelled(cancel_event): + if _invalid_response(error): + raise return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break @@ -1295,9 +1438,9 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if _invalid_response(error): - raise if _cancelled(cancel_event): + if _invalid_response(error): + raise return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break diff --git a/tests/test_http.py b/tests/test_http.py index d83d6ea8..9355455f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1799,6 +1799,7 @@ def __init__(self) -> None: super().__init__() self.futures: list[asyncio.Future[bool]] = [] self.originals: list[Any] = [] + self.finished = False async def wait(self) -> bool: future = asyncio.get_running_loop().create_future() @@ -1808,6 +1809,7 @@ async def wait(self) -> bool: try: return await future finally: + self.finished = True self._waiters.remove(future) event = TrackedEvent() @@ -1822,12 +1824,266 @@ async def wait(self) -> bool: assert await asyncio.wait_for(task, 1.0) is False assert event.futures[0].set_result == event.originals[0] assert event.futures[0].cancelled() + assert event.finished assert not event._waiters finally: task.cancel() await asyncio.gather(task, return_exceptions=True) +def test_sleep_with_cancel_latches_an_inherited_wait_set_clear_before_registration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class InheritedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + event = self + + class RaceCondition(threading.Condition): + def wait(self, timeout: float | None = None) -> bool: + event._flag = True + self.notify_all() + event._flag = False + return super().wait(0.01) + + self._cond = RaceCondition(threading.Lock()) + + event = InheritedEvent() + condition = event._cond + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert clock.delays == [] + assert "notify_all" not in vars(condition) + assert "notify" not in vars(condition) + + +def test_sleep_with_cancel_ignores_an_unrelated_condition( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class UnrelatedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.other = threading.Condition() + + def wait(self, timeout: float | None = None) -> bool: + with self.other: + self.other.notify_all() + return False + + event = UnrelatedEvent() + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + assert "notify_all" not in vars(event.other) + + +def test_sleep_with_cancel_tracks_a_backing_thread_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class BackingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.backing = threading.Event() + self.started = threading.Event() + + def wait(self, timeout: float | None = None) -> bool: + self.started.set() + return self.backing.wait(timeout) + + def set(self) -> None: + self.backing.set() + + event = BackingEvent() + + def signal() -> None: + assert event.started.wait(1.0) + clock.now = 100.5 + event.backing.set() + clock.now = 102.0 + + thread = threading.Thread(target=signal) + thread.start() + try: + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + finally: + thread.join(1.0) + assert not thread.is_alive() + assert "notify_all" not in vars(event.backing._cond) + + +def test_sleep_with_cancel_restores_inherited_condition_methods( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class ClassCondition(threading.Condition): + def notify_all(self, *args: Any, **kwargs: Any) -> None: + super().notify_all(*args, **kwargs) + + def notify(self, *args: Any, **kwargs: Any) -> None: + super().notify(*args, **kwargs) + + class InheritedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self._cond = ClassCondition(threading.Lock()) + + def wait(self, timeout: float | None = None) -> bool: + return False + + event = InheritedEvent() + condition = event._cond + assert client_module._sleep_with_cancel(0, event) is True + assert "notify_all" not in vars(condition) + assert "notify" not in vars(condition) + assert condition.notify_all.__func__ is ClassCondition.notify_all + assert condition.notify.__func__ is ClassCondition.notify + + +def test_sleep_with_cancel_preserves_an_instance_condition_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + event = threading.Event() + condition = event._cond + + def notify_all() -> None: + return None + + condition.notify_all = notify_all + assert client_module._sleep_with_cancel(0, event) is True + assert condition.notify_all is notify_all + + +async def test_async_wait_for_event_ignores_a_subclass_setup_gate( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + + class GatedEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.gate = asyncio.Event() + self.started = asyncio.Event() + + async def wait(self) -> bool: + self.started.set() + await self.gate.wait() + return await super().wait() + + event = GatedEvent() + cutoff = clock.now + 0.01 + + async def open_gate() -> None: + await event.started.wait() + event.gate.set() + clock.now = cutoff + 1.0 + + sender = asyncio.create_task(open_gate()) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + + +async def test_async_wait_for_event_latches_a_late_subclass_registration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + started = asyncio.Event() + + class LateRegisterEvent(asyncio.Event): + async def wait(self) -> bool: + started.set() + for _ in range(20): + await asyncio.sleep(0) + return await super().wait() + + event = LateRegisterEvent() + cutoff = clock.now + 0.2 + + async def send_signal() -> None: + await started.wait() + for _ in range(2): + await asyncio.sleep(0) + event.set() + clock.now = cutoff + 1.0 + + sender = asyncio.create_task(send_signal()) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + + +async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + + class WatchedEvent(asyncio.Event): + pass + + event = WatchedEvent() + first = asyncio.create_task(real_wait(event, clock.now + 0.01)) + second = asyncio.create_task(real_wait(event, clock.now + 0.05)) + try: + assert await asyncio.wait_for(first, 1.0) is False + assert "set" in vars(event) + event.set() + assert await asyncio.wait_for(second, 1.0) is True + assert "set" not in vars(event) + finally: + first.cancel() + second.cancel() + await asyncio.gather(first, second, return_exceptions=True) + + +async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + original_set_result = future.set_result + first = client_module._SignalDeadline(clock.now + 0.01) + second = client_module._SignalDeadline(clock.now + 0.05) + + client_module._watch_async_future(future, event, first) + client_module._watch_async_future(future, event, second) + assert future.set_result is not original_set_result + assert client_module._unwatch_async_future(future, first) is False + assert future.set_result is not original_set_result + + clock.now = 100.02 + event.set() + future.set_result(True) + assert first.signalled_at is None + assert second.signalled_at == 100.02 + assert client_module._unwatch_async_future(future, second) is True + assert future.set_result == original_set_result + + async def test_async_wait_for_event_cancels_timer_on_wait_startup_failure( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -2214,6 +2470,32 @@ def respond(request: Request, index: int) -> Reply: assert len(server.requests) == 1 +@MODES +async def test_wait_for_review_invalid_response_after_deadline_keeps_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + calls = 0 + + def get_review(*args: Any, **kwargs: Any) -> Any: + nonlocal calls + calls += 1 + clock.now += 101.0 + raise _transport.invalid_response() + + monkeypatch.setattr(client, "get_review", get_review) + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert calls == 1 + assert result.status == "TIMED_OUT" + assert result.review is None + assert not event.is_set() + + @MODES async def test_wait_for_review_cancel_event_during_erroring_read_keeps_last_record( mode: str, monkeypatch: pytest.MonkeyPatch From 93884982dce7d88d9d9eedde23a2e4dc6478109a Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Fri, 27 Nov 2026 15:51:39 +0530 Subject: [PATCH 15/22] Address fourteenth Proofline review findings --- proofline/client.py | 192 ++++++++++++++++++++---------- tests/test_http.py | 282 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 403 insertions(+), 71 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 766031ac..539054da 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -199,11 +199,17 @@ def _pagination_limit(resource: str = "Review") -> ProoflineError: _CANCEL_REASON = "The wait was cancelled by the caller." +def _instance_attributes(value: Any) -> dict[str, Any]: + return getattr(value, "__dict__", {}) + + class _SignalDeadline: def __init__(self, end: float) -> None: self.end = end self.signalled_at: float | None = None self.conditions: tuple[threading.Condition, ...] = () + self.watched_set = False + self.signal_future: Any = None def record(self, now: float) -> None: if self.signalled_at is None and now < self.end: @@ -255,37 +261,55 @@ def restore(self) -> None: _notify_lock = threading.Lock() _notify_trackers: dict[int, _ConditionSignalTracker] = {} +_sync_set_lock = threading.Lock() +_sync_set_watches: dict[int, _SyncSetWatch] = {} -def _thread_conditions(event: threading.Event) -> tuple[threading.Condition, ...]: - """Collect conditions owned by this event or backing events it references.""" - conditions: list[threading.Condition] = [] - seen_events: set[int] = set() - seen_conditions: set[int] = set() - pending = [event] - while pending: - current = pending.pop() - if id(current) in seen_events: - continue - seen_events.add(id(current)) - condition = getattr(current, "_cond", None) - if isinstance(condition, threading.Condition) and id(condition) not in seen_conditions: - seen_conditions.add(id(condition)) - conditions.append(condition) - pending.extend( - value for value in vars(current).values() if isinstance(value, threading.Event) - ) - return tuple(conditions) +class _SyncSetWatch: + """Watch one event's public set(), with independent deadline subscribers.""" + + def __init__(self, event: threading.Event) -> None: + self.event = event + attributes = _instance_attributes(event) + self.had_instance = "set" in attributes + self.saved: Any = attributes.get("set") + self.original = event.set + self.deadlines: set[_SignalDeadline] = set() + + def set_event(*args: Any, **kwargs: Any) -> Any: + result = self.original(*args, **kwargs) + now = monotonic() + with _sync_set_lock: + deadlines = tuple(self.deadlines) + for deadline in deadlines: + deadline.record(now) + if deadline.signal_future is not None and not deadline.signal_future.done(): + deadline.signal_future.set_result(None) + return result + + event.set = set_event # type: ignore[method-assign] + + def restore(self) -> None: + if self.had_instance: + self.event.set = self.saved # type: ignore[method-assign] + else: + del self.event.set + + +def _sync_inherited_wait(event: threading.Event) -> bool: + return type(event).wait is threading.Event.wait def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: - deadline.conditions = _thread_conditions(event) + """Watch only the condition used by Event.wait(), never nested events.""" + condition = getattr(event, "_cond", None) + deadline.conditions = (condition,) if isinstance(condition, threading.Condition) else () with _notify_lock: - for condition in deadline.conditions: - key = id(condition) + for tracked in deadline.conditions: + key = id(tracked) tracker = _notify_trackers.get(key) if tracker is None: - tracker = _ConditionSignalTracker(condition) + tracker = _ConditionSignalTracker(tracked) _notify_trackers[key] = tracker tracker.deadlines.add(deadline) return deadline @@ -302,6 +326,43 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> if not tracker.deadlines: tracker.restore() del _notify_trackers[key] + deadline.conditions = () + + +def _watch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: + with _sync_set_lock: + watch = _sync_set_watches.get(id(event)) + if watch is None: + watch = _SyncSetWatch(event) + _sync_set_watches[id(event)] = watch + watch.deadlines.add(deadline) + deadline.watched_set = True + + +def _unwatch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: + with _sync_set_lock: + watch = _sync_set_watches.get(id(event)) + if watch is None: + return + watch.deadlines.discard(deadline) + if not watch.deadlines: + watch.restore() + del _sync_set_watches[id(event)] + deadline.watched_set = False + + +def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: + # The event's own condition catches captured setter calls; the public set + # hook additionally catches subclasses that delegate to a backing event. + _track_thread_signal(event, deadline) + if not _sync_inherited_wait(event): + _watch_sync_set(event, deadline) + + +def _untrack_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: + if deadline.watched_set: + _unwatch_sync_set(event, deadline) + _untrack_thread_signal(event, deadline) def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: @@ -344,14 +405,13 @@ def _wait_for_event( """Return True when the event woke the wait, False when it timed out.""" if deadline is None: return event.wait(timeout) - inherited = type(event).wait is threading.Event.wait + inherited = _sync_inherited_wait(event) condition = getattr(event, "_cond", None) if inherited else None if isinstance(condition, threading.Condition): # Plain events and subclasses that inherit Event.wait() share this # condition for the flag and the waiter list. Checking and waiting under # it makes a set/clear between those steps observable. with condition: - _track_thread_signal(event, deadline) if _sync_deadline_state(deadline)[0] is not None: return True if getattr(event, "_flag", False) is True: @@ -368,26 +428,27 @@ def _wait_for_event( deadline.record(now) return True return False - if deadline.conditions: - with deadline.conditions[0]: - _track_thread_signal(event, deadline) - if _sync_deadline_state(deadline)[0] is not None: - return True - if event.is_set(): - deadline.record(monotonic()) - return True - signalled_at, now = _sync_deadline_state(deadline) - if signalled_at is not None: - return True - remaining = min(timeout, deadline.end - now) - if remaining <= 0: - return False - woke = event.wait(remaining) - # Subclasses can wake through a primitive we cannot wrap. Only an observed - # wake before the cutoff counts; a tracked late notification stays late. - if woke and _sync_deadline_state(deadline)[0] is None and monotonic() < deadline.end: - deadline.record(monotonic()) - return woke + # A subclass owns its wait primitive. Its public set() is the only verified + # cancellation source, and short slices bound a missed wakeup. + end = min(monotonic() + timeout, deadline.end) + while True: + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return True + remaining = end - now + if remaining <= 0: + return False + # Do not call an overridable is_set() while holding the event condition. + if event.is_set(): + deadline.record(now) + return True + woke = event.wait(min(remaining, 0.01)) + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return True + if woke and now < deadline.end and event.is_set(): + deadline.record(now) + return True _async_set_lock = threading.Lock() @@ -414,6 +475,8 @@ def set_event(*args: Any, **kwargs: Any) -> Any: deadlines = tuple(self.deadlines) for deadline in deadlines: deadline.record(now) + if deadline.signal_future is not None and not deadline.signal_future.done(): + deadline.signal_future.set_result(None) return result event.set = set_event # type: ignore[method-assign] @@ -455,10 +518,6 @@ def restore(self) -> None: del self.future.set_result -def _instance_attributes(value: Any) -> dict[str, Any]: - return getattr(value, "__dict__", {}) - - def _event_is_set(event: AsyncEvent) -> bool: try: return event.is_set() @@ -524,9 +583,10 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: future: AsyncFuture[Any] | None = None resumed = False try: - if type(event) is asyncio.Event: - # The built-in Event.wait() always suspends once on a registered - # future. Driving it directly registers that waiter before yielding. + if type(event).wait is asyncio.Event.wait: + # The standard wait() always suspends once on a registered future. + # Driving it directly registers that waiter before yielding, and + # the waiter future proves that the event itself woke the wait. coro = event.wait() try: awaited = coro.send(None) @@ -546,8 +606,11 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: pass return deadline.signalled_at is not None - # Subclasses own their suspension sequence, so only their public set() - # is treated as verified cancellation; nested gates are not signals. + # An overriding subclass owns its suspension sequence. Its public set() + # is the only verified cancellation source; a private signal future + # makes a set/clear before waiter registration wake this race at once. + signal_future: AsyncFuture[None] = loop.create_future() + deadline.signal_future = signal_future _watch_async_set(event, deadline) def on_waiter_done(task: asyncio.Task[Any]) -> None: @@ -558,7 +621,7 @@ def on_waiter_done(task: asyncio.Task[Any]) -> None: child = loop.create_task(event.wait()) child.add_done_callback(on_waiter_done) - await async_wait((child, timer), return_when=FIRST_COMPLETED) + await async_wait((child, timer, signal_future), return_when=FIRST_COMPLETED) if child.done() and not child.cancelled(): if child.result() and deadline.signalled_at is None and _event_is_set(event): deadline.record(monotonic()) @@ -577,9 +640,17 @@ def on_waiter_done(task: asyncio.Task[Any]) -> None: future.cancel() if coro is not None and not resumed: coro.close() - if child is not None and not child.done(): - child.cancel() - await asyncio.gather(child, return_exceptions=True) + if child is not None: + if child.done(): + if not child.cancelled(): + child.exception() + else: + child.cancel() + # Do not block the parent on subclass cleanup; observe the + # eventual result separately so exceptions are not orphaned. + child.add_done_callback( + lambda task: task.exception() if not task.cancelled() else None + ) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -595,7 +666,8 @@ def _sleep_with_cancel( sleep(delay) return True end = _cancel_end(delay, cutoff) - deadline = _track_thread_signal(event, _SignalDeadline(end)) + deadline = _SignalDeadline(end) + _track_sync_cancel(event, deadline) try: while True: signalled_at, now = _sync_deadline_state(deadline) @@ -622,7 +694,7 @@ def _sleep_with_cancel( return False return True finally: - _untrack_thread_signal(event, deadline) + _untrack_sync_cancel(event, deadline) async def _async_sleep_with_cancel( diff --git a/tests/test_http.py b/tests/test_http.py index 9355455f..1f35f79f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -120,6 +120,22 @@ async def finish_sender(sender: asyncio.Task[Any]) -> None: await asyncio.gather(sender, return_exceptions=True) +class ManualTimer: + """A call_at handle that fires only when the test explicitly says so.""" + + def __init__(self, callback: Any, args: tuple[Any, ...]) -> None: + self.callback = callback + self.args = args + self.cancelled = False + + def fire(self) -> None: + if not self.cancelled: + self.callback(*self.args) + + def cancel(self) -> None: + self.cancelled = True + + class Clock: def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 @@ -1432,7 +1448,7 @@ async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( def unexpected_event_wait(*args: Any, **kwargs: Any) -> bool: raise AssertionError("event wait called without cancel_event") - async def unexpected_async_event_wait(*args: Any, **kwargs: Any) -> bool: + def unexpected_async_event_wait(*args: Any, **kwargs: Any) -> bool: raise AssertionError("async event wait called without cancel_event") monkeypatch.setattr(client_module, "_wait_for_event", unexpected_event_wait) @@ -1791,21 +1807,31 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert condition.notify_all == notify_all -async def test_async_wait_for_event_restores_waiter_after_cutoff_without_a_signal() -> None: +async def test_async_wait_for_event_restores_waiter_after_cutoff_without_a_signal( + monkeypatch: pytest.MonkeyPatch, +) -> None: real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + loop = asyncio.get_running_loop() + timers: list[ManualTimer] = [] + + def manual_call_at(when: float, callback: Any, *args: Any) -> ManualTimer: + timer = ManualTimer(callback, args) + timers.append(timer) + return timer + + monkeypatch.setattr(loop, "call_at", manual_call_at) class TrackedEvent(asyncio.Event): def __init__(self) -> None: super().__init__() self.futures: list[asyncio.Future[bool]] = [] - self.originals: list[Any] = [] self.finished = False async def wait(self) -> bool: - future = asyncio.get_running_loop().create_future() + future = loop.create_future() self._waiters.append(future) self.futures.append(future) - self.originals.append(future.set_result) try: return await future finally: @@ -1813,22 +1839,85 @@ async def wait(self) -> bool: self._waiters.remove(future) event = TrackedEvent() - task = asyncio.create_task(real_wait(event, time.monotonic() + 0.05)) + task = asyncio.create_task(real_wait(event, clock.now + 0.01)) try: for _ in range(100): if event.futures: break await asyncio.sleep(0) assert event.futures - assert event.futures[0].set_result is not event.originals[0] + assert "set" in vars(event) + timers[0].fire() assert await asyncio.wait_for(task, 1.0) is False - assert event.futures[0].set_result == event.originals[0] + assert "set" not in vars(event) + for _ in range(100): + if event.finished: + break + await asyncio.sleep(0) assert event.futures[0].cancelled() assert event.finished assert not event._waiters finally: task.cancel() await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + + +async def test_async_wait_for_event_returns_at_cutoff_with_a_stubborn_waiter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + loop = asyncio.get_running_loop() + timers: list[ManualTimer] = [] + + def manual_call_at(when: float, callback: Any, *args: Any) -> ManualTimer: + timer = ManualTimer(callback, args) + timers.append(timer) + return timer + + monkeypatch.setattr(loop, "call_at", manual_call_at) + gate = asyncio.Event() + + class StubbornEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.started = asyncio.Event() + self.finished = False + + async def wait(self) -> bool: + self.started.set() + try: + await gate.wait() + except asyncio.CancelledError: + await gate.wait() + finally: + self.finished = True + return False + + event = StubbornEvent() + cutoff = clock.now + 0.01 + task = asyncio.create_task(real_wait(event, cutoff)) + try: + for _ in range(100): + if event.started.is_set(): + break + await asyncio.sleep(0) + assert event.started.is_set() + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + assert not event.finished + finally: + gate.set() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + for _ in range(100): + if event.finished: + break + await asyncio.sleep(0) def test_sleep_with_cancel_latches_an_inherited_wait_set_clear_before_registration( @@ -1864,7 +1953,7 @@ def test_sleep_with_cancel_ignores_an_unrelated_condition( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._wait_for_event - Clock(monkeypatch) + clock = Clock(monkeypatch) monkeypatch.setattr(client_module, "_wait_for_event", real_wait) class UnrelatedEvent(threading.Event): @@ -1875,6 +1964,7 @@ def __init__(self) -> None: def wait(self, timeout: float | None = None) -> bool: with self.other: self.other.notify_all() + clock.sleep(timeout or 0) return False event = UnrelatedEvent() @@ -1907,7 +1997,7 @@ def set(self) -> None: def signal() -> None: assert event.started.wait(1.0) clock.now = 100.5 - event.backing.set() + event.set() clock.now = 102.0 thread = threading.Thread(target=signal) @@ -1968,6 +2058,93 @@ def notify_all() -> None: assert condition.notify_all is notify_all +def test_sleep_with_cancel_ignores_a_nested_marker_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class MarkerEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.marker = threading.Event() + + def wait(self, timeout: float | None = None) -> bool: + self.marker.set() + clock.sleep(timeout or 0) + return False + + event = MarkerEvent() + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + assert "notify_all" not in vars(event.marker._cond) + + +def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class ReentrantEvent(threading.Event): + def is_set(self) -> bool: + with self._cond: + return super().is_set() + + def wait(self, timeout: float | None = None) -> bool: + clock.sleep(timeout or 0) + return False + + event = ReentrantEvent() + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + + +def test_sleep_with_cancel_does_not_wrap_a_replaced_backing_condition( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class SwappingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.original_backing = threading.Event() + self.backing = self.original_backing + self.started = threading.Event() + self.swapped = False + + def wait(self, timeout: float | None = None) -> bool: + self.started.set() + return self.backing.wait(timeout) + + def is_set(self) -> bool: + if not self.swapped: + self.swapped = True + self.backing = threading.Event() + return self.backing.is_set() + + def set(self) -> None: + self.backing.set() + + event = SwappingEvent() + + def signal() -> None: + assert event.started.wait(1.0) + event.set() + + thread = threading.Thread(target=signal) + thread.start() + try: + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + finally: + thread.join(1.0) + assert not thread.is_alive() + assert "notify_all" not in vars(event.original_backing._cond) + assert "notify_all" not in vars(event.backing._cond) + + async def test_async_wait_for_event_ignores_a_subclass_setup_gate( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -2035,19 +2212,100 @@ async def send_signal() -> None: await asyncio.gather(sender, return_exceptions=True) +async def test_async_wait_for_event_latches_a_set_clear_before_subclass_wait_registers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + started = asyncio.Event() + release = asyncio.Event() + + class SetClearEvent(asyncio.Event): + async def wait(self) -> bool: + started.set() + await release.wait() + return await super().wait() + + event = SetClearEvent() + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: + for _ in range(100): + if started.is_set(): + break + await asyncio.sleep(0) + assert started.is_set() + clock.now = 100.5 + event.set() + event.clear() + assert await asyncio.wait_for(task, 1.0) is True + assert "set" not in vars(event) + finally: + release.set() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +async def test_async_wait_for_event_uses_waiter_future_for_an_inherited_subclass( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + + class InheritedEvent(asyncio.Event): + pass + + event = InheritedEvent() + cutoff = clock.now + 0.05 + + async def send_signal() -> None: + for _ in range(100): + if event._waiters: + break + await asyncio.sleep(0) + assert event._waiters + clock.now = 100.01 + event.set() + clock.now = cutoff + 1.0 + + sender = asyncio.create_task(send_signal()) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + + async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) + loop = asyncio.get_running_loop() + timers: list[ManualTimer] = [] + + def manual_call_at(when: float, callback: Any, *args: Any) -> ManualTimer: + timer = ManualTimer(callback, args) + timers.append(timer) + return timer + + monkeypatch.setattr(loop, "call_at", manual_call_at) class WatchedEvent(asyncio.Event): - pass + async def wait(self) -> bool: + return await super().wait() event = WatchedEvent() first = asyncio.create_task(real_wait(event, clock.now + 0.01)) second = asyncio.create_task(real_wait(event, clock.now + 0.05)) try: + for _ in range(100): + watch = client_module._async_set_watches.get(id(event)) + if watch is not None and len(watch.deadlines) == 2: + break + await asyncio.sleep(0) + assert len(client_module._async_set_watches[id(event)].deadlines) == 2 + timers[0].fire() assert await asyncio.wait_for(first, 1.0) is False assert "set" in vars(event) event.set() @@ -2057,6 +2315,8 @@ class WatchedEvent(asyncio.Event): first.cancel() second.cancel() await asyncio.gather(first, second, return_exceptions=True) + for timer in timers: + timer.cancel() async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( From 63c2476e135056381809c8b1cf6fc734c1a6231e Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Fri, 27 Nov 2026 16:15:50 +0530 Subject: [PATCH 16/22] Address fifteenth Proofline review findings --- README.md | 2 +- proofline/client.py | 222 +++++++++++++++++++++++++++++++++--------- tests/test_http.py | 231 ++++++++++++++++++++++++++++++++++++-------- 3 files changed, 368 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 89f7cdef..ff96d9c5 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on the event itself instead of polling it in short slices. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. For standard event implementations the backoff waits on the event itself instead of polling it in short slices; synchronous `threading.Event` subclasses that override `wait()` use bounded 10 ms slices so a late waiter registration cannot stall cancellation. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 539054da..1ef0f82e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -215,12 +215,17 @@ def record(self, now: float) -> None: if self.signalled_at is None and now < self.end: self.signalled_at = now + def rollback(self, now: float) -> None: + if self.signalled_at == now: + self.signalled_at = None + class _ConditionSignalTracker: """Watch one condition, preserving whether overrides were instance attributes.""" - def __init__(self, condition: threading.Condition) -> None: + def __init__(self, condition: threading.Condition, event: threading.Event) -> None: self.condition = condition + self.event = event attributes = vars(condition) self.had_notify_all = "notify_all" in attributes self.saved_notify_all: Any = attributes.get("notify_all") @@ -233,6 +238,10 @@ def __init__(self, condition: threading.Condition) -> None: condition.notify = self.notify # type: ignore[method-assign] def record(self) -> None: + # A condition can notify for an unrelated state change. Only the event's + # own flag, read at notification time, proves a cancellation signal. + if not bool(getattr(self.event, "_flag", False)): + return now = monotonic() # Latch under the lock readers use, then notify after releasing it so a # waiter holding the condition lock cannot deadlock this tracker. @@ -277,12 +286,18 @@ def __init__(self, event: threading.Event) -> None: self.deadlines: set[_SignalDeadline] = set() def set_event(*args: Any, **kwargs: Any) -> Any: - result = self.original(*args, **kwargs) now = monotonic() with _sync_set_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: deadline.record(now) + try: + result = self.original(*args, **kwargs) + except BaseException: + for deadline in deadlines: + deadline.rollback(now) + raise + for deadline in deadlines: if deadline.signal_future is not None and not deadline.signal_future.done(): deadline.signal_future.set_result(None) return result @@ -309,7 +324,7 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ key = id(tracked) tracker = _notify_trackers.get(key) if tracker is None: - tracker = _ConditionSignalTracker(tracked) + tracker = _ConditionSignalTracker(tracked, event) _notify_trackers[key] = tracker tracker.deadlines.add(deadline) return deadline @@ -369,6 +384,21 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() +def _cancellation_signal( + event: threading.Event | AsyncEvent | None, deadline: _SignalDeadline +) -> bool: + """Honor a cancellation only when it was observed before the deadline.""" + if event is None: + return False + if deadline.signalled_at is not None: + return True + now = monotonic() + if now < deadline.end and _cancelled(event): + deadline.record(now) + return deadline.signalled_at is not None + return False + + def _invalid_response(error: ProoflineError) -> bool: return error.type == "urn:proofline:sdk:invalid-response" @@ -414,20 +444,21 @@ def _wait_for_event( with condition: if _sync_deadline_state(deadline)[0] is not None: return True - if getattr(event, "_flag", False) is True: + if bool(getattr(event, "_flag", False)): deadline.record(monotonic()) - return True - remaining = min(timeout, deadline.end - monotonic()) - if remaining <= 0: - return False - condition.wait(remaining) - signalled_at, now = _sync_deadline_state(deadline) - if signalled_at is not None: - return True - if getattr(event, "_flag", False) is True and now < deadline.end: - deadline.record(now) - return True - return False + return deadline.signalled_at is not None + end = min(monotonic() + timeout, deadline.end) + while True: + remaining = end - monotonic() + if remaining <= 0: + return deadline.signalled_at is not None + condition.wait(remaining) + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return True + if bool(getattr(event, "_flag", False)) and now < deadline.end: + deadline.record(now) + return deadline.signalled_at is not None # A subclass owns its wait primitive. Its public set() is the only verified # cancellation source, and short slices bound a missed wakeup. end = min(monotonic() + timeout, deadline.end) @@ -441,14 +472,14 @@ def _wait_for_event( # Do not call an overridable is_set() while holding the event condition. if event.is_set(): deadline.record(now) - return True + return deadline.signalled_at is not None woke = event.wait(min(remaining, 0.01)) signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: return True if woke and now < deadline.end and event.is_set(): deadline.record(now) - return True + return deadline.signalled_at is not None _async_set_lock = threading.Lock() @@ -469,12 +500,18 @@ def __init__(self, event: AsyncEvent) -> None: self.deadlines: set[_SignalDeadline] = set() def set_event(*args: Any, **kwargs: Any) -> Any: - result = self.original(*args, **kwargs) now = monotonic() with _async_set_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: deadline.record(now) + try: + result = self.original(*args, **kwargs) + except BaseException: + for deadline in deadlines: + deadline.rollback(now) + raise + for deadline in deadlines: if deadline.signal_future is not None and not deadline.signal_future.done(): deadline.signal_future.set_result(None) return result @@ -570,6 +607,78 @@ def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) - return False +_waiters_lock = threading.Lock() +_event_waiters_watches: dict[int, _AsyncWaitersWatch] = {} + + +class _AsyncWaitersWatch: + """Watch futures registered by an asyncio.Event's standard wait().""" + + def __init__(self, event: asyncio.Event) -> None: + self.event = event + attributes = _instance_attributes(event) + self.had_instance = "_waiters" in attributes + self.saved: Any = attributes.get("_waiters") + self.original: list[AsyncFuture[Any]] = getattr(event, "_waiters", []) + self.watched: list[AsyncFuture[Any]] = [] + self.deadlines: set[_SignalDeadline] = set() + watch = self + + class WatchedWaiters(list[AsyncFuture[Any]]): + def append(self, future: AsyncFuture[Any]) -> None: + with _waiters_lock: + deadlines = tuple(watch.deadlines) + for deadline in deadlines: + _watch_async_future(future, watch.event, deadline) + super().append(future) + + def remove(self, future: AsyncFuture[Any]) -> None: + try: + super().remove(future) + finally: + with _waiters_lock: + deadlines = tuple(watch.deadlines) + for deadline in deadlines: + _unwatch_async_future(future, deadline) + + self.watched = WatchedWaiters(self.original) + event._waiters = self.watched # type: ignore[assignment] + + def restore(self) -> None: + # A cancelled subclass waiter can still be suspended on a future in the + # watched list. Return it to the original list so its own cleanup works. + for future in self.watched: + if future not in self.original: + self.original.append(future) + if self.had_instance: + self.event._waiters = self.saved + else: + del self.event._waiters + + +def _watch_async_waiters(event: AsyncEvent, deadline: _SignalDeadline) -> bool: + if not isinstance(event, asyncio.Event): + return False + with _waiters_lock: + watch = _event_waiters_watches.get(id(event)) + if watch is None: + watch = _AsyncWaitersWatch(event) + _event_waiters_watches[id(event)] = watch + watch.deadlines.add(deadline) + return True + + +def _unwatch_async_waiters(event: AsyncEvent, deadline: _SignalDeadline) -> None: + with _waiters_lock: + watch = _event_waiters_watches.get(id(event)) + if watch is None: + return + watch.deadlines.discard(deadline) + if not watch.deadlines: + watch.restore() + del _event_waiters_watches[id(event)] + + async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: """Return True when the event is signalled before cutoff, False on timeout.""" loop = async_get_running_loop() @@ -582,12 +691,15 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: child: asyncio.Task[Any] | None = None future: AsyncFuture[Any] | None = None resumed = False + watched_set = False + watched_waiters = False try: - if type(event).wait is asyncio.Event.wait: + wait_method = event.wait + if getattr(wait_method, "__func__", None) is asyncio.Event.wait: # The standard wait() always suspends once on a registered future. # Driving it directly registers that waiter before yielding, and # the waiter future proves that the event itself woke the wait. - coro = event.wait() + coro = wait_method() try: awaited = coro.send(None) except StopIteration as stop: @@ -606,12 +718,18 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: pass return deadline.signalled_at is not None - # An overriding subclass owns its suspension sequence. Its public set() - # is the only verified cancellation source; a private signal future - # makes a set/clear before waiter registration wake this race at once. + # An overriding subclass owns its suspension sequence. Watch its public + # setter and the futures its standard wait delegates register, then race + # both against an independent signal future for a set/clear before the + # waiter exists. No task is joined after the cutoff. signal_future: AsyncFuture[None] = loop.create_future() deadline.signal_future = signal_future _watch_async_set(event, deadline) + watched_set = True + watched_waiters = _watch_async_waiters(event, deadline) + if _event_is_set(event): + deadline.record(monotonic()) + return deadline.signalled_at is not None def on_waiter_done(task: asyncio.Task[Any]) -> None: if task.cancelled() or task.exception() is not None: @@ -619,7 +737,7 @@ def on_waiter_done(task: asyncio.Task[Any]) -> None: if task.result() and _event_is_set(event): deadline.record(monotonic()) - child = loop.create_task(event.wait()) + child = loop.create_task(wait_method()) child.add_done_callback(on_waiter_done) await async_wait((child, timer, signal_future), return_when=FIRST_COMPLETED) if child.done() and not child.cancelled(): @@ -628,16 +746,12 @@ def on_waiter_done(task: asyncio.Task[Any]) -> None: return deadline.signalled_at is not None finally: handle.cancel() - _unwatch_async_set(event, deadline) + if watched_set: + _unwatch_async_set(event, deadline) + if watched_waiters: + _unwatch_async_waiters(event, deadline) if future is not None: - last_observer = _unwatch_async_future(future, deadline) - # A future shared by overlapping waits belongs to the remaining - # observers until the last one leaves. - if last_observer: - if future.done() and not future.cancelled(): - future.exception() - else: - future.cancel() + _unwatch_async_future(future, deadline) if coro is not None and not resumed: coro.close() if child is not None: @@ -667,8 +781,8 @@ def _sleep_with_cancel( return True end = _cancel_end(delay, cutoff) deadline = _SignalDeadline(end) - _track_sync_cancel(event, deadline) try: + _track_sync_cancel(event, deadline) while True: signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: @@ -1097,23 +1211,26 @@ def wait_for_review( return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None deadline_at = monotonic() + timeout + read_signal = _SignalDeadline(deadline_at) deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 try: + if cancel_event is not None: + _track_sync_cancel(cancel_event, read_signal) while (_transport.remaining() or 0) > 0: - if _cancelled(cancel_event): + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if _cancelled(cancel_event): - if _invalid_response(error): - raise + if _invalid_response(error) and _cancelled(cancel_event): + raise + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if _cancelled(cancel_event): + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) if (_transport.remaining() or 0) <= 0: break @@ -1124,11 +1241,15 @@ def wait_for_review( if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) - if (_transport.remaining() or 0) > 0 and _cancelled(cancel_event): + if (_transport.remaining() or 0) > 0 and _cancellation_signal( + cancel_event, read_signal + ): return _stopped(url, last, review_id, head_commit_sha) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: + if cancel_event is not None: + _untrack_sync_cancel(cancel_event, read_signal) _transport.DEADLINE.reset(deadline) @@ -1501,23 +1622,26 @@ async def wait_for_review( return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None deadline_at = monotonic() + timeout + read_signal = _SignalDeadline(deadline_at) deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 try: + if cancel_event is not None: + _watch_async_set(cancel_event, read_signal) while (_transport.remaining() or 0) > 0: - if _cancelled(cancel_event): + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if _cancelled(cancel_event): - if _invalid_response(error): - raise + if _invalid_response(error) and _cancelled(cancel_event): + raise + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break raise - if _cancelled(cancel_event): + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) if (_transport.remaining() or 0) <= 0: break @@ -1530,9 +1654,13 @@ async def wait_for_review( ): return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) - if (_transport.remaining() or 0) > 0 and _cancelled(cancel_event): + if (_transport.remaining() or 0) > 0 and _cancellation_signal( + cancel_event, read_signal + ): return _stopped(url, last, review_id, head_commit_sha) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: + if cancel_event is not None: + _unwatch_async_set(cancel_event, read_signal) _transport.DEADLINE.reset(deadline) diff --git a/tests/test_http.py b/tests/test_http.py index 1f35f79f..31981710 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -123,19 +123,38 @@ async def finish_sender(sender: asyncio.Task[Any]) -> None: class ManualTimer: """A call_at handle that fires only when the test explicitly says so.""" - def __init__(self, callback: Any, args: tuple[Any, ...]) -> None: + def __init__( + self, callback: Any, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None + ) -> None: self.callback = callback self.args = args + self.kwargs = kwargs or {} self.cancelled = False def fire(self) -> None: if not self.cancelled: - self.callback(*self.args) + self.callback(*self.args, **self.kwargs) def cancel(self) -> None: self.cancelled = True +def patch_helper_timer(monkeypatch: pytest.MonkeyPatch, loop: Any) -> list[ManualTimer]: + """Control the helper cutoff without capturing asyncio.wait_for's watchdog.""" + timers: list[ManualTimer] = [] + real_call_at = loop.call_at + + def call_at(when: float, callback: Any, *args: Any, **kwargs: Any) -> Any: + if getattr(callback, "__name__", None) == "set_result" and args == (None,): + timer = ManualTimer(callback, args, kwargs) + timers.append(timer) + return timer + return real_call_at(when, callback, *args, **kwargs) + + monkeypatch.setattr(loop, "call_at", call_at) + return timers + + class Clock: def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 @@ -1660,6 +1679,73 @@ async def send_signal() -> None: assert event.wait_calls == 1 +async def test_async_wait_for_event_accepts_an_instance_wait_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() + + async def wait_override() -> bool: + await asyncio.sleep(0) + return False + + event.wait = wait_override # type: ignore[method-assign] + task = asyncio.create_task(real_wait(event, clock.now + 0.01)) + try: + for _ in range(100): + if timers: + break + await asyncio.sleep(0) + assert timers + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + + +async def test_async_wait_for_event_latches_a_captured_setter_on_the_waiter_future( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + registered = asyncio.Event() + + async def wait_and_register(aws: Any, **kwargs: Any) -> Any: + registered.set() + kwargs["return_when"] = asyncio.FIRST_COMPLETED + return await asyncio.wait(aws, **kwargs) + + monkeypatch.setattr(client_module, "async_wait", wait_and_register) + + class CapturedEvent(asyncio.Event): + async def wait(self) -> bool: + return await super().wait() + + event = CapturedEvent() + setter = event.set + cutoff = clock.now + 0.01 + + async def send_signal() -> None: + await registered.wait() + while not event._waiters: + await asyncio.sleep(0) + setter() + clock.now = cutoff + 1.0 + + sender = asyncio.create_task(send_signal()) + try: + assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True + await finish_sender(sender) + finally: + sender.cancel() + await asyncio.gather(sender, return_exceptions=True) + + def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -1813,14 +1899,7 @@ async def test_async_wait_for_event_restores_waiter_after_cutoff_without_a_signa real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) loop = asyncio.get_running_loop() - timers: list[ManualTimer] = [] - - def manual_call_at(when: float, callback: Any, *args: Any) -> ManualTimer: - timer = ManualTimer(callback, args) - timers.append(timer) - return timer - - monkeypatch.setattr(loop, "call_at", manual_call_at) + timers = patch_helper_timer(monkeypatch, loop) class TrackedEvent(asyncio.Event): def __init__(self) -> None: @@ -1870,14 +1949,7 @@ async def test_async_wait_for_event_returns_at_cutoff_with_a_stubborn_waiter( real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) loop = asyncio.get_running_loop() - timers: list[ManualTimer] = [] - - def manual_call_at(when: float, callback: Any, *args: Any) -> ManualTimer: - timer = ManualTimer(callback, args) - timers.append(timer) - return timer - - monkeypatch.setattr(loop, "call_at", manual_call_at) + timers = patch_helper_timer(monkeypatch, loop) gate = asyncio.Event() class StubbornEvent(asyncio.Event): @@ -1972,6 +2044,47 @@ def wait(self, timeout: float | None = None) -> bool: assert "notify_all" not in vars(event.other) +def test_sleep_with_cancel_ignores_an_unrelated_own_condition_notification( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class NotifyingEvent(threading.Event): + def wait(self, timeout: float | None = None) -> bool: + with self._cond: + self._cond.notify_all() + clock.sleep(timeout or 0) + return False + + event = NotifyingEvent() + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + + +def test_sleep_with_cancel_restores_condition_after_a_set_hook_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class ReadOnlySetEvent(threading.Event): + @property + def set(self) -> Any: + raise AttributeError("set is read-only") + + def wait(self, timeout: float | None = None) -> bool: + return False + + event = ReadOnlySetEvent() + condition = event._cond + notify_all = condition.notify_all + with pytest.raises(AttributeError, match="set is read-only"): + client_module._sleep_with_cancel(0, event) + assert condition.notify_all == notify_all + + def test_sleep_with_cancel_tracks_a_backing_thread_event( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -2089,8 +2202,11 @@ def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( class ReentrantEvent(threading.Event): def is_set(self) -> bool: - with self._cond: - return super().is_set() + assert self._cond.acquire(blocking=False), "is_set called under the condition" + try: + return bool(self._flag) + finally: + self._cond.release() def wait(self, timeout: float | None = None) -> bool: clock.sleep(timeout or 0) @@ -2250,6 +2366,7 @@ async def test_async_wait_for_event_uses_waiter_future_for_an_inherited_subclass ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) class InheritedEvent(asyncio.Event): pass @@ -2274,6 +2391,8 @@ async def send_signal() -> None: finally: sender.cancel() await asyncio.gather(sender, return_exceptions=True) + for timer in timers: + timer.cancel() async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( @@ -2282,14 +2401,7 @@ async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) loop = asyncio.get_running_loop() - timers: list[ManualTimer] = [] - - def manual_call_at(when: float, callback: Any, *args: Any) -> ManualTimer: - timer = ManualTimer(callback, args) - timers.append(timer) - return timer - - monkeypatch.setattr(loop, "call_at", manual_call_at) + timers = patch_helper_timer(monkeypatch, loop) class WatchedEvent(asyncio.Event): async def wait(self) -> bool: @@ -2331,17 +2443,21 @@ async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( client_module._watch_async_future(future, event, first) client_module._watch_async_future(future, event, second) - assert future.set_result is not original_set_result - assert client_module._unwatch_async_future(future, first) is False - assert future.set_result is not original_set_result + try: + assert future.set_result is not original_set_result + assert client_module._unwatch_async_future(future, first) is False + assert future.set_result is not original_set_result - clock.now = 100.02 - event.set() - future.set_result(True) - assert first.signalled_at is None - assert second.signalled_at == 100.02 - assert client_module._unwatch_async_future(future, second) is True - assert future.set_result == original_set_result + clock.now = 100.02 + event.set() + future.set_result(True) + assert first.signalled_at is None + assert second.signalled_at == 100.02 + assert client_module._unwatch_async_future(future, second) is True + assert future.set_result == original_set_result + finally: + client_module._unwatch_async_future(future, first) + client_module._unwatch_async_future(future, second) async def test_async_wait_for_event_cancels_timer_on_wait_startup_failure( @@ -2442,6 +2558,7 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( body = review("RUNNING") body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) thread: threading.Thread | None = None + thread_started = False task: asyncio.Task[None] | None = None poll_task: asyncio.Task[Any] | None = None wait_elapsed: list[float] = [] @@ -2594,6 +2711,7 @@ async def set_event() -> None: if mode == "sync": thread = threading.Thread(target=set_event, daemon=True) thread.start() + thread_started = True result = await call( client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event ) @@ -2619,7 +2737,7 @@ async def set_event() -> None: result = poll_task.result() finally: release.set() - if thread is not None: + if thread_started and thread is not None: thread.join() supervised = [item for item in (poll_task, task) if item is not None] for item in supervised: @@ -2756,6 +2874,41 @@ def get_review(*args: Any, **kwargs: Any) -> Any: assert not event.is_set() +@MODES +async def test_wait_for_review_late_cancellation_after_read_keeps_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + real_get_review = client.get_review + + if mode == "sync": + + def get_review(*args: Any, **kwargs: Any) -> Any: + result = real_get_review(*args, **kwargs) + clock.now += 101.0 + event.set() + return result + + else: + + async def get_review(*args: Any, **kwargs: Any) -> Any: + result = await real_get_review(*args, **kwargs) + clock.now += 101.0 + event.set() + return result + + monkeypatch.setattr(client, "get_review", get_review) + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert result.status == "TIMED_OUT" + assert result.review is not None + assert event.is_set() + + @MODES async def test_wait_for_review_cancel_event_during_erroring_read_keeps_last_record( mode: str, monkeypatch: pytest.MonkeyPatch From 0e4f11023a1589ee4844d1bb9053fe4a08dc3a3c Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sat, 28 Nov 2026 14:02:51 +0530 Subject: [PATCH 17/22] Address sixteenth Proofline review findings --- README.md | 2 +- proofline/client.py | 323 ++++------ tests/test_http.py | 1389 +++++++++++++++---------------------------- 3 files changed, 587 insertions(+), 1127 deletions(-) diff --git a/README.md b/README.md index ff96d9c5..23553295 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. For standard event implementations the backoff waits on the event itself instead of polling it in short slices; synchronous `threading.Event` subclasses that override `wait()` use bounded 10 ms slices so a late waiter registration cannot stall cancellation. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored and leaves the outcome as `TIMED_OUT`. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 1ef0f82e..ccd8cdc2 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -203,6 +203,13 @@ def _instance_attributes(value: Any) -> dict[str, Any]: return getattr(value, "__dict__", {}) +def _thread_event_is_set(event: threading.Event) -> bool: + try: + return bool(event.is_set()) + except Exception: + return bool(getattr(event, "_flag", False)) + + class _SignalDeadline: def __init__(self, end: float) -> None: self.end = end @@ -210,14 +217,14 @@ def __init__(self, end: float) -> None: self.conditions: tuple[threading.Condition, ...] = () self.watched_set = False self.signal_future: Any = None + self.signal_event = threading.Event() - def record(self, now: float) -> None: + def record(self, now: float) -> bool: if self.signalled_at is None and now < self.end: self.signalled_at = now - - def rollback(self, now: float) -> None: - if self.signalled_at == now: - self.signalled_at = None + self.signal_event.set() + return True + return False class _ConditionSignalTracker: @@ -235,7 +242,15 @@ def __init__(self, condition: threading.Condition, event: threading.Event) -> No self.original_notify = condition.notify self.deadlines: set[_SignalDeadline] = set() condition.notify_all = self.notify_all # type: ignore[method-assign] - condition.notify = self.notify # type: ignore[method-assign] + try: + condition.notify = self.notify # type: ignore[method-assign] + except BaseException: + # Keep the partially installed hook observable to cleanup. + if self.had_notify_all: + condition.notify_all = self.saved_notify_all # type: ignore[assignment, method-assign] + else: + del condition.notify_all + raise def record(self) -> None: # A condition can notify for an unrelated state change. Only the event's @@ -287,19 +302,15 @@ def __init__(self, event: threading.Event) -> None: def set_event(*args: Any, **kwargs: Any) -> Any: now = monotonic() + result = self.original(*args, **kwargs) + if not _thread_event_is_set(self.event): + return result with _sync_set_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: - deadline.record(now) - try: - result = self.original(*args, **kwargs) - except BaseException: - for deadline in deadlines: - deadline.rollback(now) - raise - for deadline in deadlines: - if deadline.signal_future is not None and not deadline.signal_future.done(): - deadline.signal_future.set_result(None) + if deadline.record(now) and deadline.signal_future is not None: + if not deadline.signal_future.done(): + deadline.signal_future.set_result(None) return result event.set = set_event # type: ignore[method-assign] @@ -312,7 +323,7 @@ def restore(self) -> None: def _sync_inherited_wait(event: threading.Event) -> bool: - return type(event).wait is threading.Event.wait + return getattr(event.wait, "__func__", None) is threading.Event.wait def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: @@ -435,51 +446,21 @@ def _wait_for_event( """Return True when the event woke the wait, False when it timed out.""" if deadline is None: return event.wait(timeout) - inherited = _sync_inherited_wait(event) - condition = getattr(event, "_cond", None) if inherited else None - if isinstance(condition, threading.Condition): - # Plain events and subclasses that inherit Event.wait() share this - # condition for the flag and the waiter list. Checking and waiting under - # it makes a set/clear between those steps observable. - with condition: - if _sync_deadline_state(deadline)[0] is not None: - return True - if bool(getattr(event, "_flag", False)): - deadline.record(monotonic()) - return deadline.signalled_at is not None - end = min(monotonic() + timeout, deadline.end) - while True: - remaining = end - monotonic() - if remaining <= 0: - return deadline.signalled_at is not None - condition.wait(remaining) - signalled_at, now = _sync_deadline_state(deadline) - if signalled_at is not None: - return True - if bool(getattr(event, "_flag", False)) and now < deadline.end: - deadline.record(now) - return deadline.signalled_at is not None - # A subclass owns its wait primitive. Its public set() is the only verified - # cancellation source, and short slices bound a missed wakeup. + # The deadline's own signal is set by hooks on the event's condition and + # public setter. Waiting on it never calls an overridable wait() and never + # polls in short slices; a set/clear is still latched by the condition hook. end = min(monotonic() + timeout, deadline.end) while True: signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: return True - remaining = end - now - if remaining <= 0: + if now >= end: return False - # Do not call an overridable is_set() while holding the event condition. - if event.is_set(): - deadline.record(now) - return deadline.signalled_at is not None - woke = event.wait(min(remaining, 0.01)) - signalled_at, now = _sync_deadline_state(deadline) - if signalled_at is not None: - return True - if woke and now < deadline.end and event.is_set(): + if _thread_event_is_set(event): deadline.record(now) return deadline.signalled_at is not None + deadline.signal_event.wait(end - now) + deadline.signal_event.clear() _async_set_lock = threading.Lock() @@ -501,19 +482,15 @@ def __init__(self, event: AsyncEvent) -> None: def set_event(*args: Any, **kwargs: Any) -> Any: now = monotonic() + result = self.original(*args, **kwargs) + if not _event_is_set(self.event): + return result with _async_set_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: - deadline.record(now) - try: - result = self.original(*args, **kwargs) - except BaseException: - for deadline in deadlines: - deadline.rollback(now) - raise - for deadline in deadlines: - if deadline.signal_future is not None and not deadline.signal_future.done(): - deadline.signal_future.set_result(None) + if deadline.record(now) and deadline.signal_future is not None: + if not deadline.signal_future.done(): + deadline.signal_future.set_result(None) return result event.set = set_event # type: ignore[method-assign] @@ -607,76 +584,40 @@ def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) - return False -_waiters_lock = threading.Lock() -_event_waiters_watches: dict[int, _AsyncWaitersWatch] = {} - - -class _AsyncWaitersWatch: - """Watch futures registered by an asyncio.Event's standard wait().""" - - def __init__(self, event: asyncio.Event) -> None: - self.event = event - attributes = _instance_attributes(event) - self.had_instance = "_waiters" in attributes - self.saved: Any = attributes.get("_waiters") - self.original: list[AsyncFuture[Any]] = getattr(event, "_waiters", []) - self.watched: list[AsyncFuture[Any]] = [] - self.deadlines: set[_SignalDeadline] = set() - watch = self - - class WatchedWaiters(list[AsyncFuture[Any]]): - def append(self, future: AsyncFuture[Any]) -> None: - with _waiters_lock: - deadlines = tuple(watch.deadlines) - for deadline in deadlines: - _watch_async_future(future, watch.event, deadline) - super().append(future) - - def remove(self, future: AsyncFuture[Any]) -> None: - try: - super().remove(future) - finally: - with _waiters_lock: - deadlines = tuple(watch.deadlines) - for deadline in deadlines: - _unwatch_async_future(future, deadline) +class _AsyncSignalWaiter: + """A direct base wait() registration used only to observe a signal.""" - self.watched = WatchedWaiters(self.original) - event._waiters = self.watched # type: ignore[assignment] - - def restore(self) -> None: - # A cancelled subclass waiter can still be suspended on a future in the - # watched list. Return it to the original list so its own cleanup works. - for future in self.watched: - if future not in self.original: - self.original.append(future) - if self.had_instance: - self.event._waiters = self.saved - else: - del self.event._waiters + def __init__(self) -> None: + self.coro: Any = None + self.future: AsyncFuture[Any] | None = None -def _watch_async_waiters(event: AsyncEvent, deadline: _SignalDeadline) -> bool: +def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: + """Register an asyncio.Event waiter without driving subclass overrides.""" + waiter = _AsyncSignalWaiter() if not isinstance(event, asyncio.Event): - return False - with _waiters_lock: - watch = _event_waiters_watches.get(id(event)) - if watch is None: - watch = _AsyncWaitersWatch(event) - _event_waiters_watches[id(event)] = watch - watch.deadlines.add(deadline) - return True - - -def _unwatch_async_waiters(event: AsyncEvent, deadline: _SignalDeadline) -> None: - with _waiters_lock: - watch = _event_waiters_watches.get(id(event)) - if watch is None: - return - watch.deadlines.discard(deadline) - if not watch.deadlines: - watch.restore() - del _event_waiters_watches[id(event)] + return waiter + coro = asyncio.Event.wait(event) + try: + awaited = coro.send(None) + except StopIteration: + return waiter + waiter.coro = coro + waiter.future = cast(AsyncFuture[Any], awaited) + _watch_async_future(waiter.future, event, deadline) + return waiter + + +def _unwatch_async_waiter(waiter: _AsyncSignalWaiter, deadline: _SignalDeadline) -> None: + if waiter.future is not None: + _unwatch_async_future(waiter.future, deadline) + if not waiter.future.done(): + waiter.future.cancel() + if waiter.coro is not None: + try: + waiter.coro.close() + except RuntimeError: + pass async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: @@ -687,84 +628,28 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: deadline = _SignalDeadline(cutoff) timer: AsyncFuture[None] = loop.create_future() handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) - coro: Any = None - child: asyncio.Task[Any] | None = None - future: AsyncFuture[Any] | None = None - resumed = False + signal_future: AsyncFuture[None] = loop.create_future() + deadline.signal_future = signal_future + waiter = _AsyncSignalWaiter() watched_set = False - watched_waiters = False try: - wait_method = event.wait - if getattr(wait_method, "__func__", None) is asyncio.Event.wait: - # The standard wait() always suspends once on a registered future. - # Driving it directly registers that waiter before yielding, and - # the waiter future proves that the event itself woke the wait. - coro = wait_method() - try: - awaited = coro.send(None) - except StopIteration as stop: - resumed = True - if stop.value: - deadline.record(monotonic()) - return deadline.signalled_at is not None - future = cast(AsyncFuture[Any], awaited) - _watch_async_future(future, event, deadline) - await async_wait((future, timer), return_when=FIRST_COMPLETED) - if future.done() and not future.cancelled(): - resumed = True - try: - coro.send(None) - except StopIteration: - pass - return deadline.signalled_at is not None - - # An overriding subclass owns its suspension sequence. Watch its public - # setter and the futures its standard wait delegates register, then race - # both against an independent signal future for a set/clear before the - # waiter exists. No task is joined after the cutoff. - signal_future: AsyncFuture[None] = loop.create_future() - deadline.signal_future = signal_future _watch_async_set(event, deadline) watched_set = True - watched_waiters = _watch_async_waiters(event, deadline) + waiter = _watch_async_waiter(event, deadline) if _event_is_set(event): deadline.record(monotonic()) - return deadline.signalled_at is not None - - def on_waiter_done(task: asyncio.Task[Any]) -> None: - if task.cancelled() or task.exception() is not None: - return - if task.result() and _event_is_set(event): - deadline.record(monotonic()) - - child = loop.create_task(wait_method()) - child.add_done_callback(on_waiter_done) - await async_wait((child, timer, signal_future), return_when=FIRST_COMPLETED) - if child.done() and not child.cancelled(): - if child.result() and deadline.signalled_at is None and _event_is_set(event): - deadline.record(monotonic()) + if deadline.signalled_at is not None: + return True + awaited: tuple[AsyncFuture[Any], ...] = (timer, signal_future) + if waiter.future is not None: + awaited += (waiter.future,) + await async_wait(awaited, return_when=FIRST_COMPLETED) return deadline.signalled_at is not None finally: handle.cancel() if watched_set: _unwatch_async_set(event, deadline) - if watched_waiters: - _unwatch_async_waiters(event, deadline) - if future is not None: - _unwatch_async_future(future, deadline) - if coro is not None and not resumed: - coro.close() - if child is not None: - if child.done(): - if not child.cancelled(): - child.exception() - else: - child.cancel() - # Do not block the parent on subclass cleanup; observe the - # eventual result separately so exceptions are not orphaned. - child.add_done_callback( - lambda task: task.exception() if not task.cancelled() else None - ) + _unwatch_async_waiter(waiter, deadline) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -1198,7 +1083,8 @@ def wait_for_review( each poll, during the backoff, and after each read. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Those delays count toward the overall - wait deadline rather than a single HTTP timeout. + wait deadline rather than a single HTTP timeout. A signal first delivered + at or after the deadline is ignored and leaves the outcome as TIMED_OUT. """ if not math.isfinite(timeout) or timeout < 0: @@ -1223,9 +1109,10 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if _invalid_response(error) and _cancelled(cancel_event): + cancelled = _cancellation_signal(cancel_event, read_signal) + if _invalid_response(error) and cancelled: raise - if _cancellation_signal(cancel_event, read_signal): + if cancelled: return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break @@ -1241,16 +1128,16 @@ def wait_for_review( if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) - if (_transport.remaining() or 0) > 0 and _cancellation_signal( - cancel_event, read_signal - ): + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: - if cancel_event is not None: - _untrack_sync_cancel(cancel_event, read_signal) - _transport.DEADLINE.reset(deadline) + try: + if cancel_event is not None: + _untrack_sync_cancel(cancel_event, read_signal) + finally: + _transport.DEADLINE.reset(deadline) class AsyncProoflineClient(AsyncOperations): @@ -1625,18 +1512,25 @@ async def wait_for_review( read_signal = _SignalDeadline(deadline_at) deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 + read_waiter = _AsyncSignalWaiter() + watched_set = False try: if cancel_event is not None: _watch_async_set(cancel_event, read_signal) + watched_set = True + read_waiter = _watch_async_waiter(cancel_event, read_signal) + if _cancellation_signal(cancel_event, read_signal): + return _stopped(url, None, review_id, head_commit_sha) while (_transport.remaining() or 0) > 0: if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if _invalid_response(error) and _cancelled(cancel_event): + cancelled = _cancellation_signal(cancel_event, read_signal) + if _invalid_response(error) and cancelled: raise - if _cancellation_signal(cancel_event, read_signal): + if cancelled: return _stopped(url, last, review_id, head_commit_sha) if error.status == 0 and (_transport.remaining() or 0) <= 0: break @@ -1654,13 +1548,14 @@ async def wait_for_review( ): return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) - if (_transport.remaining() or 0) > 0 and _cancellation_signal( - cancel_event, read_signal - ): + if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) return timed_out or ReviewOutcome("TIMED_OUT", url) finally: - if cancel_event is not None: - _unwatch_async_set(cancel_event, read_signal) - _transport.DEADLINE.reset(deadline) + try: + if watched_set and cancel_event is not None: + _unwatch_async_set(cancel_event, read_signal) + _unwatch_async_waiter(read_waiter, read_signal) + finally: + _transport.DEADLINE.reset(deadline) diff --git a/tests/test_http.py b/tests/test_http.py index 31981710..406f962f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1490,35 +1490,34 @@ def unexpected_async_event_wait(*args: Any, **kwargs: Any) -> bool: assert len(server.requests) == 8 +async def wait_until(predicate: Any) -> None: + for _ in range(200): + if predicate(): + return + await asyncio.sleep(0) + raise AssertionError("the wait helper did not reach the expected state") + + async def test_async_wait_for_event_latches_a_set_then_clear( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() - - async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: - registered.set() - kwargs["return_when"] = asyncio.ALL_COMPLETED - return await asyncio.wait(aws, **kwargs) - - monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() - cutoff = clock.now + 0.01 - - async def send_signal() -> None: - await registered.wait() + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 event.set() event.clear() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(send_signal()) - try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + assert await asyncio.wait_for(task, 1.0) is True + assert "set" not in vars(event) finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() async def test_async_wait_for_event_ignores_a_signal_after_cutoff( @@ -1526,181 +1525,121 @@ async def test_async_wait_for_event_ignores_a_signal_after_cutoff( ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() - observed: list[Any] = [] - - async def wait_for_all_and_record(aws: Any, **kwargs: Any) -> Any: - observed.append(aws) - registered.set() - kwargs["return_when"] = asyncio.ALL_COMPLETED - return await asyncio.wait(aws, **kwargs) - - monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_record) - + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() cutoff = clock.now + 0.01 - signal_sent = False - - async def send_late_signal() -> None: - nonlocal signal_sent - await registered.wait() + task = asyncio.create_task(real_wait(event, cutoff)) + try: + await wait_until(lambda: bool(event._waiters)) clock.now = cutoff + 1.0 event.set() - signal_sent = True - - sender = asyncio.create_task(send_late_signal()) - try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False - await finish_sender(sender) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + assert event.is_set() finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) - assert signal_sent is True - assert len(observed) == 1 - waiter, timer = observed[0] - assert waiter.done() and waiter.result() is True - assert timer.done() + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() -async def test_async_wait_for_event_latches_delivery_before_a_late_resume( +async def test_async_wait_for_event_latches_a_captured_setter_on_the_waiter_future( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() - - async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: - registered.set() - kwargs["return_when"] = asyncio.ALL_COMPLETED - return await asyncio.wait(aws, **kwargs) - - monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() - cutoff = clock.now + 0.01 - - async def send_signal() -> None: - await registered.wait() - event.set() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(send_signal()) + setter = event.set + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 + setter() + assert await asyncio.wait_for(task, 1.0) is True finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() -async def test_async_wait_for_event_handles_a_subclass_that_yields_none_first( +async def test_async_wait_for_event_uses_a_base_waiter_for_an_inherited_subclass( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() - - async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: - registered.set() - kwargs["return_when"] = asyncio.ALL_COMPLETED - return await asyncio.wait(aws, **kwargs) - - monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) - - class YieldFirstEvent(asyncio.Event): - def __init__(self) -> None: - super().__init__() - self.suspensions = 0 - - async def wait(self) -> bool: - self.suspensions += 1 - await asyncio.sleep(0) - return await super().wait() - - event = YieldFirstEvent() - cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) - async def send_signal() -> None: - await registered.wait() - event.set() - clock.now = cutoff + 1.0 + class InheritedEvent(asyncio.Event): + pass - sender = asyncio.create_task(send_signal()) + event = InheritedEvent() + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 + event.set() + assert await asyncio.wait_for(task, 1.0) is True finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) - assert event.suspensions == 1 + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() -async def test_async_wait_for_event_honors_a_delegating_wait_override( +async def test_async_wait_for_event_does_not_call_a_subclass_wait_override( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() - - async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: - registered.set() - kwargs["return_when"] = asyncio.ALL_COMPLETED - return await asyncio.wait(aws, **kwargs) - - monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) - class DelegatingEvent(asyncio.Event): + class CountingEvent(asyncio.Event): def __init__(self) -> None: super().__init__() - self.backing = asyncio.Event() self.wait_calls = 0 async def wait(self) -> bool: self.wait_calls += 1 - return await asyncio.create_task(self.backing.wait()) + raise AssertionError("the helper must not call an overriding wait()") - def set(self) -> None: - self.backing.set() - - event = DelegatingEvent() - cutoff = clock.now + 0.01 - - async def send_signal() -> None: - await registered.wait() - event.set() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(send_signal()) + event = CountingEvent() + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await asyncio.wait_for(sender, 1.0) + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 + event.set() + assert await asyncio.wait_for(task, 1.0) is True + assert event.wait_calls == 0 finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) - assert event.wait_calls == 1 + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() -async def test_async_wait_for_event_accepts_an_instance_wait_override( +async def test_async_wait_for_event_does_not_call_an_instance_wait_override( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() + calls: list[int] = [] async def wait_override() -> bool: - await asyncio.sleep(0) - return False + calls.append(1) + raise AssertionError("the helper must not call an instance wait override") event.wait = wait_override # type: ignore[method-assign] - task = asyncio.create_task(real_wait(event, clock.now + 0.01)) + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - for _ in range(100): - if timers: - break - await asyncio.sleep(0) - assert timers - timers[0].fire() - assert await asyncio.wait_for(task, 1.0) is False + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 + event.set() + assert await asyncio.wait_for(task, 1.0) is True + assert calls == [] finally: task.cancel() await asyncio.gather(task, return_exceptions=True) @@ -1708,296 +1647,242 @@ async def wait_override() -> bool: timer.cancel() -async def test_async_wait_for_event_latches_a_captured_setter_on_the_waiter_future( +async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() + first = asyncio.create_task(real_wait(event, clock.now + 0.01)) + second = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: - async def wait_and_register(aws: Any, **kwargs: Any) -> Any: - registered.set() - kwargs["return_when"] = asyncio.FIRST_COMPLETED - return await asyncio.wait(aws, **kwargs) + def two_watches() -> bool: + watch = client_module._async_set_watches.get(id(event)) + return watch is not None and len(watch.deadlines) == 2 - monkeypatch.setattr(client_module, "async_wait", wait_and_register) + await wait_until(two_watches) + timers[0].fire() + assert await asyncio.wait_for(first, 1.0) is False + assert "set" in vars(event) + clock.now = 100.001 + event.set() + assert await asyncio.wait_for(second, 1.0) is True + assert "set" not in vars(event) + finally: + first.cancel() + second.cancel() + await asyncio.gather(first, second, return_exceptions=True) + for timer in timers: + timer.cancel() - class CapturedEvent(asyncio.Event): - async def wait(self) -> bool: - return await super().wait() - event = CapturedEvent() +async def test_async_wait_for_event_restores_the_waiter_and_setter_after_cutoff( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() setter = event.set - cutoff = clock.now + 0.01 - - async def send_signal() -> None: - await registered.wait() - while not event._waiters: - await asyncio.sleep(0) - setter() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(send_signal()) + task = asyncio.create_task(real_wait(event, clock.now + 0.01)) try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) + await wait_until(lambda: bool(event._waiters)) + assert "set" in vars(event) + future = next(iter(event._waiters)) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + assert "set" not in vars(event) + assert event.set == setter + assert future.cancelled() + assert not event._waiters finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() -def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( +async def test_async_wait_for_event_cancels_timer_when_waiter_registration_fails( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - - class DeadlineSignalEvent(threading.Event): - def wait(self, timeout: float | None = None) -> bool: - clock.now = 101.0 - self.set() - return True - - event = DeadlineSignalEvent() - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True - assert clock.delays == [] + real_wait = client_module._async_wait_for_event + loop = asyncio.get_running_loop() + handles: list[asyncio.TimerHandle] = [] + real_call_at = loop.call_at + def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: + handle = real_call_at(when, callback, *args) + handles.append(handle) + return handle -def test_sleep_with_cancel_latches_delivery_before_a_late_resume( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + monkeypatch.setattr(loop, "call_at", record_call_at) - class LateResumeEvent(threading.Event): - def wait(self, timeout: float | None = None) -> bool: - clock.now = 100.5 - self.set() - clock.now = 102.0 - return True + def fail(*args: Any) -> Any: + raise RuntimeError("registration failed") - event = LateResumeEvent() - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - assert clock.delays == [] + monkeypatch.setattr(client_module, "_watch_async_waiter", fail) + with pytest.raises(RuntimeError, match="registration failed"): + await real_wait(asyncio.Event(), loop.time() + 100.0) + assert handles + assert all(handle.cancelled() for handle in handles) -def test_sleep_with_cancel_records_a_captured_setter( +async def test_async_wait_for_event_cancels_timer_when_set_watch_fails( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + real_wait = client_module._async_wait_for_event + loop = asyncio.get_running_loop() + handles: list[asyncio.TimerHandle] = [] + real_call_at = loop.call_at - class CapturedSetterEvent(threading.Event): - setter: Any = None + def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: + handle = real_call_at(when, callback, *args) + handles.append(handle) + return handle - def wait(self, timeout: float | None = None) -> bool: - clock.now = 100.5 - self.setter() - clock.now = 102.0 - return True + monkeypatch.setattr(loop, "call_at", record_call_at) - event = CapturedSetterEvent() - event.setter = event.set - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - assert clock.delays == [] + def fail(*args: Any) -> None: + raise RuntimeError("set watch failed") + monkeypatch.setattr(client_module, "_watch_async_set", fail) + with pytest.raises(RuntimeError, match="set watch failed"): + await real_wait(asyncio.Event(), loop.time() + 100.0) + assert handles + assert all(handle.cancelled() for handle in handles) -async def test_async_wait_for_event_records_a_captured_setter( + +async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - registered = asyncio.Event() + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + original_set_result = future.set_result + first = client_module._SignalDeadline(clock.now + 0.01) + second = client_module._SignalDeadline(clock.now + 0.05) + + client_module._watch_async_future(future, event, first) + client_module._watch_async_future(future, event, second) + try: + assert future.set_result is not original_set_result + assert client_module._unwatch_async_future(future, first) is False + assert future.set_result is not original_set_result + + clock.now = 100.02 + event.set() + future.set_result(True) + assert first.signalled_at is None + assert second.signalled_at == 100.02 + assert client_module._unwatch_async_future(future, second) is True + assert future.set_result == original_set_result + finally: + client_module._unwatch_async_future(future, first) + client_module._unwatch_async_future(future, second) - async def wait_for_all_and_register(aws: Any, **kwargs: Any) -> Any: - registered.set() - kwargs["return_when"] = asyncio.ALL_COMPLETED - return await asyncio.wait(aws, **kwargs) - monkeypatch.setattr(client_module, "async_wait", wait_for_all_and_register) +async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: event = asyncio.Event() setter = event.set - cutoff = clock.now + 0.01 - async def send_signal() -> None: - await registered.wait() - setter() - clock.now = cutoff + 1.0 + assert await client_module._async_wait_for_event(event, time.monotonic() - 1.0) is False + assert event.set == setter + assert not event._waiters - sender = asyncio.create_task(send_signal()) - try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) - finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) + +async def test_async_wait_for_event_propagates_external_cancellation() -> None: + event = asyncio.Event() + task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) + await asyncio.sleep(0) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task -def test_sleep_with_cancel_does_not_replace_the_event_setter() -> None: +def test_sleep_with_cancel_returns_true_at_deadline_without_a_signal( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) event = threading.Event() - setter = event.set - condition = event._cond - notify_all = condition.notify_all + assert client_module._sleep_with_cancel(5, event, cutoff=clock.now) is True + assert clock.delays == [] - assert client_module._sleep_with_cancel(0, event) is True - assert event.set == setter - assert condition.notify_all == notify_all +def test_sleep_with_cancel_ignores_a_signal_set_at_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + clock.now = 101.0 + event.set() + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + assert clock.delays == [] -def test_sleep_with_cancel_records_a_set_clear_before_wait_registration( + +def test_sleep_with_cancel_latches_delivery_before_a_late_resume( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event - Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + clock = Clock(monkeypatch) + event = threading.Event() - class SetClearEvent(threading.Event): - def wait(self, timeout: float | None = None) -> bool: - self.set() - self.clear() - return False + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 100.5 + wait_event.set() + clock.now = 102.0 + return False - event = SetClearEvent() - condition = event._cond - notify_all = condition.notify_all + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert clock.delays == [] + + +def test_sleep_with_cancel_records_a_captured_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() setter = event.set + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 100.5 + setter() + clock.now = 102.0 + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - assert event.set == setter - assert condition.notify_all == notify_all + assert clock.delays == [] -def test_sleep_with_cancel_records_a_plain_event_set_clear_before_the_wait( +def test_sleep_with_cancel_records_a_set_clear_before_wait_registration( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event - Clock(monkeypatch) + clock = Clock(monkeypatch) event = threading.Event() - setter = event.set - clearer = event.clear condition = event._cond notify_all = condition.notify_all + setter = event.set def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - setter() - clearer() - return real_wait(wait_event, timeout, deadline) + clock.now = 100.5 + wait_event.set() + wait_event.clear() + clock.now = 102.0 + return False monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False assert event.set == setter assert condition.notify_all == notify_all - - -async def test_async_wait_for_event_restores_waiter_after_cutoff_without_a_signal( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - clock = Clock(monkeypatch) - loop = asyncio.get_running_loop() - timers = patch_helper_timer(monkeypatch, loop) - - class TrackedEvent(asyncio.Event): - def __init__(self) -> None: - super().__init__() - self.futures: list[asyncio.Future[bool]] = [] - self.finished = False - - async def wait(self) -> bool: - future = loop.create_future() - self._waiters.append(future) - self.futures.append(future) - try: - return await future - finally: - self.finished = True - self._waiters.remove(future) - - event = TrackedEvent() - task = asyncio.create_task(real_wait(event, clock.now + 0.01)) - try: - for _ in range(100): - if event.futures: - break - await asyncio.sleep(0) - assert event.futures - assert "set" in vars(event) - timers[0].fire() - assert await asyncio.wait_for(task, 1.0) is False - assert "set" not in vars(event) - for _ in range(100): - if event.finished: - break - await asyncio.sleep(0) - assert event.futures[0].cancelled() - assert event.finished - assert not event._waiters - finally: - task.cancel() - await asyncio.gather(task, return_exceptions=True) - for timer in timers: - timer.cancel() - - -async def test_async_wait_for_event_returns_at_cutoff_with_a_stubborn_waiter( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - clock = Clock(monkeypatch) - loop = asyncio.get_running_loop() - timers = patch_helper_timer(monkeypatch, loop) - gate = asyncio.Event() - - class StubbornEvent(asyncio.Event): - def __init__(self) -> None: - super().__init__() - self.started = asyncio.Event() - self.finished = False - - async def wait(self) -> bool: - self.started.set() - try: - await gate.wait() - except asyncio.CancelledError: - await gate.wait() - finally: - self.finished = True - return False - - event = StubbornEvent() - cutoff = clock.now + 0.01 - task = asyncio.create_task(real_wait(event, cutoff)) - try: - for _ in range(100): - if event.started.is_set(): - break - await asyncio.sleep(0) - assert event.started.is_set() - timers[0].fire() - assert await asyncio.wait_for(task, 1.0) is False - assert not event.finished - finally: - gate.set() - task.cancel() - await asyncio.gather(task, return_exceptions=True) - for timer in timers: - timer.cancel() - for _ in range(100): - if event.finished: - break - await asyncio.sleep(0) + assert clock.delays == [] def test_sleep_with_cancel_latches_an_inherited_wait_set_clear_before_registration( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) class InheritedEvent(threading.Event): def __init__(self) -> None: @@ -2005,14 +1890,22 @@ def __init__(self) -> None: event = self class RaceCondition(threading.Condition): - def wait(self, timeout: float | None = None) -> bool: + def notify_all(self, *args: Any, **kwargs: Any) -> None: event._flag = True - self.notify_all() - event._flag = False - return super().wait(0.01) + try: + super().notify_all(*args, **kwargs) + finally: + event._flag = False self._cond = RaceCondition(threading.Lock()) + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 100.5 + wait_event.set() + clock.now = 102.0 + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) event = InheritedEvent() condition = event._cond assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False @@ -2024,42 +1917,37 @@ def wait(self, timeout: float | None = None) -> bool: def test_sleep_with_cancel_ignores_an_unrelated_condition( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - - class UnrelatedEvent(threading.Event): - def __init__(self) -> None: - super().__init__() - self.other = threading.Condition() + event = threading.Event() + event.other = threading.Condition() # type: ignore[attr-defined] - def wait(self, timeout: float | None = None) -> bool: - with self.other: - self.other.notify_all() - clock.sleep(timeout or 0) - return False + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + other = getattr(wait_event, "other") + with other: + other.notify_all() + clock.now = 101.0 + return False - event = UnrelatedEvent() + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True - assert "notify_all" not in vars(event.other) + assert "notify_all" not in vars(event.other) # type: ignore[attr-defined] def test_sleep_with_cancel_ignores_an_unrelated_own_condition_notification( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + event = threading.Event() - class NotifyingEvent(threading.Event): - def wait(self, timeout: float | None = None) -> bool: - with self._cond: - self._cond.notify_all() - clock.sleep(timeout or 0) - return False + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + with wait_event._cond: + wait_event._cond.notify_all() + clock.now = 101.0 + return False - event = NotifyingEvent() + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + assert clock.delays == [] def test_sleep_with_cancel_restores_condition_after_a_set_hook_failure( @@ -2096,10 +1984,11 @@ class BackingEvent(threading.Event): def __init__(self) -> None: super().__init__() self.backing = threading.Event() - self.started = threading.Event() + + def is_set(self) -> bool: + return self.backing.is_set() def wait(self, timeout: float | None = None) -> bool: - self.started.set() return self.backing.wait(timeout) def set(self) -> None: @@ -2108,7 +1997,7 @@ def set(self) -> None: event = BackingEvent() def signal() -> None: - assert event.started.wait(1.0) + time.sleep(0.05) clock.now = 100.5 event.set() clock.now = 102.0 @@ -2142,9 +2031,6 @@ def __init__(self) -> None: super().__init__() self._cond = ClassCondition(threading.Lock()) - def wait(self, timeout: float | None = None) -> bool: - return False - event = InheritedEvent() condition = event._cond assert client_module._sleep_with_cancel(0, event) is True @@ -2168,368 +2054,95 @@ def notify_all() -> None: condition.notify_all = notify_all assert client_module._sleep_with_cancel(0, event) is True - assert condition.notify_all is notify_all - - -def test_sleep_with_cancel_ignores_a_nested_marker_event( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - - class MarkerEvent(threading.Event): - def __init__(self) -> None: - super().__init__() - self.marker = threading.Event() - - def wait(self, timeout: float | None = None) -> bool: - self.marker.set() - clock.sleep(timeout or 0) - return False - - event = MarkerEvent() - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True - assert "notify_all" not in vars(event.marker._cond) - - -def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - - class ReentrantEvent(threading.Event): - def is_set(self) -> bool: - assert self._cond.acquire(blocking=False), "is_set called under the condition" - try: - return bool(self._flag) - finally: - self._cond.release() - - def wait(self, timeout: float | None = None) -> bool: - clock.sleep(timeout or 0) - return False - - event = ReentrantEvent() - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True - - -def test_sleep_with_cancel_does_not_wrap_a_replaced_backing_condition( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._wait_for_event - Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - - class SwappingEvent(threading.Event): - def __init__(self) -> None: - super().__init__() - self.original_backing = threading.Event() - self.backing = self.original_backing - self.started = threading.Event() - self.swapped = False - - def wait(self, timeout: float | None = None) -> bool: - self.started.set() - return self.backing.wait(timeout) - - def is_set(self) -> bool: - if not self.swapped: - self.swapped = True - self.backing = threading.Event() - return self.backing.is_set() - - def set(self) -> None: - self.backing.set() - - event = SwappingEvent() - - def signal() -> None: - assert event.started.wait(1.0) - event.set() - - thread = threading.Thread(target=signal) - thread.start() - try: - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - finally: - thread.join(1.0) - assert not thread.is_alive() - assert "notify_all" not in vars(event.original_backing._cond) - assert "notify_all" not in vars(event.backing._cond) - - -async def test_async_wait_for_event_ignores_a_subclass_setup_gate( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - clock = Clock(monkeypatch) - - class GatedEvent(asyncio.Event): - def __init__(self) -> None: - super().__init__() - self.gate = asyncio.Event() - self.started = asyncio.Event() - - async def wait(self) -> bool: - self.started.set() - await self.gate.wait() - return await super().wait() - - event = GatedEvent() - cutoff = clock.now + 0.01 - - async def open_gate() -> None: - await event.started.wait() - event.gate.set() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(open_gate()) - try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is False - await finish_sender(sender) - finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) - - -async def test_async_wait_for_event_latches_a_late_subclass_registration( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - clock = Clock(monkeypatch) - started = asyncio.Event() - - class LateRegisterEvent(asyncio.Event): - async def wait(self) -> bool: - started.set() - for _ in range(20): - await asyncio.sleep(0) - return await super().wait() - - event = LateRegisterEvent() - cutoff = clock.now + 0.2 - - async def send_signal() -> None: - await started.wait() - for _ in range(2): - await asyncio.sleep(0) - event.set() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(send_signal()) - try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) - finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) - - -async def test_async_wait_for_event_latches_a_set_clear_before_subclass_wait_registers( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - clock = Clock(monkeypatch) - started = asyncio.Event() - release = asyncio.Event() - - class SetClearEvent(asyncio.Event): - async def wait(self) -> bool: - started.set() - await release.wait() - return await super().wait() - - event = SetClearEvent() - task = asyncio.create_task(real_wait(event, clock.now + 10.0)) - try: - for _ in range(100): - if started.is_set(): - break - await asyncio.sleep(0) - assert started.is_set() - clock.now = 100.5 - event.set() - event.clear() - assert await asyncio.wait_for(task, 1.0) is True - assert "set" not in vars(event) - finally: - release.set() - task.cancel() - await asyncio.gather(task, return_exceptions=True) - - -async def test_async_wait_for_event_uses_waiter_future_for_an_inherited_subclass( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - clock = Clock(monkeypatch) - timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) - - class InheritedEvent(asyncio.Event): - pass - - event = InheritedEvent() - cutoff = clock.now + 0.05 - - async def send_signal() -> None: - for _ in range(100): - if event._waiters: - break - await asyncio.sleep(0) - assert event._waiters - clock.now = 100.01 - event.set() - clock.now = cutoff + 1.0 - - sender = asyncio.create_task(send_signal()) - try: - assert await asyncio.wait_for(real_wait(event, cutoff), 1.0) is True - await finish_sender(sender) - finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) - for timer in timers: - timer.cancel() + assert condition.notify_all is notify_all -async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( +def test_sleep_with_cancel_ignores_a_nested_marker_event( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - loop = asyncio.get_running_loop() - timers = patch_helper_timer(monkeypatch, loop) + event = threading.Event() + event.marker = threading.Event() # type: ignore[attr-defined] - class WatchedEvent(asyncio.Event): - async def wait(self) -> bool: - return await super().wait() + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + marker = getattr(wait_event, "marker") + marker.set() + clock.now = 101.0 + return False - event = WatchedEvent() - first = asyncio.create_task(real_wait(event, clock.now + 0.01)) - second = asyncio.create_task(real_wait(event, clock.now + 0.05)) - try: - for _ in range(100): - watch = client_module._async_set_watches.get(id(event)) - if watch is not None and len(watch.deadlines) == 2: - break - await asyncio.sleep(0) - assert len(client_module._async_set_watches[id(event)].deadlines) == 2 - timers[0].fire() - assert await asyncio.wait_for(first, 1.0) is False - assert "set" in vars(event) - event.set() - assert await asyncio.wait_for(second, 1.0) is True - assert "set" not in vars(event) - finally: - first.cancel() - second.cancel() - await asyncio.gather(first, second, return_exceptions=True) - for timer in timers: - timer.cancel() + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True + assert "notify_all" not in vars(event.marker._cond) # type: ignore[attr-defined] -async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( +def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - event = asyncio.Event() - future = asyncio.get_running_loop().create_future() - original_set_result = future.set_result - first = client_module._SignalDeadline(clock.now + 0.01) - second = client_module._SignalDeadline(clock.now + 0.05) - - client_module._watch_async_future(future, event, first) - client_module._watch_async_future(future, event, second) - try: - assert future.set_result is not original_set_result - assert client_module._unwatch_async_future(future, first) is False - assert future.set_result is not original_set_result - - clock.now = 100.02 - event.set() - future.set_result(True) - assert first.signalled_at is None - assert second.signalled_at == 100.02 - assert client_module._unwatch_async_future(future, second) is True - assert future.set_result == original_set_result - finally: - client_module._unwatch_async_future(future, first) - client_module._unwatch_async_future(future, second) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + class ReentrantEvent(threading.Event): + def is_set(self) -> bool: + assert self._cond.acquire(blocking=False), "is_set called under the condition" + try: + return bool(self._flag) + finally: + self._cond.release() -async def test_async_wait_for_event_cancels_timer_on_wait_startup_failure( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._async_wait_for_event - loop = asyncio.get_running_loop() - handles: list[asyncio.TimerHandle] = [] - real_call_at = loop.call_at + event = ReentrantEvent() - def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: - handle = real_call_at(when, callback, *args) - handles.append(handle) - return handle + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 101.0 + return False - monkeypatch.setattr(loop, "call_at", record_call_at) - foreign = asyncio.new_event_loop() - try: - event = asyncio.Event() - event._loop = foreign - with pytest.raises(RuntimeError): - await real_wait(event, loop.time() + 100.0) - finally: - foreign.close() - assert handles - assert all(handle.cancelled() for handle in handles) + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True -async def test_async_wait_for_event_propagates_wait_failure_and_cancels_timer( +def test_sleep_with_cancel_does_not_wrap_a_replaced_backing_condition( monkeypatch: pytest.MonkeyPatch, ) -> None: - real_wait = client_module._async_wait_for_event - loop = asyncio.get_running_loop() - handles: list[asyncio.TimerHandle] = [] - real_call_at = loop.call_at + clock = Clock(monkeypatch) - def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: - handle = real_call_at(when, callback, *args) - handles.append(handle) - return handle + class SwappingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.backing = threading.Event() - monkeypatch.setattr(loop, "call_at", record_call_at) + def is_set(self) -> bool: + return self.backing.is_set() - class FailingEvent(asyncio.Event): - async def wait(self) -> bool: - failed: asyncio.Future[bool] = asyncio.get_running_loop().create_future() - failed.set_exception(RuntimeError("wait failed")) - await failed - return True + def set(self) -> None: + self.backing.set() - with pytest.raises(RuntimeError, match="wait failed"): - await real_wait(FailingEvent(), loop.time() + 100.0) - assert handles - assert all(handle.cancelled() for handle in handles) + event = SwappingEvent() + event.set() + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert clock.delays == [] + assert "notify_all" not in vars(event.backing._cond) -async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: - event = asyncio.Event() - setter = event.set +def test_sleep_with_cancel_supports_an_instance_wait_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() - assert await client_module._async_wait_for_event(event, time.monotonic() - 1.0) is False - assert event.set == setter - assert not event._waiters + def wait_override(timeout: float | None = None) -> bool: + clock.now = 100.5 + return False + event.wait = wait_override # type: ignore[method-assign] -async def test_async_wait_for_event_propagates_external_cancellation() -> None: - event = asyncio.Event() - task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) - await asyncio.sleep(0) - task.cancel() - with pytest.raises(asyncio.CancelledError): - await task + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 100.5 + wait_event.set() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert clock.delays == [] @MODES @@ -2555,207 +2168,51 @@ async def test_wait_for_review_cancel_event_stops_before_any_request( async def test_wait_for_review_cancel_event_wakes_real_backoff( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: + real_sync_wait = client_module._wait_for_event + real_async_wait = client_module._async_wait_for_event + Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_sync_wait) + monkeypatch.setattr(client_module, "_async_wait_for_event", real_async_wait) body = review("RUNNING") body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) - thread: threading.Thread | None = None - thread_started = False - task: asyncio.Task[None] | None = None - poll_task: asyncio.Task[Any] | None = None - wait_elapsed: list[float] = [] - wait_results: list[bool] = [] - failures: list[BaseException] = [] - event: Any - release: Any - abort: Any + event: Any = asyncio.Event() if mode == "async" else threading.Event() + setter: Any = None - if mode == "sync": - - class SignallingEvent(threading.Event): - """A threading.Event that exposes real waiter registration.""" - - def __init__(self) -> None: - super().__init__() - self._condition = threading.Condition(threading.Lock()) - self._waiters = 0 - self.waiter_registered = threading.Event() - - def is_set(self) -> bool: - with self._condition: - return self._flag - - def set(self) -> None: - with self._condition: - self._flag = True - self._condition.notify_all() - - def clear(self) -> None: - with self._condition: - self._flag = False - - def wait(self, timeout: float | None = None) -> bool: - deadline = None if timeout is None else time.monotonic() + timeout - with self._condition: - if self._flag: - return True - self._waiters += 1 - # Setting this under the condition lock means set() cannot - # run until this waiter has released the lock in wait(). - self.waiter_registered.set() - try: - while not self._flag: - remaining = None if deadline is None else deadline - time.monotonic() - if remaining is not None and remaining <= 0: - return False - self._condition.wait(remaining) - return True - finally: - self._waiters -= 1 - - event = SignallingEvent() - release = threading.Event() - abort = threading.Event() - real_wait = client_module._wait_for_event - - def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - started = time.monotonic() - try: - woke = real_wait(wait_event, timeout, deadline) - wait_results.append(woke) - if abort.is_set() and failures: - raise failures[0] - return woke - finally: - wait_elapsed.append(time.monotonic() - started) + if mode == "async": - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + async def set_later() -> None: + await asyncio.sleep(0.05) + event.set() - def set_event() -> None: - deadline = time.monotonic() + 10.0 - while not event.waiter_registered.is_set() and not release.is_set(): - if time.monotonic() >= deadline: - failures.append(AssertionError("waiter registration timed out")) - event.set() - abort.set() - return - release.wait(0.01) - if not release.is_set() and event.waiter_registered.is_set(): - event.set() + setter = asyncio.create_task(set_later()) else: - class SignallingEventAsync(asyncio.Event): - """An Event double that signals once the built-in wait registers.""" - - def __init__(self) -> None: - super().__init__() - self.waiter_registered = asyncio.Event() - - def _get_loop(self) -> Any: - self.waiter_registered.set() - return super()._get_loop() - - event = SignallingEventAsync() - release = asyncio.Event() - abort = asyncio.Event() - real_async_wait = client_module._async_wait_for_event - - async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: - started = time.monotonic() - try: - if abort.is_set(): - raise failures[0] - wait_task = asyncio.create_task(real_async_wait(wait_event, cutoff)) - abort_task = asyncio.create_task(abort.wait()) - try: - await asyncio.wait((wait_task, abort_task), return_when=asyncio.FIRST_COMPLETED) - if abort_task.done(): - raise failures[0] - result = wait_task.result() - wait_results.append(result) - return result - finally: - supervised = (wait_task, abort_task) - for item in supervised: - if not item.done(): - item.cancel() - await asyncio.gather(*supervised, return_exceptions=True) - finally: - wait_elapsed.append(time.monotonic() - started) - - monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) + def set_later() -> None: + time.sleep(0.05) + event.set() - async def set_event() -> None: - registration = asyncio.create_task(event.waiter_registered.wait()) - teardown = asyncio.create_task(release.wait()) - try: - await asyncio.wait( - (registration, teardown), - timeout=10.0, - return_when=asyncio.FIRST_COMPLETED, - ) - if release.is_set(): - return - if not registration.done(): - failures.append(AssertionError("waiter registration timed out")) - abort.set() - return - event.set() - finally: - for item in (registration, teardown): - if not item.done(): - item.cancel() - await asyncio.gather(registration, teardown, return_exceptions=True) + setter = threading.Thread(target=set_later, daemon=True) + setter.start() + started = time.monotonic() with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: try: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + finally: if mode == "sync": - thread = threading.Thread(target=set_event, daemon=True) - thread.start() - thread_started = True - result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event - ) + setter.join(1.0) else: - poll_task = asyncio.create_task( - call( - client, - "wait_for_review", - ORG, - REVIEW, - timeout=100, - cancel_event=event, - ) - ) - task = asyncio.create_task(set_event()) - await asyncio.wait((poll_task, task), return_when=asyncio.FIRST_COMPLETED) - if task.done(): - await task - if failures: - raise failures[0] - result = await asyncio.wait_for(poll_task, 5.0) - else: - result = poll_task.result() - finally: - release.set() - if thread_started and thread is not None: - thread.join() - supervised = [item for item in (poll_task, task) if item is not None] - for item in supervised: - if not item.done(): - item.cancel() - if supervised: - await asyncio.gather(*supervised, return_exceptions=True) - assert len(server.requests) == 1 + setter.cancel() + await asyncio.gather(setter, return_exceptions=True) - if failures: - raise failures[0] - - assert event.waiter_registered.is_set() - assert wait_elapsed - assert wait_elapsed[0] < 2.0 - assert wait_results[0] is True + assert time.monotonic() - started < 2.0 + assert len(server.requests) == 1 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." + assert result.review is not None assert result.review.id == REVIEW @@ -2978,6 +2435,114 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert clock.delays == [5.0] +@MODES +async def test_wait_for_review_invalid_response_after_set_clear_still_raises( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + if mode == "sync": + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + event.clear() + raise _transport.invalid_response() + + else: + + async def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + event.clear() + raise _transport.invalid_response() + + monkeypatch.setattr(client, "get_review", get_review) + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert len(server.requests) == 0 + + +@MODES +async def test_wait_for_review_records_cancellation_at_the_backoff_cutoff( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + body = review("RUNNING") + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + + if mode == "sync": + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 105.0 + wait_event.set() + wait_event.clear() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + else: + + async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: + clock.now = 105.0 + wait_event.set() + wait_event.clear() + return False + + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) + + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review is not None + assert result.review.id == REVIEW + + +@MODES +async def test_wait_for_review_resets_deadline_when_observer_cleanup_raises( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + if mode == "sync": + + def untrack(*args: Any) -> None: + raise RuntimeError("cleanup failed") + + monkeypatch.setattr(client_module, "_untrack_sync_cancel", untrack) + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + raise ProoflineError(503, "urn:proofline:sdk:test", "boom") + + else: + + def unwatch(*args: Any) -> None: + raise RuntimeError("cleanup failed") + + monkeypatch.setattr(client_module, "_unwatch_async_set", unwatch) + + async def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + raise ProoflineError(503, "urn:proofline:sdk:test", "boom") + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + monkeypatch.setattr(client, "get_review", get_review) + with pytest.raises(RuntimeError, match="cleanup failed"): + await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) + assert _transport.DEADLINE.get() is None + assert server.requests == [] + + @MODES async def test_wait_for_review_rejects_an_unknown_cancel_event_type( mode: str, monkeypatch: pytest.MonkeyPatch From c9753b616ef490c7039007f060b6ea77c668d084 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sat, 28 Nov 2026 14:18:44 +0530 Subject: [PATCH 18/22] Address seventeenth Proofline review findings --- README.md | 2 +- proofline/client.py | 176 ++++++++++++++++++++----------- tests/test_http.py | 247 ++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 353 insertions(+), 72 deletions(-) diff --git a/README.md b/README.md index 23553295..82a6e6ee 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored and leaves the outcome as `TIMED_OUT`. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored and leaves the outcome as `TIMED_OUT`. Cancellation must be observable on the event you pass: call `set()` on that event rather than a cached bound setter, and do not mutate a delegating event's backing object directly, because the SDK cannot observe those pulses and can miss a set-then-clear. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index ccd8cdc2..c712f0cf 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -203,7 +203,7 @@ def _instance_attributes(value: Any) -> dict[str, Any]: return getattr(value, "__dict__", {}) -def _thread_event_is_set(event: threading.Event) -> bool: +def _thread_event_is_set(event: threading.Event | AsyncEvent) -> bool: try: return bool(event.is_set()) except Exception: @@ -230,9 +230,8 @@ def record(self, now: float) -> bool: class _ConditionSignalTracker: """Watch one condition, preserving whether overrides were instance attributes.""" - def __init__(self, condition: threading.Condition, event: threading.Event) -> None: + def __init__(self, condition: threading.Condition) -> None: self.condition = condition - self.event = event attributes = vars(condition) self.had_notify_all = "notify_all" in attributes self.saved_notify_all: Any = attributes.get("notify_all") @@ -240,10 +239,12 @@ def __init__(self, condition: threading.Condition, event: threading.Event) -> No self.saved_notify: Any = attributes.get("notify") self.original_notify_all = condition.notify_all self.original_notify = condition.notify - self.deadlines: set[_SignalDeadline] = set() - condition.notify_all = self.notify_all # type: ignore[method-assign] + self.subscribers: dict[_SignalDeadline, threading.Event] = {} + self.installed_notify_all = self.notify_all + self.installed_notify = self.notify + condition.notify_all = self.installed_notify_all # type: ignore[method-assign] try: - condition.notify = self.notify # type: ignore[method-assign] + condition.notify = self.installed_notify # type: ignore[method-assign] except BaseException: # Keep the partially installed hook observable to cleanup. if self.had_notify_all: @@ -253,16 +254,14 @@ def __init__(self, condition: threading.Condition, event: threading.Event) -> No raise def record(self) -> None: - # A condition can notify for an unrelated state change. Only the event's - # own flag, read at notification time, proves a cancellation signal. - if not bool(getattr(self.event, "_flag", False)): - return - now = monotonic() - # Latch under the lock readers use, then notify after releasing it so a - # waiter holding the condition lock cannot deadlock this tracker. + # Observation, timestamping, and publication share the lock that guards + # the final timeout decision and unsubscribe, so a waiter cannot miss a + # signal delivered before its cutoff. with _notify_lock: - for deadline in tuple(self.deadlines): - deadline.record(now) + for deadline, event in tuple(self.subscribers.items()): + if not bool(getattr(event, "_flag", False)): + continue + deadline.record(monotonic()) def notify_all(self) -> None: self.record() @@ -273,14 +272,16 @@ def notify(self, *args: Any, **kwargs: Any) -> None: self.original_notify(*args, **kwargs) def restore(self) -> None: - if self.had_notify_all: - self.condition.notify_all = self.saved_notify_all # type: ignore[method-assign] - else: - del self.condition.notify_all - if self.had_notify: - self.condition.notify = self.saved_notify # type: ignore[method-assign] - else: - del self.condition.notify + if getattr(self.condition, "notify_all", None) is self.installed_notify_all: + if self.had_notify_all: + self.condition.notify_all = self.saved_notify_all # type: ignore[method-assign] + else: + del self.condition.notify_all + if getattr(self.condition, "notify", None) is self.installed_notify: + if self.had_notify: + self.condition.notify = self.saved_notify # type: ignore[method-assign] + else: + del self.condition.notify _notify_lock = threading.Lock() @@ -301,10 +302,13 @@ def __init__(self, event: threading.Event) -> None: self.deadlines: set[_SignalDeadline] = set() def set_event(*args: Any, **kwargs: Any) -> Any: - now = monotonic() result = self.original(*args, **kwargs) if not _thread_event_is_set(self.event): return result + # Timestamp the observed flag, not entry into the setter: an + # override may set the flag only after this point. A delivery + # observed by a condition hook is already latched and wins here. + now = monotonic() with _sync_set_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: @@ -313,9 +317,12 @@ def set_event(*args: Any, **kwargs: Any) -> Any: deadline.signal_future.set_result(None) return result - event.set = set_event # type: ignore[method-assign] + self.installed = set_event + event.set = self.installed # type: ignore[method-assign] def restore(self) -> None: + if getattr(self.event, "set", None) is not self.installed: + return if self.had_instance: self.event.set = self.saved # type: ignore[method-assign] else: @@ -335,9 +342,9 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ key = id(tracked) tracker = _notify_trackers.get(key) if tracker is None: - tracker = _ConditionSignalTracker(tracked, event) + tracker = _ConditionSignalTracker(tracked) _notify_trackers[key] = tracker - tracker.deadlines.add(deadline) + tracker.subscribers[deadline] = event return deadline @@ -348,8 +355,8 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> tracker = _notify_trackers.get(key) if tracker is None: continue - tracker.deadlines.discard(deadline) - if not tracker.deadlines: + tracker.subscribers.pop(deadline, None) + if not tracker.subscribers: tracker.restore() del _notify_trackers[key] deadline.conditions = () @@ -395,19 +402,29 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: return event is not None and event.is_set() +def _record_signal_before( + event: threading.Event | AsyncEvent | None, deadline: _SignalDeadline, end: float +) -> bool: + """Latch a signal only after reading the flag, under the publication lock.""" + if deadline.signalled_at is not None: + return True + if event is None or not _thread_event_is_set(event): + return False + with _notify_lock: + if deadline.signalled_at is not None: + return True + now = monotonic() + if now < end: + deadline.record(now) + return True + return False + + def _cancellation_signal( event: threading.Event | AsyncEvent | None, deadline: _SignalDeadline ) -> bool: """Honor a cancellation only when it was observed before the deadline.""" - if event is None: - return False - if deadline.signalled_at is not None: - return True - now = monotonic() - if now < deadline.end and _cancelled(event): - deadline.record(now) - return deadline.signalled_at is not None - return False + return _record_signal_before(event, deadline, deadline.end) def _invalid_response(error: ProoflineError) -> bool: @@ -451,14 +468,13 @@ def _wait_for_event( # polls in short slices; a set/clear is still latched by the condition hook. end = min(monotonic() + timeout, deadline.end) while True: + if _record_signal_before(event, deadline, end): + return True signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: return True if now >= end: return False - if _thread_event_is_set(event): - deadline.record(now) - return deadline.signalled_at is not None deadline.signal_event.wait(end - now) deadline.signal_event.clear() @@ -481,10 +497,13 @@ def __init__(self, event: AsyncEvent) -> None: self.deadlines: set[_SignalDeadline] = set() def set_event(*args: Any, **kwargs: Any) -> Any: - now = monotonic() result = self.original(*args, **kwargs) if not _event_is_set(self.event): return result + # Timestamp the observed flag, not entry into the setter: an + # override may set the flag only after this point. A delivery + # observed by a waiter hook is already latched and wins here. + now = monotonic() with _async_set_lock: deadlines = tuple(self.deadlines) for deadline in deadlines: @@ -493,9 +512,12 @@ def set_event(*args: Any, **kwargs: Any) -> Any: deadline.signal_future.set_result(None) return result - event.set = set_event # type: ignore[method-assign] + self.installed = set_event + event.set = self.installed # type: ignore[method-assign] def restore(self) -> None: + if getattr(self.event, "set", None) is not self.installed: + return if self.had_instance: self.event.set = self.saved # type: ignore[method-assign] else: @@ -523,9 +545,12 @@ def set_result(result: Any) -> None: deadline.record(now) self.original(result) - future.set_result = set_result # type: ignore[method-assign] + self.installed = set_result + future.set_result = self.installed # type: ignore[method-assign] def restore(self) -> None: + if getattr(self.future, "set_result", None) is not self.installed: + return if self.had_instance: self.future.set_result = self.saved # type: ignore[method-assign] else: @@ -604,7 +629,20 @@ def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncS return waiter waiter.coro = coro waiter.future = cast(AsyncFuture[Any], awaited) - _watch_async_future(waiter.future, event, deadline) + try: + _watch_async_future(waiter.future, event, deadline) + except BaseException: + # The future is already registered with the event. Drop that + # registration before propagating, or the event retains a suspended + # coroutine with its traceback after the caller exits. + waiter.future.cancel() + try: + coro.close() + except RuntimeError: + pass + waiter.coro = None + waiter.future = None + raise return waiter @@ -647,9 +685,11 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: return deadline.signalled_at is not None finally: handle.cancel() - if watched_set: - _unwatch_async_set(event, deadline) - _unwatch_async_waiter(waiter, deadline) + try: + if watched_set: + _unwatch_async_set(event, deadline) + finally: + _unwatch_async_waiter(waiter, deadline) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -674,22 +714,15 @@ def _sleep_with_cancel( return False if now >= end: return True - if _cancelled(event): - # Read the flag before the final cutoff check: a signal at or - # after the cutoff cannot turn a timeout into a stop. - signalled_at, now = _sync_deadline_state(deadline) - if signalled_at is not None: - return False - if now < end: - deadline.record(now) - return False - return True + # The flag is read before the clock, so a signal delivered at or + # after the cutoff cannot be stamped with an earlier clock value. + if _record_signal_before(event, deadline, end): + return False if not _wait_for_event(event, end - now, deadline): signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: return False - if now < end and _cancelled(event): - deadline.record(now) + if now < end and _record_signal_before(event, deadline, end): return False return True finally: @@ -1085,6 +1118,11 @@ def wait_for_review( transport retries and their delays. Those delays count toward the overall wait deadline rather than a single HTTP timeout. A signal first delivered at or after the deadline is ignored and leaves the outcome as TIMED_OUT. + + The signal must be observable through the supplied event's own flag and + condition. Call ``set()`` on the event passed here; a cached bound + setter or a direct mutation of a delegating event's backing object is + not supported and can be missed. """ if not math.isfinite(timeout) or timeout < 0: @@ -1499,6 +1537,16 @@ async def wait_for_review( head_commit_sha: str | None = None, cancel_event: AsyncEvent | None = None, ) -> ReviewOutcome: + """Wait for recorded review completion or return TIMED_OUT. + + cancel_event stops the wait before another request. It is checked before + each poll, during the backoff, and after each read. An in-flight read is + not interrupted. A signal first delivered at or after the deadline is + ignored and leaves the outcome as TIMED_OUT. The signal must be + observable through the supplied event's own flag and waiter + registration: call ``set()`` on the event passed here, not a cached + bound setter or a direct mutation of a backing object. + """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") _head_commit(head_commit_sha) @@ -1554,8 +1602,10 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: try: - if watched_set and cancel_event is not None: - _unwatch_async_set(cancel_event, read_signal) - _unwatch_async_waiter(read_waiter, read_signal) + try: + if watched_set and cancel_event is not None: + _unwatch_async_set(cancel_event, read_signal) + finally: + _unwatch_async_waiter(read_waiter, read_signal) finally: _transport.DEADLINE.reset(deadline) diff --git a/tests/test_http.py b/tests/test_http.py index 406f962f..b398436d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1783,6 +1783,224 @@ async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( client_module._unwatch_async_future(future, second) +def test_cancellation_signal_reads_the_flag_before_the_clock( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + deadline = client_module._SignalDeadline(101.0) + + def is_set() -> bool: + # The flag becomes true only after the old pre-clock read would have + # sampled 100.5, so a late signal must not be stamped with that value. + clock.now = 101.5 + return True + + monkeypatch.setattr(event, "is_set", is_set) + assert client_module._cancellation_signal(event, deadline) is False + assert deadline.signalled_at is None + + +def test_sync_set_watch_timestamps_a_late_flag_after_the_setter_returns( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class LateFlagEvent(threading.Event): + def set(self) -> None: + clock.now = 101.5 + super().set() + + event = LateFlagEvent() + deadline = client_module._SignalDeadline(101.0) + client_module._watch_sync_set(event, deadline) + try: + event.set() + assert event.is_set() + assert deadline.signalled_at is None + finally: + client_module._unwatch_sync_set(event, deadline) + + +async def test_async_set_watch_timestamps_a_late_flag_after_the_setter_returns( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class LateFlagEvent(asyncio.Event): + def set(self) -> None: + clock.now = 101.5 + super().set() + + event = LateFlagEvent() + deadline = client_module._SignalDeadline(101.0) + client_module._watch_async_set(event, deadline) + try: + event.set() + assert event.is_set() + assert deadline.signalled_at is None + finally: + client_module._unwatch_async_set(event, deadline) + + +def test_sync_set_watch_preserves_a_replacement_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + deadline = client_module._SignalDeadline(clock.now + 10.0) + + def replacement() -> None: + return None + + client_module._watch_sync_set(event, deadline) + try: + event.set = replacement # type: ignore[method-assign] + finally: + client_module._unwatch_sync_set(event, deadline) + assert event.set is replacement + + +async def test_async_set_watch_preserves_a_replacement_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + deadline = client_module._SignalDeadline(clock.now + 10.0) + + def replacement() -> None: + return None + + client_module._watch_async_set(event, deadline) + try: + event.set = replacement # type: ignore[method-assign] + finally: + client_module._unwatch_async_set(event, deadline) + assert event.set is replacement + + +async def test_async_future_watch_preserves_a_replacement_set_result( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + deadline = client_module._SignalDeadline(clock.now + 10.0) + + def replacement(result: Any) -> None: + return None + + client_module._watch_async_future(future, event, deadline) + try: + future.set_result = replacement # type: ignore[method-assign] + finally: + client_module._unwatch_async_future(future, deadline) + assert future.set_result is replacement + + +async def test_async_wait_for_event_unregisters_waiter_when_restore_raises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + loop = asyncio.get_running_loop() + timers = patch_helper_timer(monkeypatch, loop) + event = asyncio.Event() + real_unwatch = client_module._unwatch_async_set + captured: list[tuple[Any, Any]] = [] + + def raise_on_unwatch(event_arg: Any, deadline_arg: Any) -> None: + captured.append((event_arg, deadline_arg)) + raise RuntimeError("restore failed") + + monkeypatch.setattr(client_module, "_unwatch_async_set", raise_on_unwatch) + task = asyncio.create_task(client_module._async_wait_for_event(event, loop.time() + 100.0)) + try: + await wait_until(lambda: bool(event._waiters)) + timers[0].fire() + with pytest.raises(RuntimeError, match="restore failed"): + await task + assert not event._waiters + assert id(event) not in client_module._async_future_watches + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + monkeypatch.setattr(client_module, "_unwatch_async_set", real_unwatch) + for event_arg, deadline_arg in captured: + real_unwatch(event_arg, deadline_arg) + + +async def test_async_waiter_registration_failure_drops_the_waiter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + deadline = client_module._SignalDeadline(clock.now + 10.0) + captured: list[asyncio.Future[Any]] = [] + + def fail(future: asyncio.Future[Any], event_arg: Any, deadline_arg: Any) -> None: + captured.append(future) + raise RuntimeError("hook failed") + + monkeypatch.setattr(client_module, "_watch_async_future", fail) + with pytest.raises(RuntimeError, match="hook failed"): + client_module._watch_async_waiter(event, deadline) + assert captured + assert captured[0].cancelled() + assert not event._waiters + + +def test_condition_tracker_validates_each_subscriber_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + first = threading.Event() + second = threading.Event() + first._cond = condition + second._cond = condition + first_deadline = client_module._SignalDeadline(clock.now + 10.0) + second_deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(first, first_deadline) + client_module._track_thread_signal(second, second_deadline) + try: + first.set() + assert first_deadline.signalled_at == clock.now + assert second_deadline.signalled_at is None + + client_module._untrack_thread_signal(first, first_deadline) + tracker = client_module._notify_trackers.get(id(condition)) + assert tracker is not None + assert len(tracker.subscribers) == 1 + + second.set() + assert second_deadline.signalled_at == clock.now + finally: + client_module._untrack_thread_signal(first, first_deadline) + client_module._untrack_thread_signal(second, second_deadline) + + +def test_condition_tracker_preserves_a_replaced_notify_all( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + deadline = client_module._SignalDeadline(clock.now + 10.0) + + def replacement() -> None: + return None + + client_module._track_thread_signal(event, deadline) + try: + condition.notify_all = replacement # type: ignore[method-assign] + finally: + client_module._untrack_thread_signal(event, deadline) + assert condition.notify_all is replacement + assert "notify" not in vars(condition) + + async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: event = asyncio.Event() setter = event.set @@ -2511,6 +2729,8 @@ async def test_wait_for_review_resets_deadline_when_observer_cleanup_raises( ) -> None: Clock(monkeypatch) event = asyncio.Event() if mode == "async" else threading.Event() + real_unwatch = client_module._unwatch_async_set + captured: list[tuple[Any, Any]] = [] if mode == "sync": @@ -2525,7 +2745,8 @@ def get_review(*args: Any, **kwargs: Any) -> Any: else: - def unwatch(*args: Any) -> None: + def unwatch(event_arg: Any, deadline_arg: Any) -> None: + captured.append((event_arg, deadline_arg)) raise RuntimeError("cleanup failed") monkeypatch.setattr(client_module, "_unwatch_async_set", unwatch) @@ -2534,13 +2755,23 @@ async def get_review(*args: Any, **kwargs: Any) -> Any: event.set() raise ProoflineError(503, "urn:proofline:sdk:test", "boom") - with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session(mode, server.url) as client: - monkeypatch.setattr(client, "get_review", get_review) - with pytest.raises(RuntimeError, match="cleanup failed"): - await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) - assert _transport.DEADLINE.get() is None - assert server.requests == [] + try: + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + monkeypatch.setattr(client, "get_review", get_review) + with pytest.raises(RuntimeError, match="cleanup failed"): + await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert _transport.DEADLINE.get() is None + if mode == "async": + assert not getattr(event, "_waiters") + assert id(event) not in client_module._async_future_watches + assert server.requests == [] + finally: + monkeypatch.setattr(client_module, "_unwatch_async_set", real_unwatch) + for event_arg, deadline_arg in captured: + real_unwatch(event_arg, deadline_arg) @MODES From 44474404d615adbefcf97d6e77d14305c97f5a9b Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sat, 28 Nov 2026 15:01:22 +0530 Subject: [PATCH 19/22] Address eighteenth Proofline review findings --- README.md | 2 +- proofline/client.py | 331 ++++++++++++++++++--------------------- tests/test_http.py | 372 ++++++++++++++++++++++++++++++++++++-------- 3 files changed, 459 insertions(+), 246 deletions(-) diff --git a/README.md b/README.md index 82a6e6ee..55b6373d 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(cancel.set) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored and leaves the outcome as `TIMED_OUT`. Cancellation must be observable on the event you pass: call `set()` on that event rather than a cached bound setter, and do not mutate a delegating event's backing object directly, because the SDK cannot observe those pulses and can miss a set-then-clear. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event rather than a cached bound setter. For `asyncio.Event`, the setter must notify waiters registered on that same event; changing only a backing object's flag is not observable. The SDK never binds the caller's async event to the wait's loop, so the same event may be reused later. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index c712f0cf..3c0897fd 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -11,6 +11,7 @@ from asyncio import get_running_loop as async_get_running_loop from asyncio import sleep as async_sleep from asyncio import wait as async_wait +from collections import deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from string import hexdigits from time import monotonic, sleep @@ -216,7 +217,6 @@ def __init__(self, end: float) -> None: self.signalled_at: float | None = None self.conditions: tuple[threading.Condition, ...] = () self.watched_set = False - self.signal_future: Any = None self.signal_event = threading.Event() def record(self, now: float) -> bool: @@ -227,6 +227,26 @@ def record(self, now: float) -> bool: return False +def _restore_method(target: Any, name: str, had_instance: bool, saved: Any, installed: Any) -> None: + """Restore one hooked attribute only while it still holds our wrapper.""" + if getattr(target, name, None) is not installed: + return + if had_instance: + setattr(target, name, saved) + else: + delattr(target, name) + + +def _rollback_condition_hook( + condition: threading.Condition, name: str, had_instance: bool, saved: Any, installed: Any +) -> None: + """Attempt one rollback without hiding the setup failure.""" + try: + _restore_method(condition, name, had_instance, saved, installed) + except Exception: + pass + + class _ConditionSignalTracker: """Watch one condition, preserving whether overrides were instance attributes.""" @@ -246,22 +266,32 @@ def __init__(self, condition: threading.Condition) -> None: try: condition.notify = self.installed_notify # type: ignore[method-assign] except BaseException: - # Keep the partially installed hook observable to cleanup. - if self.had_notify_all: - condition.notify_all = self.saved_notify_all # type: ignore[assignment, method-assign] - else: - del condition.notify_all + _rollback_condition_hook( + condition, + "notify_all", + self.had_notify_all, + self.saved_notify_all, + self.installed_notify_all, + ) + _rollback_condition_hook( + condition, + "notify", + self.had_notify, + self.saved_notify, + self.installed_notify, + ) raise def record(self) -> None: # Observation, timestamping, and publication share the lock that guards # the final timeout decision and unsubscribe, so a waiter cannot miss a - # signal delivered before its cutoff. + # signal delivered before its cutoff. One notification is stamped once + # and reused for every deadline watching that event. with _notify_lock: + now = monotonic() for deadline, event in tuple(self.subscribers.items()): - if not bool(getattr(event, "_flag", False)): - continue - deadline.record(monotonic()) + if bool(getattr(event, "_flag", False)): + deadline.record(now) def notify_all(self) -> None: self.record() @@ -272,19 +302,23 @@ def notify(self, *args: Any, **kwargs: Any) -> None: self.original_notify(*args, **kwargs) def restore(self) -> None: - if getattr(self.condition, "notify_all", None) is self.installed_notify_all: - if self.had_notify_all: - self.condition.notify_all = self.saved_notify_all # type: ignore[method-assign] - else: - del self.condition.notify_all - if getattr(self.condition, "notify", None) is self.installed_notify: - if self.had_notify: - self.condition.notify = self.saved_notify # type: ignore[method-assign] - else: - del self.condition.notify - - -_notify_lock = threading.Lock() + _restore_method( + self.condition, + "notify_all", + self.had_notify_all, + self.saved_notify_all, + self.installed_notify_all, + ) + _restore_method( + self.condition, + "notify", + self.had_notify, + self.saved_notify, + self.installed_notify, + ) + + +_notify_lock = threading.RLock() _notify_trackers: dict[int, _ConditionSignalTracker] = {} _sync_set_lock = threading.Lock() _sync_set_watches: dict[int, _SyncSetWatch] = {} @@ -305,32 +339,22 @@ def set_event(*args: Any, **kwargs: Any) -> Any: result = self.original(*args, **kwargs) if not _thread_event_is_set(self.event): return result - # Timestamp the observed flag, not entry into the setter: an - # override may set the flag only after this point. A delivery - # observed by a condition hook is already latched and wins here. - now = monotonic() with _sync_set_lock: deadlines = tuple(self.deadlines) - for deadline in deadlines: - if deadline.record(now) and deadline.signal_future is not None: - if not deadline.signal_future.done(): - deadline.signal_future.set_result(None) + # The clock and publication share the lock used by the final + # timeout check and unsubscribe, so a signal stamped before the + # cutoff cannot be missed after that check has run. + with _notify_lock: + now = monotonic() + for deadline in deadlines: + deadline.record(now) return result self.installed = set_event event.set = self.installed # type: ignore[method-assign] def restore(self) -> None: - if getattr(self.event, "set", None) is not self.installed: - return - if self.had_instance: - self.event.set = self.saved # type: ignore[method-assign] - else: - del self.event.set - - -def _sync_inherited_wait(event: threading.Event) -> bool: - return getattr(event.wait, "__func__", None) is threading.Event.wait + _restore_method(self.event, "set", self.had_instance, self.saved, self.installed) def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: @@ -349,17 +373,29 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: - with _notify_lock: - for condition in deadline.conditions: - key = id(condition) - tracker = _notify_trackers.get(key) - if tracker is None: - continue - tracker.subscribers.pop(deadline, None) - if not tracker.subscribers: - tracker.restore() - del _notify_trackers[key] - deadline.conditions = () + to_restore: list[_ConditionSignalTracker] = [] + try: + with _notify_lock: + for condition in deadline.conditions: + key = id(condition) + tracker = _notify_trackers.get(key) + if tracker is None: + continue + tracker.subscribers.pop(deadline, None) + if not tracker.subscribers: + del _notify_trackers[key] + to_restore.append(tracker) + finally: + deadline.conditions = () + error: Exception | None = None + for tracker in to_restore: + try: + tracker.restore() + except Exception as exc: + if error is None: + error = exc + if error is not None: + raise error def _watch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: @@ -373,29 +409,35 @@ def _watch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: def _unwatch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: + deadline.watched_set = False + to_restore: _SyncSetWatch | None = None with _sync_set_lock: watch = _sync_set_watches.get(id(event)) if watch is None: return watch.deadlines.discard(deadline) if not watch.deadlines: - watch.restore() del _sync_set_watches[id(event)] - deadline.watched_set = False + to_restore = watch + if to_restore is not None: + to_restore.restore() def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: # The event's own condition catches captured setter calls; the public set # hook additionally catches subclasses that delegate to a backing event. + # Install both even when wait() is inherited: an overridden set() can still + # notify only a backing event's condition. _track_thread_signal(event, deadline) - if not _sync_inherited_wait(event): - _watch_sync_set(event, deadline) + _watch_sync_set(event, deadline) def _untrack_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: - if deadline.watched_set: - _unwatch_sync_set(event, deadline) - _untrack_thread_signal(event, deadline) + try: + if deadline.watched_set: + _unwatch_sync_set(event, deadline) + finally: + _untrack_thread_signal(event, deadline) def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: @@ -479,51 +521,10 @@ def _wait_for_event( deadline.signal_event.clear() -_async_set_lock = threading.Lock() _async_future_lock = threading.Lock() -_async_set_watches: dict[int, _AsyncSetWatch] = {} _async_future_watches: dict[int, _AsyncFutureWatch] = {} -class _AsyncSetWatch: - """One shared hook on an event's public set(), with independent observers.""" - - def __init__(self, event: AsyncEvent) -> None: - self.event = event - attributes = _instance_attributes(event) - self.had_instance = "set" in attributes - self.saved: Any = attributes.get("set") - self.original = event.set - self.deadlines: set[_SignalDeadline] = set() - - def set_event(*args: Any, **kwargs: Any) -> Any: - result = self.original(*args, **kwargs) - if not _event_is_set(self.event): - return result - # Timestamp the observed flag, not entry into the setter: an - # override may set the flag only after this point. A delivery - # observed by a waiter hook is already latched and wins here. - now = monotonic() - with _async_set_lock: - deadlines = tuple(self.deadlines) - for deadline in deadlines: - if deadline.record(now) and deadline.signal_future is not None: - if not deadline.signal_future.done(): - deadline.signal_future.set_result(None) - return result - - self.installed = set_event - event.set = self.installed # type: ignore[method-assign] - - def restore(self) -> None: - if getattr(self.event, "set", None) is not self.installed: - return - if self.had_instance: - self.event.set = self.saved # type: ignore[method-assign] - else: - del self.event.set - - class _AsyncFutureWatch: """One shared hook on a waiter future, with independent observers.""" @@ -549,12 +550,7 @@ def set_result(result: Any) -> None: future.set_result = self.installed # type: ignore[method-assign] def restore(self) -> None: - if getattr(self.future, "set_result", None) is not self.installed: - return - if self.had_instance: - self.future.set_result = self.saved # type: ignore[method-assign] - else: - del self.future.set_result + _restore_method(self.future, "set_result", self.had_instance, self.saved, self.installed) def _event_is_set(event: AsyncEvent) -> bool: @@ -564,26 +560,6 @@ def _event_is_set(event: AsyncEvent) -> bool: return False -def _watch_async_set(event: AsyncEvent, deadline: _SignalDeadline) -> None: - with _async_set_lock: - watch = _async_set_watches.get(id(event)) - if watch is None: - watch = _AsyncSetWatch(event) - _async_set_watches[id(event)] = watch - watch.deadlines.add(deadline) - - -def _unwatch_async_set(event: AsyncEvent, deadline: _SignalDeadline) -> None: - with _async_set_lock: - watch = _async_set_watches.get(id(event)) - if watch is None: - return - watch.deadlines.discard(deadline) - if not watch.deadlines: - watch.restore() - del _async_set_watches[id(event)] - - def _watch_async_future( future: AsyncFuture[Any], event: AsyncEvent, deadline: _SignalDeadline ) -> None: @@ -602,60 +578,67 @@ def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) - if watch is None: return False watch.deadlines.discard(deadline) - if not watch.deadlines: - watch.restore() + last = not watch.deadlines + if last: del _async_future_watches[id(future)] - return True - return False + if last: + watch.restore() + return last class _AsyncSignalWaiter: - """A direct base wait() registration used only to observe a signal.""" + """A future registered directly on the event, without driving overrides.""" def __init__(self) -> None: - self.coro: Any = None + self.event: AsyncEvent | None = None self.future: AsyncFuture[Any] | None = None def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: - """Register an asyncio.Event waiter without driving subclass overrides.""" + """Observe a signal without binding the caller's event to this loop.""" waiter = _AsyncSignalWaiter() if not isinstance(event, asyncio.Event): return waiter - coro = asyncio.Event.wait(event) - try: - awaited = coro.send(None) - except StopIteration: - return waiter - waiter.coro = coro - waiter.future = cast(AsyncFuture[Any], awaited) + loop = async_get_running_loop() + future: AsyncFuture[Any] = loop.create_future() + waiters = getattr(event, "_waiters", None) + if waiters is None: + waiters = deque() + event._waiters = waiters + waiters.append(future) + waiter.event = event + waiter.future = future try: - _watch_async_future(waiter.future, event, deadline) + _watch_async_future(future, event, deadline) except BaseException: - # The future is already registered with the event. Drop that - # registration before propagating, or the event retains a suspended - # coroutine with its traceback after the caller exits. - waiter.future.cancel() try: - coro.close() - except RuntimeError: + waiters.remove(future) + except ValueError: pass - waiter.coro = None + future.cancel() + waiter.event = None waiter.future = None raise return waiter def _unwatch_async_waiter(waiter: _AsyncSignalWaiter, deadline: _SignalDeadline) -> None: - if waiter.future is not None: - _unwatch_async_future(waiter.future, deadline) - if not waiter.future.done(): - waiter.future.cancel() - if waiter.coro is not None: - try: - waiter.coro.close() - except RuntimeError: - pass + try: + if waiter.future is not None: + _unwatch_async_future(waiter.future, deadline) + finally: + future = waiter.future + event = waiter.event + if future is not None: + if event is not None: + waiters = getattr(event, "_waiters", None) + if waiters is not None: + try: + waiters.remove(future) + except ValueError: + pass + if not future.done(): + future.cancel() async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: @@ -666,30 +649,21 @@ async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: deadline = _SignalDeadline(cutoff) timer: AsyncFuture[None] = loop.create_future() handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) - signal_future: AsyncFuture[None] = loop.create_future() - deadline.signal_future = signal_future waiter = _AsyncSignalWaiter() - watched_set = False try: - _watch_async_set(event, deadline) - watched_set = True waiter = _watch_async_waiter(event, deadline) if _event_is_set(event): deadline.record(monotonic()) if deadline.signalled_at is not None: return True - awaited: tuple[AsyncFuture[Any], ...] = (timer, signal_future) + awaited: tuple[AsyncFuture[Any], ...] = (timer,) if waiter.future is not None: awaited += (waiter.future,) await async_wait(awaited, return_when=FIRST_COMPLETED) return deadline.signalled_at is not None finally: handle.cancel() - try: - if watched_set: - _unwatch_async_set(event, deadline) - finally: - _unwatch_async_waiter(waiter, deadline) + _unwatch_async_waiter(waiter, deadline) def _cancel_end(delay: float, cutoff: float | None) -> float: @@ -1117,7 +1091,8 @@ def wait_for_review( not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Those delays count toward the overall wait deadline rather than a single HTTP timeout. A signal first delivered - at or after the deadline is ignored and leaves the outcome as TIMED_OUT. + at or after the deadline is ignored; it does not change the wait's result + or suppress a read error that would otherwise propagate. The signal must be observable through the supplied event's own flag and condition. Call ``set()`` on the event passed here; a cached bound @@ -1542,10 +1517,11 @@ async def wait_for_review( cancel_event stops the wait before another request. It is checked before each poll, during the backoff, and after each read. An in-flight read is not interrupted. A signal first delivered at or after the deadline is - ignored and leaves the outcome as TIMED_OUT. The signal must be - observable through the supplied event's own flag and waiter - registration: call ``set()`` on the event passed here, not a cached - bound setter or a direct mutation of a backing object. + ignored; it does not change the wait's result or suppress a read error + that would otherwise propagate. The signal must notify waiters + registered on the event passed here: call ``set()`` on that event and + do not only mutate a backing object's flag. The SDK observes the signal + through its own waiter without binding the caller's event to the loop. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1561,11 +1537,8 @@ async def wait_for_review( deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 read_waiter = _AsyncSignalWaiter() - watched_set = False try: if cancel_event is not None: - _watch_async_set(cancel_event, read_signal) - watched_set = True read_waiter = _watch_async_waiter(cancel_event, read_signal) if _cancellation_signal(cancel_event, read_signal): return _stopped(url, None, review_id, head_commit_sha) @@ -1602,10 +1575,6 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: try: - try: - if watched_set and cancel_event is not None: - _unwatch_async_set(cancel_event, read_signal) - finally: - _unwatch_async_waiter(read_waiter, read_signal) + _unwatch_async_waiter(read_waiter, read_signal) finally: _transport.DEADLINE.reset(deadline) diff --git a/tests/test_http.py b/tests/test_http.py index b398436d..4dacf89f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1647,29 +1647,26 @@ async def wait_override() -> bool: timer.cancel() -async def test_async_wait_for_event_overlapping_waits_keep_the_set_watch( +async def test_async_wait_for_event_overlapping_waits_keep_both_waiters( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() + setter = event.set first = asyncio.create_task(real_wait(event, clock.now + 0.01)) second = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - - def two_watches() -> bool: - watch = client_module._async_set_watches.get(id(event)) - return watch is not None and len(watch.deadlines) == 2 - - await wait_until(two_watches) + await wait_until(lambda: len(event._waiters) >= 2) timers[0].fire() assert await asyncio.wait_for(first, 1.0) is False - assert "set" in vars(event) + assert event.set == setter + assert "set" not in vars(event) clock.now = 100.001 event.set() assert await asyncio.wait_for(second, 1.0) is True - assert "set" not in vars(event) + assert not event._waiters finally: first.cancel() second.cancel() @@ -1678,7 +1675,7 @@ def two_watches() -> bool: timer.cancel() -async def test_async_wait_for_event_restores_the_waiter_and_setter_after_cutoff( +async def test_async_wait_for_event_restores_the_waiter_without_touching_the_setter( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event @@ -1689,14 +1686,14 @@ async def test_async_wait_for_event_restores_the_waiter_and_setter_after_cutoff( task = asyncio.create_task(real_wait(event, clock.now + 0.01)) try: await wait_until(lambda: bool(event._waiters)) - assert "set" in vars(event) future = next(iter(event._waiters)) timers[0].fire() assert await asyncio.wait_for(task, 1.0) is False - assert "set" not in vars(event) assert event.set == setter + assert "set" not in vars(event) assert future.cancelled() assert not event._waiters + assert id(future) not in client_module._async_future_watches finally: task.cancel() await asyncio.gather(task, return_exceptions=True) @@ -1729,7 +1726,7 @@ def fail(*args: Any) -> Any: assert all(handle.cancelled() for handle in handles) -async def test_async_wait_for_event_cancels_timer_when_set_watch_fails( +async def test_async_wait_for_event_cancels_timer_when_future_hook_fails( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._async_wait_for_event @@ -1744,14 +1741,16 @@ def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandl monkeypatch.setattr(loop, "call_at", record_call_at) - def fail(*args: Any) -> None: - raise RuntimeError("set watch failed") + def fail(future: Any, event: Any, deadline: Any) -> None: + raise RuntimeError("future hook failed") - monkeypatch.setattr(client_module, "_watch_async_set", fail) - with pytest.raises(RuntimeError, match="set watch failed"): - await real_wait(asyncio.Event(), loop.time() + 100.0) + monkeypatch.setattr(client_module, "_watch_async_future", fail) + event = asyncio.Event() + with pytest.raises(RuntimeError, match="future hook failed"): + await real_wait(event, loop.time() + 100.0) assert handles assert all(handle.cancelled() for handle in handles) + assert not event._waiters async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( @@ -1822,25 +1821,54 @@ def set(self) -> None: client_module._unwatch_sync_set(event, deadline) -async def test_async_set_watch_timestamps_a_late_flag_after_the_setter_returns( +async def test_async_wait_for_event_supports_a_read_only_setter( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + + class ReadOnlySetEvent(asyncio.Event): + @property + def set(self) -> Any: + return asyncio.Event.set.__get__(self, asyncio.Event) + + event = ReadOnlySetEvent() + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 + event.set() + assert await asyncio.wait_for(task, 1.0) is True + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + + +async def test_async_wait_for_event_requires_notification_on_the_event() -> None: + class BackingOnlyEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.backing = asyncio.Event() + + def is_set(self) -> bool: + return self.backing.is_set() - class LateFlagEvent(asyncio.Event): def set(self) -> None: - clock.now = 101.5 - super().set() + self.backing.set() - event = LateFlagEvent() - deadline = client_module._SignalDeadline(101.0) - client_module._watch_async_set(event, deadline) + event = BackingOnlyEvent() + task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 0.05)) try: + await wait_until(lambda: bool(event._waiters)) event.set() + assert await asyncio.wait_for(task, 1.0) is False assert event.is_set() - assert deadline.signalled_at is None finally: - client_module._unwatch_async_set(event, deadline) + task.cancel() + await asyncio.gather(task, return_exceptions=True) def test_sync_set_watch_preserves_a_replacement_setter( @@ -1861,22 +1889,30 @@ def replacement() -> None: assert event.set is replacement -async def test_async_set_watch_preserves_a_replacement_setter( +async def test_async_wait_for_event_preserves_a_replacement_setter( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() - deadline = client_module._SignalDeadline(clock.now + 10.0) def replacement() -> None: return None - client_module._watch_async_set(event, deadline) + event.set = replacement # type: ignore[method-assign] + task = asyncio.create_task(real_wait(event, clock.now + 0.01)) try: - event.set = replacement # type: ignore[method-assign] + await wait_until(lambda: bool(event._waiters)) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + assert event.set is replacement + assert not event._waiters finally: - client_module._unwatch_async_set(event, deadline) - assert event.set is replacement + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() async def test_async_future_watch_preserves_a_replacement_set_result( @@ -1904,30 +1940,32 @@ async def test_async_wait_for_event_unregisters_waiter_when_restore_raises( loop = asyncio.get_running_loop() timers = patch_helper_timer(monkeypatch, loop) event = asyncio.Event() - real_unwatch = client_module._unwatch_async_set - captured: list[tuple[Any, Any]] = [] + real_restore = client_module._AsyncFutureWatch.restore + captured: list[Any] = [] - def raise_on_unwatch(event_arg: Any, deadline_arg: Any) -> None: - captured.append((event_arg, deadline_arg)) + def raise_on_restore(watch: Any) -> None: + captured.append(watch) raise RuntimeError("restore failed") - monkeypatch.setattr(client_module, "_unwatch_async_set", raise_on_unwatch) + monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", raise_on_restore) task = asyncio.create_task(client_module._async_wait_for_event(event, loop.time() + 100.0)) try: await wait_until(lambda: bool(event._waiters)) + future = next(iter(event._waiters)) timers[0].fire() with pytest.raises(RuntimeError, match="restore failed"): - await task + await asyncio.wait_for(task, 1.0) assert not event._waiters - assert id(event) not in client_module._async_future_watches + assert future.cancelled() + assert id(future) not in client_module._async_future_watches finally: task.cancel() await asyncio.gather(task, return_exceptions=True) for timer in timers: timer.cancel() - monkeypatch.setattr(client_module, "_unwatch_async_set", real_unwatch) - for event_arg, deadline_arg in captured: - real_unwatch(event_arg, deadline_arg) + monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", real_restore) + for watch in captured: + real_restore(watch) async def test_async_waiter_registration_failure_drops_the_waiter( @@ -1948,6 +1986,7 @@ def fail(future: asyncio.Future[Any], event_arg: Any, deadline_arg: Any) -> None assert captured assert captured[0].cancelled() assert not event._waiters + assert id(captured[0]) not in client_module._async_future_watches def test_condition_tracker_validates_each_subscriber_event( @@ -2001,6 +2040,92 @@ def replacement() -> None: assert "notify" not in vars(condition) +def test_condition_tracker_stamps_one_notification_once_for_all_deadlines( + monkeypatch: pytest.MonkeyPatch, +) -> None: + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + first = client_module._SignalDeadline(101.0) + second = client_module._SignalDeadline(102.0) + client_module._track_thread_signal(event, first) + client_module._track_thread_signal(event, second) + readings = iter((100.5, 101.5)) + monkeypatch.setattr(client_module, "monotonic", lambda: next(readings)) + try: + event.set() + assert first.signalled_at == 100.5 + assert second.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, first) + client_module._untrack_thread_signal(event, second) + + +def test_condition_tracker_rolls_back_both_hooks_when_setup_fails() -> None: + class FailNotifyCondition(threading.Condition): + def __init__(self, lock: Any) -> None: + self.fail_notify = True + super().__init__(lock) + + def __setattr__(self, name: str, value: Any) -> None: + if name == "notify" and getattr(self, "fail_notify", False): + raise RuntimeError("notify failed") + super().__setattr__(name, value) + + condition = FailNotifyCondition(threading.Lock()) + event = threading.Event() + event._cond = condition + deadline = client_module._SignalDeadline(101.0) + with pytest.raises(RuntimeError, match="notify failed"): + client_module._track_thread_signal(event, deadline) + assert "notify_all" not in vars(condition) + assert "notify" not in vars(condition) + assert id(condition) not in client_module._notify_trackers + + +def test_sync_deadline_lock_is_reentrant_for_signal_handlers() -> None: + event = threading.Event() + deadline = client_module._SignalDeadline(time.monotonic() + 10.0) + client_module._track_thread_signal(event, deadline) + done = threading.Event() + + def handler() -> None: + with client_module._notify_lock: + event.set() + done.set() + + thread = threading.Thread(target=handler, daemon=True) + try: + thread.start() + assert done.wait(1.0), "a nested notification deadlocked on the deadline lock" + assert deadline.signalled_at is not None + thread.join(1.0) + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_sync_set_publication_holds_the_deadline_lock(monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_sync_cancel(event, deadline) + real_record = deadline.record + observed: list[bool] = [] + + def record(now: float) -> bool: + observed.append(bool(client_module._notify_lock._is_owned())) + return real_record(now) + + monkeypatch.setattr(deadline, "record", record) + try: + event.set() + assert observed + assert all(observed) + assert deadline.signalled_at == clock.now + finally: + client_module._untrack_sync_cancel(event, deadline) + + async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: event = asyncio.Event() setter = event.set @@ -2335,12 +2460,50 @@ def set(self) -> None: self.backing.set() event = SwappingEvent() - event.set() + original_condition = event.backing._cond + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + wait_event.backing = threading.Event() + wait_event.backing.set() + clock.now = 100.5 + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False assert clock.delays == [] + assert "notify_all" not in vars(original_condition) assert "notify_all" not in vars(event.backing._cond) +def test_sleep_with_cancel_observes_an_overridden_setter_with_inherited_wait( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class DelegatingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.backing = threading.Event() + + def is_set(self) -> bool: + return self.backing.is_set() + + def set(self) -> None: + self.backing.set() + + event = DelegatingEvent() + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + clock.now = 100.5 + wait_event.set() + wait_event.backing.clear() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert "set" not in vars(event) + + def test_sleep_with_cancel_supports_an_instance_wait_override( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -2382,42 +2545,109 @@ async def test_wait_for_review_cancel_event_stops_before_any_request( assert clock.delays == [] +def test_async_cancel_event_is_reusable_across_event_loops() -> None: + event = asyncio.Event() + failures: list[BaseException] = [] + + def run_once() -> None: + async def main() -> None: + task = asyncio.create_task( + client_module._async_wait_for_event(event, time.monotonic() + 10.0) + ) + for _ in range(200): + if event._waiters: + break + await asyncio.sleep(0) + else: + raise AssertionError("the waiter was not registered") + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + + try: + asyncio.run(main()) + except BaseException as error: + failures.append(error) + + run_once() + run_once() + assert failures == [] + assert event._loop is None + assert not event._waiters + + +async def test_async_wait_for_review_accepts_a_read_only_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + Clock(monkeypatch) + + class ReadOnlySetEvent(asyncio.Event): + @property + def set(self) -> Any: + return asyncio.Event.set.__get__(self, asyncio.Event) + + event = ReadOnlySetEvent() + with Server(lambda request, index: Reply(body=review())) as server: + async with session("async", server.url) as client: + result = await client.wait_for_review(ORG, REVIEW, timeout=100, cancel_event=event) + assert len(server.requests) == 1 + assert result.status == "COMPLETED" + assert "set" not in vars(event) + + @MODES async def test_wait_for_review_cancel_event_wakes_real_backoff( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: real_sync_wait = client_module._wait_for_event real_async_wait = client_module._async_wait_for_event - Clock(monkeypatch) monkeypatch.setattr(client_module, "_wait_for_event", real_sync_wait) monkeypatch.setattr(client_module, "_async_wait_for_event", real_async_wait) body = review("RUNNING") body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) event: Any = asyncio.Event() if mode == "async" else threading.Event() + ready: Any = asyncio.Event() if mode == "async" else threading.Event() setter: Any = None - if mode == "async": + if mode == "sync": - async def set_later() -> None: - await asyncio.sleep(0.05) - event.set() + def sync_wait(*args: Any, **kwargs: Any) -> bool: + ready.set() + return real_sync_wait(*args, **kwargs) - setter = asyncio.create_task(set_later()) - else: + monkeypatch.setattr(client_module, "_wait_for_event", sync_wait) def set_later() -> None: - time.sleep(0.05) + assert ready.wait(1.0), "the sync backoff waiter was never registered" event.set() setter = threading.Thread(target=set_later, daemon=True) setter.start() + else: + + async def async_wait(*args: Any, **kwargs: Any) -> bool: + task = asyncio.create_task(real_async_wait(*args, **kwargs)) + await wait_until(lambda: len(event._waiters) >= 2) + ready.set() + return await task + + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait) + + async def set_later() -> None: + await asyncio.wait_for(ready.wait(), 1.0) + event.set() + + setter = asyncio.create_task(set_later()) started = time.monotonic() with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: try: - result = await call( - client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + result = await asyncio.wait_for( + call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event), + timeout=2.0, ) finally: if mode == "sync": @@ -2427,6 +2657,7 @@ def set_later() -> None: await asyncio.gather(setter, return_exceptions=True) assert time.monotonic() - started < 2.0 + assert ready.is_set() assert len(server.requests) == 1 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." @@ -2701,8 +2932,12 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) else: + calls = 0 async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: + nonlocal calls + calls += 1 + assert calls == 1, "the backoff should not poll again after the signal" clock.now = 105.0 wait_event.set() wait_event.clear() @@ -2729,12 +2964,15 @@ async def test_wait_for_review_resets_deadline_when_observer_cleanup_raises( ) -> None: Clock(monkeypatch) event = asyncio.Event() if mode == "async" else threading.Event() - real_unwatch = client_module._unwatch_async_set - captured: list[tuple[Any, Any]] = [] + real_untrack = client_module._untrack_sync_cancel + real_restore = client_module._AsyncFutureWatch.restore + sync_args: list[tuple[Any, ...]] = [] + async_watches: list[Any] = [] if mode == "sync": def untrack(*args: Any) -> None: + sync_args.append(args) raise RuntimeError("cleanup failed") monkeypatch.setattr(client_module, "_untrack_sync_cancel", untrack) @@ -2745,11 +2983,11 @@ def get_review(*args: Any, **kwargs: Any) -> Any: else: - def unwatch(event_arg: Any, deadline_arg: Any) -> None: - captured.append((event_arg, deadline_arg)) + def raise_restore(watch: Any) -> None: + async_watches.append(watch) raise RuntimeError("cleanup failed") - monkeypatch.setattr(client_module, "_unwatch_async_set", unwatch) + monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", raise_restore) async def get_review(*args: Any, **kwargs: Any) -> Any: event.set() @@ -2765,13 +3003,19 @@ async def get_review(*args: Any, **kwargs: Any) -> Any: ) assert _transport.DEADLINE.get() is None if mode == "async": - assert not getattr(event, "_waiters") - assert id(event) not in client_module._async_future_watches + assert async_watches + assert all( + id(w.future) not in client_module._async_future_watches + for w in async_watches + ) + assert not event._waiters assert server.requests == [] finally: - monkeypatch.setattr(client_module, "_unwatch_async_set", real_unwatch) - for event_arg, deadline_arg in captured: - real_unwatch(event_arg, deadline_arg) + for args in sync_args: + real_untrack(*args) + monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", real_restore) + for watch in async_watches: + real_restore(watch) @MODES From 5b3abb4d0d6cce7da2c5e16a2ab94275a9402700 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sat, 28 Nov 2026 15:49:22 +0530 Subject: [PATCH 20/22] Address nineteenth Proofline review findings --- README.md | 8 +- proofline/client.py | 317 +++++++++++++++++++++++--------- tests/test_http.py | 438 +++++++++++++++++++++++++++++++++++++++----- 3 files changed, 628 insertions(+), 135 deletions(-) diff --git a/README.md b/README.md index 55b6373d..9cb0f717 100644 --- a/README.md +++ b/README.md @@ -74,11 +74,11 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. If `cancel_event` is also set, cancellation takes precedence: the status is `STOPPED`, the mismatch or unavailable-head gap is still attached, and `reason` is the cancellation reason. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Cancelling a wait -Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(cancel.set)` when the setter is another thread. If your application already owns `SIGINT` handling, route cancellation through that handler instead of replacing it with `loop.add_signal_handler`. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. +Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. Set it from another thread or task. For an `asyncio.Event`, use `loop.call_soon_threadsafe(lambda: cancel.set())` when the setter is another thread so the event loop resolves the setter at dispatch time. If your application already owns `SIGINT` handling, route cancellation through that handler instead of replacing it with `loop.add_signal_handler`. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. ```python import threading @@ -98,10 +98,10 @@ outcome = await async_client.wait_for_review( review_id, cancel_event=cancel, ) -# From another thread: loop.call_soon_threadsafe(cancel.set) +# From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event rather than a cached bound setter. For `asyncio.Event`, the setter must notify waiters registered on that same event; changing only a backing object's flag is not observable. The SDK never binds the caller's async event to the wait's loop, so the same event may be reused later. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event rather than a cached bound setter. For `asyncio.Event`, the setter must notify waiters registered on that same event to wake an in-progress backoff; changing only a backing object's flag does not notify those waiters, though a flag that is still set can be observed at a check after a read. The SDK never binds the caller's async event to the wait's loop, so the same event may be reused later. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 3c0897fd..f0a87e7d 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -211,10 +211,26 @@ def _thread_event_is_set(event: threading.Event | AsyncEvent) -> bool: return bool(getattr(event, "_flag", False)) +_notify_lock = threading.RLock() +_pending_notifications: list[tuple[_SignalDeadline, float]] = [] + + +def _publish_signals(items: tuple[tuple[_SignalDeadline, float], ...]) -> None: + """Publish already-sampled timestamps under the deadline decision lock.""" + _pending_notifications.extend(items) + with _notify_lock: + while _pending_notifications: + deadline, now = _pending_notifications.pop(0) + deadline.record(now) + + class _SignalDeadline: + """One cancellation latch, bounded by that wait's own deadline.""" + def __init__(self, end: float) -> None: self.end = end self.signalled_at: float | None = None + self.deferred_at: float | None = None self.conditions: tuple[threading.Condition, ...] = () self.watched_set = False self.signal_event = threading.Event() @@ -222,10 +238,17 @@ def __init__(self, end: float) -> None: def record(self, now: float) -> bool: if self.signalled_at is None and now < self.end: self.signalled_at = now + self.deferred_at = None self.signal_event.set() return True return False + def defer(self, now: float) -> None: + """Wake the waiter without accepting a signal whose source is unverified.""" + if self.signalled_at is None and self.deferred_at is None and now < self.end: + self.deferred_at = now + self.signal_event.set() + def _restore_method(target: Any, name: str, had_instance: bool, saved: Any, installed: Any) -> None: """Restore one hooked attribute only while it still holds our wrapper.""" @@ -259,11 +282,12 @@ def __init__(self, condition: threading.Condition) -> None: self.saved_notify: Any = attributes.get("notify") self.original_notify_all = condition.notify_all self.original_notify = condition.notify - self.subscribers: dict[_SignalDeadline, threading.Event] = {} + # (event whose raw flag proves the signal, whether it is a backing event) + self.subscribers: dict[_SignalDeadline, tuple[Any, bool]] = {} self.installed_notify_all = self.notify_all self.installed_notify = self.notify - condition.notify_all = self.installed_notify_all # type: ignore[method-assign] try: + condition.notify_all = self.installed_notify_all # type: ignore[method-assign] condition.notify = self.installed_notify # type: ignore[method-assign] except BaseException: _rollback_condition_hook( @@ -283,15 +307,24 @@ def __init__(self, condition: threading.Condition) -> None: raise def record(self) -> None: - # Observation, timestamping, and publication share the lock that guards - # the final timeout decision and unsubscribe, so a waiter cannot miss a - # signal delivered before its cutoff. One notification is stamped once - # and reused for every deadline watching that event. + # Sample the clock at notification entry. Publication shares the lock + # with the final deadline decision, but an unrelated observer cannot + # turn an early signal into a late one by holding that lock. + now = monotonic() with _notify_lock: - now = monotonic() - for deadline, event in tuple(self.subscribers.items()): - if bool(getattr(event, "_flag", False)): - deadline.record(now) + subscribers = tuple(self.subscribers.items()) + publications: list[tuple[_SignalDeadline, float]] = [] + for deadline, (event, backing) in subscribers: + if not bool(getattr(event, "_flag", False)): + continue + if backing: + deadline.defer(now) + else: + publications.append((deadline, now)) + _pending_notifications.extend(publications) + while _pending_notifications: + pending_deadline, pending_at = _pending_notifications.pop(0) + pending_deadline.record(pending_at) def notify_all(self) -> None: self.record() @@ -318,7 +351,6 @@ def restore(self) -> None: ) -_notify_lock = threading.RLock() _notify_trackers: dict[int, _ConditionSignalTracker] = {} _sync_set_lock = threading.Lock() _sync_set_watches: dict[int, _SyncSetWatch] = {} @@ -336,44 +368,69 @@ def __init__(self, event: threading.Event) -> None: self.deadlines: set[_SignalDeadline] = set() def set_event(*args: Any, **kwargs: Any) -> Any: + # Snapshot before delegation: a wait that subscribes after a + # set/clear pulse must not inherit this notification. + with _sync_set_lock: + deadlines = tuple(self.deadlines) result = self.original(*args, **kwargs) if not _thread_event_is_set(self.event): return result - with _sync_set_lock: - deadlines = tuple(self.deadlines) - # The clock and publication share the lock used by the final - # timeout check and unsubscribe, so a signal stamped before the - # cutoff cannot be missed after that check has run. - with _notify_lock: - now = monotonic() - for deadline in deadlines: - deadline.record(now) + _publish_signals(tuple((deadline, monotonic()) for deadline in deadlines)) return result self.installed = set_event - event.set = self.installed # type: ignore[method-assign] + + def install(self) -> None: + try: + self.event.set = self.installed # type: ignore[method-assign] + except BaseException: + _restore_method(self.event, "set", self.had_instance, self.saved, self.installed) + raise def restore(self) -> None: _restore_method(self.event, "set", self.had_instance, self.saved, self.installed) +def _standard_thread_setter(event: threading.Event) -> bool: + """Whether a read-only property still exposes the standard Event.set().""" + return getattr(getattr(event, "set", None), "__func__", None) is threading.Event.set + + def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: - """Watch only the condition used by Event.wait(), never nested events.""" + """Watch the event's condition and any backing event conditions it exposes.""" + watched: list[tuple[threading.Condition, Any, bool]] = [] condition = getattr(event, "_cond", None) - deadline.conditions = (condition,) if isinstance(condition, threading.Condition) else () + if isinstance(condition, threading.Condition): + watched.append((condition, event, False)) + seen = {id(condition)} + else: + seen = set() + for value in _instance_attributes(event).values(): + backing_condition = ( + getattr(value, "_cond", None) if isinstance(value, threading.Event) else None + ) + if ( + value is event + or not isinstance(backing_condition, threading.Condition) + or id(backing_condition) in seen + ): + continue + seen.add(id(backing_condition)) + watched.append((backing_condition, value, True)) + deadline.conditions = tuple(item[0] for item in watched) with _notify_lock: - for tracked in deadline.conditions: + for tracked, watched_event, backing in watched: key = id(tracked) tracker = _notify_trackers.get(key) if tracker is None: tracker = _ConditionSignalTracker(tracked) _notify_trackers[key] = tracker - tracker.subscribers[deadline] = event + tracker.subscribers[deadline] = (watched_event, backing) return deadline def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: - to_restore: list[_ConditionSignalTracker] = [] + error: Exception | None = None try: with _notify_lock: for condition in deadline.conditions: @@ -384,33 +441,40 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> tracker.subscribers.pop(deadline, None) if not tracker.subscribers: del _notify_trackers[key] - to_restore.append(tracker) + try: + tracker.restore() + except Exception as exc: + if error is None: + error = exc finally: deadline.conditions = () - error: Exception | None = None - for tracker in to_restore: - try: - tracker.restore() - except Exception as exc: - if error is None: - error = exc if error is not None: raise error -def _watch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: +def _watch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> bool: + """Install the public setter hook when assignment is supported.""" with _sync_set_lock: watch = _sync_set_watches.get(id(event)) if watch is None: watch = _SyncSetWatch(event) + try: + watch.install() + except AttributeError: + # A getter-only property exposing the standard setter is safe: + # its condition hook already observes the notification. + if not _standard_thread_setter(event): + raise + deadline.watched_set = False + return False _sync_set_watches[id(event)] = watch watch.deadlines.add(deadline) - deadline.watched_set = True + deadline.watched_set = True + return True def _unwatch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: deadline.watched_set = False - to_restore: _SyncSetWatch | None = None with _sync_set_lock: watch = _sync_set_watches.get(id(event)) if watch is None: @@ -418,16 +482,13 @@ def _unwatch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None watch.deadlines.discard(deadline) if not watch.deadlines: del _sync_set_watches[id(event)] - to_restore = watch - if to_restore is not None: - to_restore.restore() + watch.restore() def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: - # The event's own condition catches captured setter calls; the public set - # hook additionally catches subclasses that delegate to a backing event. - # Install both even when wait() is inherited: an overridden set() can still - # notify only a backing event's condition. + # Condition observers catch captured setters and backing notifications; the + # public set hook additionally catches subclasses that notify a condition + # the SDK cannot discover from instance attributes. _track_thread_signal(event, deadline) _watch_sync_set(event, deadline) @@ -447,14 +508,24 @@ def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: def _record_signal_before( event: threading.Event | AsyncEvent | None, deadline: _SignalDeadline, end: float ) -> bool: - """Latch a signal only after reading the flag, under the publication lock.""" + """Latch a verified signal only after reading the flag, under the lock.""" if deadline.signalled_at is not None: return True if event is None or not _thread_event_is_set(event): + # A deferred notification from a backing condition is only evidence + # while this event itself exposes a set flag. + with _notify_lock: + deadline.deferred_at = None return False with _notify_lock: if deadline.signalled_at is not None: return True + deferred = deadline.deferred_at + if deferred is not None: + if deferred < end: + deadline.record(deferred) + return True + deadline.deferred_at = None now = monotonic() if now < end: deadline.record(now) @@ -494,8 +565,11 @@ def _stopped( def _sync_deadline_state(deadline: _SignalDeadline) -> tuple[float | None, float]: - """Read the latch and clock under the lock that records notifications.""" + """Drain pending publications, then read the latch and clock under one lock.""" with _notify_lock: + while _pending_notifications: + pending_deadline, pending_at = _pending_notifications.pop(0) + pending_deadline.record(pending_at) return deadline.signalled_at, monotonic() @@ -510,7 +584,7 @@ def _wait_for_event( # polls in short slices; a set/clear is still latched by the condition hook. end = min(monotonic() + timeout, deadline.end) while True: - if _record_signal_before(event, deadline, end): + if _record_signal_before(event, deadline, deadline.end): return True signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: @@ -521,16 +595,44 @@ def _wait_for_event( deadline.signal_event.clear() -_async_future_lock = threading.Lock() +_async_future_lock = threading.RLock() _async_future_watches: dict[int, _AsyncFutureWatch] = {} +_async_signal_watches: dict[int, _AsyncSignalWatch] = {} + + +def _event_is_set(event: AsyncEvent) -> bool: + try: + return event.is_set() + except Exception: + return False + + +class _AsyncSignalWatch: + """One notification timestamp per event, shared by every waiting deadline.""" + + def __init__(self, event: AsyncEvent) -> None: + self.event = event + self.deadlines: set[_SignalDeadline] = set() + self.notified = False + + def note(self, now: float) -> None: + with _async_future_lock: + if self.notified: + return + self.notified = True + deadlines = tuple(self.deadlines) + _publish_signals(tuple((deadline, now) for deadline in deadlines)) class _AsyncFutureWatch: """One shared hook on a waiter future, with independent observers.""" - def __init__(self, future: AsyncFuture[Any], event: AsyncEvent) -> None: + def __init__( + self, future: AsyncFuture[Any], event: AsyncEvent, signal: _AsyncSignalWatch + ) -> None: self.future = future self.event = event + self.signal = signal attributes = _instance_attributes(future) self.had_instance = "set_result" in attributes self.saved: Any = attributes.get("set_result") @@ -540,35 +642,47 @@ def __init__(self, future: AsyncFuture[Any], event: AsyncEvent) -> None: def set_result(result: Any) -> None: now = monotonic() if _event_is_set(event): - with _async_future_lock: - deadlines = tuple(self.deadlines) - for deadline in deadlines: - deadline.record(now) + signal.note(now) self.original(result) self.installed = set_result - future.set_result = self.installed # type: ignore[method-assign] + try: + future.set_result = self.installed # type: ignore[method-assign] + except BaseException: + _restore_method(future, "set_result", self.had_instance, self.saved, self.installed) + raise def restore(self) -> None: _restore_method(self.future, "set_result", self.had_instance, self.saved, self.installed) -def _event_is_set(event: AsyncEvent) -> bool: - try: - return event.is_set() - except Exception: - return False +def _async_signal_watch(event: AsyncEvent) -> _AsyncSignalWatch: + watch = _async_signal_watches.get(id(event)) + if watch is None: + watch = _AsyncSignalWatch(event) + _async_signal_watches[id(event)] = watch + return watch def _watch_async_future( - future: AsyncFuture[Any], event: AsyncEvent, deadline: _SignalDeadline + future: AsyncFuture[Any], + event: AsyncEvent, + deadline: _SignalDeadline, + signal: _AsyncSignalWatch | None = None, ) -> None: with _async_future_lock: + if signal is None: + signal = _async_signal_watch(event) + if not signal.deadlines: + # A set-then-clear before any observer registered is stale. A new + # observer scans the event flag itself, so only reset a fresh epoch. + signal.notified = False watch = _async_future_watches.get(id(future)) if watch is None: - watch = _AsyncFutureWatch(future, event) + watch = _AsyncFutureWatch(future, event, signal) _async_future_watches[id(future)] = watch watch.deadlines.add(deadline) + signal.deadlines.add(deadline) def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) -> bool: @@ -578,12 +692,14 @@ def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) - if watch is None: return False watch.deadlines.discard(deadline) + watch.signal.deadlines.discard(deadline) last = not watch.deadlines if last: del _async_future_watches[id(future)] - if last: - watch.restore() - return last + if not watch.signal.deadlines: + _async_signal_watches.pop(id(watch.event), None) + watch.restore() + return last class _AsyncSignalWaiter: @@ -600,17 +716,27 @@ def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncS if not isinstance(event, asyncio.Event): return waiter loop = async_get_running_loop() - future: AsyncFuture[Any] = loop.create_future() + event_loop = getattr(event, "_loop", None) + if event_loop is not None and event_loop is not loop: + raise RuntimeError("cancel_event is already bound to a different event loop.") waiters = getattr(event, "_waiters", None) if waiters is None: waiters = deque() event._waiters = waiters + for pending in waiters: + pending_loop = getattr(pending, "_loop", None) + if pending_loop is not None and pending_loop is not loop: + raise RuntimeError("cancel_event has waiters on a different event loop.") + with _async_future_lock: + signal = _async_signal_watch(event) + future: AsyncFuture[Any] = loop.create_future() waiters.append(future) waiter.event = event waiter.future = future try: - _watch_async_future(future, event, deadline) + _watch_async_future(future, event, deadline, signal) except BaseException: + _unwatch_async_future(future, deadline) try: waiters.remove(future) except ValueError: @@ -641,12 +767,14 @@ def _unwatch_async_waiter(waiter: _AsyncSignalWaiter, deadline: _SignalDeadline) future.cancel() -async def _async_wait_for_event(event: AsyncEvent, cutoff: float) -> bool: +async def _async_wait_for_event( + event: AsyncEvent, cutoff: float, signal: _SignalDeadline | None = None +) -> bool: """Return True when the event is signalled before cutoff, False on timeout.""" loop = async_get_running_loop() if monotonic() >= cutoff: return False - deadline = _SignalDeadline(cutoff) + deadline = signal if signal is not None else _SignalDeadline(cutoff) timer: AsyncFuture[None] = loop.create_future() handle = loop.call_at(loop.time() + max(0.0, cutoff - monotonic()), timer.set_result, None) waiter = _AsyncSignalWaiter() @@ -672,39 +800,50 @@ def _cancel_end(delay: float, cutoff: float | None) -> float: def _sleep_with_cancel( - delay: float, event: threading.Event | None, cutoff: float | None = None + delay: float, + event: threading.Event | None, + cutoff: float | None = None, + signal: _SignalDeadline | None = None, ) -> bool: """Wait on the event until the delay or cutoff, returning False if cancelled.""" if event is None: sleep(delay) return True end = _cancel_end(delay, cutoff) - deadline = _SignalDeadline(end) + owns_signal = signal is None + deadline: _SignalDeadline = _SignalDeadline(end) if signal is None else signal try: - _track_sync_cancel(event, deadline) + if owns_signal: + _track_sync_cancel(event, deadline) while True: signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: return False + # A backing notification can be timestamped before this check even + # when the setter resumes after the backoff cutoff. Verify it before + # giving the cutoff precedence. The flag is read before the clock so + # a signal first delivered at or after the deadline is still ignored. + if _record_signal_before(event, deadline, deadline.end): + return False if now >= end: return True - # The flag is read before the clock, so a signal delivered at or - # after the cutoff cannot be stamped with an earlier clock value. - if _record_signal_before(event, deadline, end): - return False if not _wait_for_event(event, end - now, deadline): signalled_at, now = _sync_deadline_state(deadline) if signalled_at is not None: return False - if now < end and _record_signal_before(event, deadline, end): + if _record_signal_before(event, deadline, deadline.end): return False return True finally: - _untrack_sync_cancel(event, deadline) + if owns_signal: + _untrack_sync_cancel(event, deadline) async def _async_sleep_with_cancel( - delay: float, event: AsyncEvent | None, cutoff: float | None = None + delay: float, + event: AsyncEvent | None, + cutoff: float | None = None, + signal: _SignalDeadline | None = None, ) -> bool: if event is None: await async_sleep(delay) @@ -713,7 +852,7 @@ async def _async_sleep_with_cancel( while True: if monotonic() >= end: return True - if await _async_wait_for_event(event, end): + if await _async_wait_for_event(event, end, signal): return False if monotonic() >= end: return True @@ -1096,8 +1235,11 @@ def wait_for_review( The signal must be observable through the supplied event's own flag and condition. Call ``set()`` on the event passed here; a cached bound - setter or a direct mutation of a delegating event's backing object is - not supported and can be missed. + setter or a direct mutation of a delegating event's backing object does + not wake an in-progress backoff. A getter-only property exposing the + standard ``threading.Event.set()`` is supported through its condition. + Backing notifications are timestamped when they occur and verified + against the supplied event's flag at the next checkpoint. """ if not math.isfinite(timeout) or timeout < 0: @@ -1138,7 +1280,9 @@ def wait_for_review( if result is not None: return result remaining = _transport.remaining() or 0 - if not _sleep_with_cancel(min(interval, remaining), cancel_event, deadline_at): + if not _sleep_with_cancel( + min(interval, remaining), cancel_event, deadline_at, read_signal + ): return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) if _cancellation_signal(cancel_event, read_signal): @@ -1520,8 +1664,11 @@ async def wait_for_review( ignored; it does not change the wait's result or suppress a read error that would otherwise propagate. The signal must notify waiters registered on the event passed here: call ``set()`` on that event and - do not only mutate a backing object's flag. The SDK observes the signal - through its own waiter without binding the caller's event to the loop. + do not only mutate a backing object's flag, which can still be observed + at a check after a read but will not wake an in-progress backoff. The + SDK observes the signal through its own waiter without binding the + caller's event to the loop; an event already bound to another loop is + rejected before the first request. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1565,7 +1712,7 @@ async def wait_for_review( return result remaining = _transport.remaining() or 0 if not await _async_sleep_with_cancel( - min(interval, remaining), cancel_event, deadline_at + min(interval, remaining), cancel_event, deadline_at, read_signal ): return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) diff --git a/tests/test_http.py b/tests/test_http.py index 4dacf89f..7f4ecd82 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -179,7 +179,9 @@ def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None woke = True return woke - async def async_wait_for_event(self, event: Any, cutoff: float) -> bool: + async def async_wait_for_event( + self, event: Any, cutoff: float, signal: Any | None = None + ) -> bool: self.sleep(max(0.0, cutoff - self.now)) await asyncio.sleep(0) return bool(event.is_set()) @@ -1741,7 +1743,7 @@ def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandl monkeypatch.setattr(loop, "call_at", record_call_at) - def fail(future: Any, event: Any, deadline: Any) -> None: + def fail(*args: Any) -> None: raise RuntimeError("future hook failed") monkeypatch.setattr(client_module, "_watch_async_future", fail) @@ -1976,8 +1978,8 @@ async def test_async_waiter_registration_failure_drops_the_waiter( deadline = client_module._SignalDeadline(clock.now + 10.0) captured: list[asyncio.Future[Any]] = [] - def fail(future: asyncio.Future[Any], event_arg: Any, deadline_arg: Any) -> None: - captured.append(future) + def fail(*args: Any) -> None: + captured.append(args[0]) raise RuntimeError("hook failed") monkeypatch.setattr(client_module, "_watch_async_future", fail) @@ -2084,24 +2086,42 @@ def __setattr__(self, name: str, value: Any) -> None: def test_sync_deadline_lock_is_reentrant_for_signal_handlers() -> None: - event = threading.Event() - deadline = client_module._SignalDeadline(time.monotonic() + 10.0) - client_module._track_thread_signal(event, deadline) - done = threading.Event() + # A nested notification that deadlocks must not leave the parent test + # holding the deadline lock during cleanup, so probe it in a subprocess. + code = """ +import sys +import threading - def handler() -> None: - with client_module._notify_lock: - event.set() - done.set() +sys.path.insert(0, sys.argv[1]) +from proofline import client - thread = threading.Thread(target=handler, daemon=True) - try: - thread.start() - assert done.wait(1.0), "a nested notification deadlocked on the deadline lock" - assert deadline.signalled_at is not None - thread.join(1.0) - finally: - client_module._untrack_thread_signal(event, deadline) +event = threading.Event() +deadline = client._SignalDeadline(float("inf")) +client._track_thread_signal(event, deadline) +done = threading.Event() + +def handler(): + with client._notify_lock: + event.set() + done.set() + +thread = threading.Thread(target=handler, daemon=True) +thread.start() +assert done.wait(1.0), "nested notification deadlocked on the deadline lock" +assert deadline.signalled_at is not None +thread.join(1.0) +client._untrack_thread_signal(event, deadline) +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=5, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" def test_sync_set_publication_holds_the_deadline_lock(monkeypatch: pytest.MonkeyPatch) -> None: @@ -2338,9 +2358,17 @@ def set(self) -> None: self.backing.set() event = BackingEvent() + ready = threading.Event() + real_track = client_module._track_sync_cancel + + def track(event_arg: Any, deadline: Any) -> None: + real_track(event_arg, deadline) + ready.set() + + monkeypatch.setattr(client_module, "_track_sync_cancel", track) def signal() -> None: - time.sleep(0.05) + assert ready.wait(1.0), "the cancellation observers were never installed" clock.now = 100.5 event.set() clock.now = 102.0 @@ -2425,17 +2453,23 @@ def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( clock = Clock(monkeypatch) monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + held = False + class ReentrantEvent(threading.Event): def is_set(self) -> bool: - assert self._cond.acquire(blocking=False), "is_set called under the condition" - try: - return bool(self._flag) - finally: - self._cond.release() + assert not held, "is_set called under the condition" + return bool(self._flag) event = ReentrantEvent() def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + nonlocal held + with wait_event._cond: + held = True + try: + wait_event._cond.notify_all() + finally: + held = False clock.now = 101.0 return False @@ -2601,10 +2635,6 @@ def set(self) -> Any: async def test_wait_for_review_cancel_event_wakes_real_backoff( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: - real_sync_wait = client_module._wait_for_event - real_async_wait = client_module._async_wait_for_event - monkeypatch.setattr(client_module, "_wait_for_event", real_sync_wait) - monkeypatch.setattr(client_module, "_async_wait_for_event", real_async_wait) body = review("RUNNING") body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) event: Any = asyncio.Event() if mode == "async" else threading.Event() @@ -2613,11 +2643,18 @@ async def test_wait_for_review_cancel_event_wakes_real_backoff( if mode == "sync": - def sync_wait(*args: Any, **kwargs: Any) -> bool: - ready.set() - return real_sync_wait(*args, **kwargs) + class ReadySignalEvent(threading.Event): + def wait(self, timeout: float | None = None) -> bool: + ready.set() + return super().wait(timeout) + + real_track = client_module._track_sync_cancel + + def track(event_arg: Any, deadline: Any) -> None: + real_track(event_arg, deadline) + deadline.signal_event = ReadySignalEvent() - monkeypatch.setattr(client_module, "_wait_for_event", sync_wait) + monkeypatch.setattr(client_module, "_track_sync_cancel", track) def set_later() -> None: assert ready.wait(1.0), "the sync backoff waiter was never registered" @@ -2626,12 +2663,17 @@ def set_later() -> None: setter = threading.Thread(target=set_later, daemon=True) setter.start() else: + real_async_wait = client_module._async_wait_for_event async def async_wait(*args: Any, **kwargs: Any) -> bool: - task = asyncio.create_task(real_async_wait(*args, **kwargs)) - await wait_until(lambda: len(event._waiters) >= 2) - ready.set() - return await task + helper = asyncio.create_task(real_async_wait(*args, **kwargs)) + try: + await wait_until(lambda: len(event._waiters) >= 2) + ready.set() + return await helper + finally: + helper.cancel() + await asyncio.gather(helper, return_exceptions=True) monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait) @@ -2645,16 +2687,27 @@ async def set_later() -> None: with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: try: - result = await asyncio.wait_for( - call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event), - timeout=2.0, - ) + if mode == "sync": + result = await asyncio.wait_for( + asyncio.to_thread( + client.wait_for_review, + ORG, + REVIEW, + timeout=5, + cancel_event=event, + ), + timeout=2.0, + ) + else: + result = await asyncio.wait_for( + client.wait_for_review(ORG, REVIEW, timeout=5, cancel_event=event), + timeout=2.0, + ) finally: if mode == "sync": setter.join(1.0) else: - setter.cancel() - await asyncio.gather(setter, return_exceptions=True) + await finish_sender(setter) assert time.monotonic() - started < 2.0 assert ready.is_set() @@ -2856,7 +2909,9 @@ async def test_wait_for_review_cancel_before_next_poll_keeps_last_record( if mode == "async": - async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: + async def async_wait_for_event( + wait_event: Any, cutoff: float, signal: Any | None = None + ) -> bool: clock.sleep(max(0.0, cutoff - clock.now)) wait_event.set() await asyncio.sleep(0) @@ -2923,8 +2978,12 @@ async def test_wait_for_review_records_cancellation_at_the_backoff_cutoff( body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) if mode == "sync": + calls = 0 def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + nonlocal calls + calls += 1 + assert calls == 1, "the backoff should not poll again after the signal" clock.now = 105.0 wait_event.set() wait_event.clear() @@ -2934,7 +2993,9 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) else: calls = 0 - async def async_wait_for_event(wait_event: Any, cutoff: float) -> bool: + async def async_wait_for_event( + wait_event: Any, cutoff: float, signal: Any | None = None + ) -> bool: nonlocal calls calls += 1 assert calls == 1, "the backoff should not poll again after the signal" @@ -4204,3 +4265,288 @@ def respond(request: Request, index: int) -> Reply: assert len(exported.rows) == 1 assert exported.rows[0]["claim"] == row["claim"] assert exported.next_cursor == "next-page" + + +def test_sync_wait_for_review_accepts_a_read_only_standard_setter() -> None: + class ReadOnlySetEvent(threading.Event): + @property + def set(self) -> Any: + return threading.Event.set.__get__(self, threading.Event) + + event = ReadOnlySetEvent() + with Server(lambda request, index: Reply(body=review())) as server: + with ProoflineClient(SecretStr(TOKEN), base_url=server.url) as client: + result = client.wait_for_review(ORG, REVIEW, timeout=100, cancel_event=event) + assert len(server.requests) == 1 + assert result.status == "COMPLETED" + assert "set" not in vars(event) + + +async def test_async_waiter_registration_rejects_a_foreign_loop_waiter() -> None: + class ForeignWaiter: + _loop = object() + + event = asyncio.Event() + foreign = ForeignWaiter() + event._waiters.append(foreign) # type: ignore[arg-type] + deadline = client_module._SignalDeadline(time.monotonic() + 10.0) + try: + with pytest.raises(RuntimeError, match="different event loop"): + client_module._watch_async_waiter(event, deadline) + assert list(event._waiters) == [foreign] + assert id(event) not in client_module._async_signal_watches + finally: + event._waiters.remove(foreign) # type: ignore[arg-type] + + +def test_sync_set_registration_waits_for_a_restoring_teardown( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = threading.Event() + first = client_module._SignalDeadline(101.0) + second = client_module._SignalDeadline(101.0) + assert client_module._watch_sync_set(event, first) + watch = client_module._sync_set_watches[id(event)] + real_restore = watch.restore + restore_started = threading.Event() + allow_restore = threading.Event() + + def slow_restore() -> None: + restore_started.set() + if allow_restore.wait(1.0): + real_restore() + + monkeypatch.setattr(watch, "restore", slow_restore) + registered = threading.Event() + + def teardown() -> None: + client_module._unwatch_sync_set(event, first) + + def register() -> None: + client_module._watch_sync_set(event, second) + registered.set() + + leaver = threading.Thread(target=teardown) + joiner = threading.Thread(target=register) + leaver.start() + try: + assert restore_started.wait(1.0), "the old wrapper was never retired" + joiner.start() + assert not registered.wait(0.05), "registration saw the outgoing wrapper" + allow_restore.set() + assert registered.wait(1.0), "registration did not follow restoration" + finally: + allow_restore.set() + leaver.join(1.0) + if joiner.is_alive(): + joiner.join(1.0) + if second.watched_set: + client_module._unwatch_sync_set(event, second) + assert not leaver.is_alive() + assert not joiner.is_alive() + assert "set" not in vars(event) + assert id(event) not in client_module._sync_set_watches + + +async def test_async_future_registration_waits_for_a_restoring_teardown( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + first = client_module._SignalDeadline(101.0) + second = client_module._SignalDeadline(101.0) + client_module._watch_async_future(future, event, first) + watch = client_module._async_future_watches[id(future)] + real_restore = watch.restore + restore_started = threading.Event() + allow_restore = threading.Event() + + def slow_restore() -> None: + restore_started.set() + if allow_restore.wait(1.0): + real_restore() + + monkeypatch.setattr(watch, "restore", slow_restore) + teardown = asyncio.create_task( + asyncio.to_thread(client_module._unwatch_async_future, future, first) + ) + joiner: asyncio.Task[None] | None = None + try: + assert await asyncio.to_thread(restore_started.wait, 1.0) + registered = threading.Event() + + def register() -> None: + client_module._watch_async_future(future, event, second) + registered.set() + + joiner = asyncio.create_task(asyncio.to_thread(register)) + await asyncio.sleep(0.05) + assert not registered.is_set(), "registration saw the outgoing future hook" + allow_restore.set() + await asyncio.wait_for(teardown, 1.0) + assert await asyncio.to_thread(registered.wait, 1.0) + assert await asyncio.wait_for(joiner, 1.0) is None + finally: + allow_restore.set() + await asyncio.gather(teardown, return_exceptions=True) + if joiner is not None: + await asyncio.gather(joiner, return_exceptions=True) + if second in getattr(client_module._async_future_watches.get(id(future)), "deadlines", ()): + client_module._unwatch_async_future(future, second) + assert "set_result" not in getattr(future, "__dict__", {}) + + +def test_condition_tracker_rolls_back_a_failing_first_assignment() -> None: + class FailNotifyAllCondition(threading.Condition): + def __init__(self, lock: Any) -> None: + self.fail_assign = True + super().__init__(lock) + + def __setattr__(self, name: str, value: Any) -> None: + if name == "notify_all" and getattr(self, "fail_assign", False): + raise RuntimeError("notify_all assignment failed") + super().__setattr__(name, value) + + condition = FailNotifyAllCondition(threading.Lock()) + event = threading.Event() + event._cond = condition + deadline = client_module._SignalDeadline(101.0) + with pytest.raises(RuntimeError, match="notify_all assignment failed"): + client_module._track_thread_signal(event, deadline) + assert "notify_all" not in vars(condition) + assert "notify" not in vars(condition) + assert id(condition) not in client_module._notify_trackers + + +async def test_async_future_watch_stamps_one_notification_for_all_observers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + first = client_module._SignalDeadline(clock.now + 0.1) + second = client_module._SignalDeadline(clock.now + 0.2) + client_module._watch_async_future(future, event, first) + client_module._watch_async_future(future, event, second) + try: + clock.now = 100.02 + event.set() + future.set_result(True) + assert first.signalled_at == second.signalled_at == 100.02 + finally: + client_module._unwatch_async_future(future, first) + client_module._unwatch_async_future(future, second) + + +def test_sync_set_watch_snapshots_subscribers_before_delegating( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + early = client_module._SignalDeadline(clock.now + 10.0) + late = client_module._SignalDeadline(clock.now + 10.0) + + class InterleavingEvent(threading.Event): + def set(self) -> None: + client_module._watch_sync_set(self, late) + super().set() + self.clear() + + event = InterleavingEvent() + client_module._watch_sync_set(event, early) + try: + event.set() + assert early.signalled_at is None + assert late.signalled_at is None + finally: + client_module._unwatch_sync_set(event, early) + client_module._unwatch_sync_set(event, late) + + +def test_condition_tracker_samples_time_before_the_publication_lock( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + + class AdvancingLock: + def __enter__(self) -> Any: + clock.now = 101.5 + return self + + def __exit__(self, *args: Any) -> bool: + return False + + monkeypatch.setattr(client_module, "_notify_lock", AdvancingLock()) + try: + event.set() + assert deadline.signalled_at == 100.0 + finally: + client_module._untrack_thread_signal(event, deadline) + + +@MODES +async def test_wait_for_review_reuses_the_read_latch_for_backoff( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + calls = 0 + real_signal = client_module._cancellation_signal + + def signal(event_arg: Any, deadline: Any) -> bool: + nonlocal calls + calls += 1 + result = real_signal(event_arg, deadline) + if calls == 2: + event.set() + event.clear() + return result + + monkeypatch.setattr(client_module, "_cancellation_signal", signal) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event + ) + assert len(server.requests) == 1 + assert calls >= 2 + assert clock.delays == [] + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review is not None + assert result.review.id == REVIEW + + +def test_sleep_with_cancel_timestamps_a_backing_notification( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + real_wait = client_module._wait_for_event + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class SlowBackingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.backing = threading.Event() + + def is_set(self) -> bool: + return self.backing.is_set() + + def set(self) -> None: + clock.now = 100.5 + self.backing.set() + clock.now = 101.5 + + event = SlowBackingEvent() + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + wait_event.set() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert "notify_all" not in vars(event.backing._cond) From d27e21de8f2afad7f108c90f80d6e437f949968b Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sat, 28 Nov 2026 16:14:20 +0530 Subject: [PATCH 21/22] Address twentieth Proofline review findings --- README.md | 4 +- proofline/client.py | 313 ++++++++++++++++++------------ tests/test_http.py | 455 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 540 insertions(+), 232 deletions(-) diff --git a/README.md b/README.md index 9cb0f717..ea34d704 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. If `cancel_event` is also set, cancellation takes precedence: the status is `STOPPED`, the mismatch or unavailable-head gap is still attached, and `reason` is the cancellation reason. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. If `cancel_event` is also set and cancellation is observed before the deadline, cancellation takes precedence over that mismatch: the status is `STOPPED`, the mismatch or unavailable-head gap is still attached, and `reason` is the cancellation reason. The response must still pass normal validation, and a signal first delivered at or after the deadline does not override the mismatch. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Cancelling a wait @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event rather than a cached bound setter. For `asyncio.Event`, the setter must notify waiters registered on that same event to wake an in-progress backoff; changing only a backing object's flag does not notify those waiters, though a flag that is still set can be observed at a check after a read. The SDK never binds the caller's async event to the wait's loop, so the same event may be reused later. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event. A cached bound standard `threading.Event.set()` still notifies that event's condition and works; a setter that bypasses the observed condition, or a direct mutation of a backing object, may not wake an in-progress backoff. For `asyncio.Event`, the setter must notify waiters registered on that same event; changing only a backing object's flag does not notify those waiters, though a flag that is still set can be observed at a check after a read. The SDK never binds the caller's async event to the wait's loop, so the same event may be reused later as long as it is not already bound to a different loop and has no waiters from one; those events are rejected before the first request. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index f0a87e7d..4c6d1906 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -212,16 +212,34 @@ def _thread_event_is_set(event: threading.Event | AsyncEvent) -> bool: _notify_lock = threading.RLock() -_pending_notifications: list[tuple[_SignalDeadline, float]] = [] +_publication_lock = threading.Lock() +# (deadline, sampled time, whether the caller's own flag was verified at delivery) +_pending_notifications: list[tuple[_SignalDeadline, float, bool]] = [] -def _publish_signals(items: tuple[tuple[_SignalDeadline, float], ...]) -> None: - """Publish already-sampled timestamps under the deadline decision lock.""" - _pending_notifications.extend(items) +def _stage_signals(items: tuple[tuple[_SignalDeadline, float, bool], ...]) -> None: + """Make sampled notifications visible before contending for the deadline lock.""" + with _publication_lock: + _pending_notifications.extend(items) + + +def _drain_signals() -> None: + """Publish staged notifications under the same lock used by deadline checks.""" + with _publication_lock: + items = tuple(_pending_notifications) + _pending_notifications.clear() with _notify_lock: - while _pending_notifications: - deadline, now = _pending_notifications.pop(0) - deadline.record(now) + for deadline, now, verified in items: + if verified: + deadline.record(now) + else: + deadline.defer(now) + + +def _publish_signals(items: tuple[tuple[_SignalDeadline, float], ...]) -> None: + """Stage and publish already-verified timestamps for the supplied deadlines.""" + _stage_signals(tuple((deadline, now, True) for deadline, now in items)) + _drain_signals() class _SignalDeadline: @@ -230,7 +248,6 @@ class _SignalDeadline: def __init__(self, end: float) -> None: self.end = end self.signalled_at: float | None = None - self.deferred_at: float | None = None self.conditions: tuple[threading.Condition, ...] = () self.watched_set = False self.signal_event = threading.Event() @@ -238,18 +255,32 @@ def __init__(self, end: float) -> None: def record(self, now: float) -> bool: if self.signalled_at is None and now < self.end: self.signalled_at = now - self.deferred_at = None self.signal_event.set() return True return False def defer(self, now: float) -> None: - """Wake the waiter without accepting a signal whose source is unverified.""" - if self.signalled_at is None and self.deferred_at is None and now < self.end: - self.deferred_at = now + """Wake the waiter without treating an unverified notification as evidence.""" + if self.signalled_at is None and now < self.end: self.signal_event.set() +def _flag_verified_at_delivery(caller: Any, watched: Any) -> bool: + """Check a flag without calling an override under the notifying condition.""" + if not bool(getattr(watched, "_flag", False)): + return False + if caller is watched: + return True + attributes = _instance_attributes(caller) + delegates = "is_set" in attributes or type(caller).is_set is not threading.Event.is_set + sources = [value for value in attributes.values() if isinstance(value, threading.Event)] + return ( + delegates + and any(value is watched for value in sources) + and all(bool(getattr(value, "_flag", False)) for value in sources) + ) + + def _restore_method(target: Any, name: str, had_instance: bool, saved: Any, installed: Any) -> None: """Restore one hooked attribute only while it still holds our wrapper.""" if getattr(target, name, None) is not installed: @@ -282,8 +313,10 @@ def __init__(self, condition: threading.Condition) -> None: self.saved_notify: Any = attributes.get("notify") self.original_notify_all = condition.notify_all self.original_notify = condition.notify - # (event whose raw flag proves the signal, whether it is a backing event) - self.subscribers: dict[_SignalDeadline, tuple[Any, bool]] = {} + # (event whose raw flag proves the signal, whether it is a backing event, + # the event supplied by the caller) + self.subscribers: dict[_SignalDeadline, tuple[Any, bool, Any]] = {} + self._subscription_lock = threading.Lock() self.installed_notify_all = self.notify_all self.installed_notify = self.notify try: @@ -307,24 +340,19 @@ def __init__(self, condition: threading.Condition) -> None: raise def record(self) -> None: - # Sample the clock at notification entry. Publication shares the lock - # with the final deadline decision, but an unrelated observer cannot - # turn an early signal into a late one by holding that lock. + # Sample and stage before contending for the deadline decision lock, so + # a paused notifier cannot hide a timely signal from the final check. now = monotonic() - with _notify_lock: + with self._subscription_lock: subscribers = tuple(self.subscribers.items()) - publications: list[tuple[_SignalDeadline, float]] = [] - for deadline, (event, backing) in subscribers: - if not bool(getattr(event, "_flag", False)): - continue - if backing: - deadline.defer(now) - else: - publications.append((deadline, now)) - _pending_notifications.extend(publications) - while _pending_notifications: - pending_deadline, pending_at = _pending_notifications.pop(0) - pending_deadline.record(pending_at) + staged: list[tuple[_SignalDeadline, float, bool]] = [] + for deadline, (watched, backing, caller) in subscribers: + if not bool(getattr(watched, "_flag", False)): + continue + verified = not backing or _flag_verified_at_delivery(caller, watched) + staged.append((deadline, now, verified)) + _stage_signals(tuple(staged)) + _drain_signals() def notify_all(self) -> None: self.record() @@ -375,7 +403,9 @@ def set_event(*args: Any, **kwargs: Any) -> Any: result = self.original(*args, **kwargs) if not _thread_event_is_set(self.event): return result - _publish_signals(tuple((deadline, monotonic()) for deadline in deadlines)) + # One timestamp for every subscriber to this single notification. + now = monotonic() + _publish_signals(tuple((deadline, now) for deadline in deadlines)) return result self.installed = set_event @@ -425,7 +455,8 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ if tracker is None: tracker = _ConditionSignalTracker(tracked) _notify_trackers[key] = tracker - tracker.subscribers[deadline] = (watched_event, backing) + with tracker._subscription_lock: + tracker.subscribers[deadline] = (watched_event, backing, event) return deadline @@ -438,8 +469,10 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> tracker = _notify_trackers.get(key) if tracker is None: continue - tracker.subscribers.pop(deadline, None) - if not tracker.subscribers: + with tracker._subscription_lock: + tracker.subscribers.pop(deadline, None) + empty = not tracker.subscribers + if empty: del _notify_trackers[key] try: tracker.restore() @@ -509,23 +542,16 @@ def _record_signal_before( event: threading.Event | AsyncEvent | None, deadline: _SignalDeadline, end: float ) -> bool: """Latch a verified signal only after reading the flag, under the lock.""" + _drain_signals() if deadline.signalled_at is not None: return True if event is None or not _thread_event_is_set(event): - # A deferred notification from a backing condition is only evidence - # while this event itself exposes a set flag. - with _notify_lock: - deadline.deferred_at = None return False with _notify_lock: if deadline.signalled_at is not None: return True - deferred = deadline.deferred_at - if deferred is not None: - if deferred < end: - deadline.record(deferred) - return True - deadline.deferred_at = None + # An earlier unverified backing wake is only a hint; it cannot backdate + # a flag that first became set after this point. now = monotonic() if now < end: deadline.record(now) @@ -566,10 +592,8 @@ def _stopped( def _sync_deadline_state(deadline: _SignalDeadline) -> tuple[float | None, float]: """Drain pending publications, then read the latch and clock under one lock.""" + _drain_signals() with _notify_lock: - while _pending_notifications: - pending_deadline, pending_at = _pending_notifications.pop(0) - pending_deadline.record(pending_at) return deadline.signalled_at, monotonic() @@ -607,19 +631,44 @@ def _event_is_set(event: AsyncEvent) -> bool: return False +def _check_async_event_loop(event: asyncio.Event) -> None: + """Reject an event or waiter already bound to another event loop.""" + loop = async_get_running_loop() + event_loop = getattr(event, "_loop", None) + if event_loop is not None and event_loop is not loop: + raise RuntimeError("cancel_event is already bound to a different event loop.") + for pending in getattr(event, "_waiters", ()) or (): + pending_loop = getattr(pending, "_loop", None) + if pending_loop is not None and pending_loop is not loop: + raise RuntimeError("cancel_event has waiters on a different event loop.") + + class _AsyncSignalWatch: """One notification timestamp per event, shared by every waiting deadline.""" def __init__(self, event: AsyncEvent) -> None: self.event = event self.deadlines: set[_SignalDeadline] = set() - self.notified = False + self.counts: dict[_SignalDeadline, int] = {} + + def add(self, deadline: _SignalDeadline) -> None: + self.counts[deadline] = self.counts.get(deadline, 0) + 1 + self.deadlines.add(deadline) + + def remove(self, deadline: _SignalDeadline) -> bool: + """Remove one registration; return True when it was the last one.""" + count = self.counts.get(deadline, 0) + if count <= 1: + self.counts.pop(deadline, None) + self.deadlines.discard(deadline) + return True + self.counts[deadline] = count - 1 + return False def note(self, now: float) -> None: + # Every pulse reaches the deadlines subscribed at that moment. Each + # deadline latches only its own first timely signal. with _async_future_lock: - if self.notified: - return - self.notified = True deadlines = tuple(self.deadlines) _publish_signals(tuple((deadline, now) for deadline in deadlines)) @@ -656,14 +705,6 @@ def restore(self) -> None: _restore_method(self.future, "set_result", self.had_instance, self.saved, self.installed) -def _async_signal_watch(event: AsyncEvent) -> _AsyncSignalWatch: - watch = _async_signal_watches.get(id(event)) - if watch is None: - watch = _AsyncSignalWatch(event) - _async_signal_watches[id(event)] = watch - return watch - - def _watch_async_future( future: AsyncFuture[Any], event: AsyncEvent, @@ -671,18 +712,36 @@ def _watch_async_future( signal: _AsyncSignalWatch | None = None, ) -> None: with _async_future_lock: + owns_signal = signal is None if signal is None: - signal = _async_signal_watch(event) - if not signal.deadlines: - # A set-then-clear before any observer registered is stale. A new - # observer scans the event flag itself, so only reset a fresh epoch. - signal.notified = False + signal = _async_signal_watches.get(id(event)) + if signal is None: + signal = _AsyncSignalWatch(event) watch = _async_future_watches.get(id(future)) - if watch is None: - watch = _AsyncFutureWatch(future, event, signal) - _async_future_watches[id(future)] = watch - watch.deadlines.add(deadline) - signal.deadlines.add(deadline) + installed_watch: _AsyncFutureWatch | None = None + try: + if watch is None: + watch = _AsyncFutureWatch(future, event, signal) + installed_watch = watch + _async_future_watches[id(future)] = watch + watch.deadlines.add(deadline) + signal.add(deadline) + except BaseException: + if installed_watch is not None: + try: + installed_watch.restore() + except Exception: + pass + if watch is not None: + watch.deadlines.discard(deadline) + if not watch.deadlines and _async_future_watches.get(id(future)) is watch: + del _async_future_watches[id(future)] + signal.remove(deadline) + if not signal.deadlines and _async_signal_watches.get(id(event)) is signal: + _async_signal_watches.pop(id(event), None) + raise + if owns_signal: + _async_signal_watches[id(event)] = signal def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) -> bool: @@ -692,12 +751,13 @@ def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) - if watch is None: return False watch.deadlines.discard(deadline) - watch.signal.deadlines.discard(deadline) + final_signal_registration = watch.signal.remove(deadline) last = not watch.deadlines if last: del _async_future_watches[id(future)] - if not watch.signal.deadlines: - _async_signal_watches.pop(id(watch.event), None) + if final_signal_registration and not watch.signal.deadlines: + if _async_signal_watches.get(id(watch.event)) is watch.signal: + _async_signal_watches.pop(id(watch.event), None) watch.restore() return last @@ -715,62 +775,56 @@ def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncS waiter = _AsyncSignalWaiter() if not isinstance(event, asyncio.Event): return waiter - loop = async_get_running_loop() - event_loop = getattr(event, "_loop", None) - if event_loop is not None and event_loop is not loop: - raise RuntimeError("cancel_event is already bound to a different event loop.") - waiters = getattr(event, "_waiters", None) - if waiters is None: - waiters = deque() - event._waiters = waiters - for pending in waiters: - pending_loop = getattr(pending, "_loop", None) - if pending_loop is not None and pending_loop is not loop: - raise RuntimeError("cancel_event has waiters on a different event loop.") with _async_future_lock: - signal = _async_signal_watch(event) - future: AsyncFuture[Any] = loop.create_future() - waiters.append(future) - waiter.event = event - waiter.future = future - try: - _watch_async_future(future, event, deadline, signal) - except BaseException: - _unwatch_async_future(future, deadline) + _check_async_event_loop(event) + loop = async_get_running_loop() + waiters = getattr(event, "_waiters", None) + if waiters is None: + waiters = deque() + event._waiters = waiters + future: AsyncFuture[Any] = loop.create_future() + waiters.append(future) + waiter.event = event + waiter.future = future try: - waiters.remove(future) - except ValueError: - pass - future.cancel() - waiter.event = None - waiter.future = None - raise - return waiter + _watch_async_future(future, event, deadline) + except BaseException: + try: + waiters.remove(future) + except ValueError: + pass + future.cancel() + waiter.event = None + waiter.future = None + raise + return waiter def _unwatch_async_waiter(waiter: _AsyncSignalWaiter, deadline: _SignalDeadline) -> None: - try: - if waiter.future is not None: - _unwatch_async_future(waiter.future, deadline) - finally: - future = waiter.future - event = waiter.event - if future is not None: - if event is not None: - waiters = getattr(event, "_waiters", None) - if waiters is not None: - try: - waiters.remove(future) - except ValueError: - pass - if not future.done(): - future.cancel() + with _async_future_lock: + try: + if waiter.future is not None: + _unwatch_async_future(waiter.future, deadline) + finally: + future = waiter.future + event = waiter.event + if future is not None: + if event is not None: + waiters = getattr(event, "_waiters", None) + if waiters is not None: + try: + waiters.remove(future) + except ValueError: + pass + if not future.done(): + future.cancel() async def _async_wait_for_event( event: AsyncEvent, cutoff: float, signal: _SignalDeadline | None = None ) -> bool: """Return True when the event is signalled before cutoff, False on timeout.""" + _drain_signals() loop = async_get_running_loop() if monotonic() >= cutoff: return False @@ -781,13 +835,15 @@ async def _async_wait_for_event( try: waiter = _watch_async_waiter(event, deadline) if _event_is_set(event): - deadline.record(monotonic()) + _publish_signals(((deadline, monotonic()),)) + _drain_signals() if deadline.signalled_at is not None: return True awaited: tuple[AsyncFuture[Any], ...] = (timer,) if waiter.future is not None: awaited += (waiter.future,) await async_wait(awaited, return_when=FIRST_COMPLETED) + _drain_signals() return deadline.signalled_at is not None finally: handle.cancel() @@ -1234,12 +1290,14 @@ def wait_for_review( or suppress a read error that would otherwise propagate. The signal must be observable through the supplied event's own flag and - condition. Call ``set()`` on the event passed here; a cached bound - setter or a direct mutation of a delegating event's backing object does - not wake an in-progress backoff. A getter-only property exposing the - standard ``threading.Event.set()`` is supported through its condition. - Backing notifications are timestamped when they occur and verified - against the supplied event's flag at the next checkpoint. + condition. Call ``set()`` on the event passed here. A cached bound + standard setter is supported because it still notifies that event's + condition; a setter that bypasses the observed condition, or a direct + mutation of a backing object the caller does not expose, cannot wake an + in-progress backoff. A getter-only property exposing the standard + ``threading.Event.set()`` is supported through its condition. Verified + backing notifications are timestamped when they occur; unverified wakes + are rechecked against the supplied event's flag at the next checkpoint. """ if not math.isfinite(timeout) or timeout < 0: @@ -1667,8 +1725,9 @@ async def wait_for_review( do not only mutate a backing object's flag, which can still be observed at a check after a read but will not wake an in-progress backoff. The SDK observes the signal through its own waiter without binding the - caller's event to the loop; an event already bound to another loop is - rejected before the first request. + caller's event to the loop; an event or existing waiter already bound + to another loop is rejected before the early cancellation check or the + first request. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -1676,6 +1735,8 @@ async def wait_for_review( if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): raise TypeError("cancel_event must be an asyncio.Event.") url = _review_url(self._base_url, organization_id, review_id) + if cancel_event is not None: + _check_async_event_loop(cancel_event) if _cancelled(cancel_event): return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None diff --git a/tests/test_http.py b/tests/test_http.py index 7f4ecd82..771fa695 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -111,10 +111,11 @@ async def wait_for_all(aws: Any, **kwargs: Any) -> Any: return await asyncio.wait(aws, **kwargs) -async def finish_sender(sender: asyncio.Task[Any]) -> None: - """Bound and reap a test signal task even when an assertion fails.""" +async def finish_sender(sender: asyncio.Task[Any], *, check: bool = True) -> None: + """Reap a signal task; only propagate its timeout when the probe succeeded.""" try: - await asyncio.wait_for(sender, 1.0) + if check: + await asyncio.wait_for(sender, 1.0) finally: sender.cancel() await asyncio.gather(sender, return_exceptions=True) @@ -1753,6 +1754,7 @@ def fail(*args: Any) -> None: assert handles assert all(handle.cancelled() for handle in handles) assert not event._waiters + assert id(event) not in client_module._async_signal_watches async def test_async_future_watch_keeps_one_hook_for_overlapping_observers( @@ -1989,6 +1991,7 @@ def fail(*args: Any) -> None: assert captured[0].cancelled() assert not event._waiters assert id(captured[0]) not in client_module._async_future_watches + assert id(event) not in client_module._async_signal_watches def test_condition_tracker_validates_each_subscriber_event( @@ -2359,6 +2362,7 @@ def set(self) -> None: event = BackingEvent() ready = threading.Event() + failures: list[str] = [] real_track = client_module._track_sync_cancel def track(event_arg: Any, deadline: Any) -> None: @@ -2368,18 +2372,23 @@ def track(event_arg: Any, deadline: Any) -> None: monkeypatch.setattr(client_module, "_track_sync_cancel", track) def signal() -> None: - assert ready.wait(1.0), "the cancellation observers were never installed" + if not ready.wait(2.0): + failures.append("the cancellation observers were never installed") + clock.now = 101.5 + event.set() + return clock.now = 100.5 event.set() clock.now = 102.0 - thread = threading.Thread(target=signal) + thread = threading.Thread(target=signal, daemon=True) thread.start() try: assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False finally: - thread.join(1.0) + thread.join(2.0) assert not thread.is_alive() + assert failures == [] assert "notify_all" not in vars(event.backing._cond) @@ -2541,22 +2550,43 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) def test_sleep_with_cancel_supports_an_instance_wait_override( monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._wait_for_event clock = Clock(monkeypatch) - event = threading.Event() + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - def wait_override(timeout: float | None = None) -> bool: - clock.now = 100.5 - return False + class NeverWaitEvent(threading.Event): + def wait(self, timeout: float | None = None) -> bool: + raise AssertionError("the SDK must not call the caller's wait() override") - event.wait = wait_override # type: ignore[method-assign] + event = NeverWaitEvent() + ready = threading.Event() + failures: list[str] = [] + real_track = client_module._track_sync_cancel - def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + def track(event_arg: Any, deadline: Any) -> None: + real_track(event_arg, deadline) + ready.set() + + monkeypatch.setattr(client_module, "_track_sync_cancel", track) + + def signal() -> None: + if not ready.wait(2.0): + failures.append("the cancellation observers were never installed") + clock.now = 101.5 + event.set() + return clock.now = 100.5 - wait_event.set() - return False + event.set() + clock.now = 102.0 - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + thread = threading.Thread(target=signal, daemon=True) + thread.start() + try: + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + finally: + thread.join(2.0) + assert not thread.is_alive() + assert failures == [] assert clock.delays == [] @@ -2631,83 +2661,119 @@ def set(self) -> Any: assert "set" not in vars(event) -@MODES -async def test_wait_for_review_cancel_event_wakes_real_backoff( - mode: str, monkeypatch: pytest.MonkeyPatch -) -> None: - body = review("RUNNING") - body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) - event: Any = asyncio.Event() if mode == "async" else threading.Event() - ready: Any = asyncio.Event() if mode == "async" else threading.Event() - setter: Any = None +def test_sync_wait_for_review_cancel_event_wakes_real_backoff_in_subprocess() -> None: + # A deadlocked synchronous worker must be terminable by the parent test. + code = """ +import sys +import threading +import time +from pathlib import Path - if mode == "sync": +root = sys.argv[1] +sys.path.insert(0, root) +from tests import test_http as t - class ReadySignalEvent(threading.Event): - def wait(self, timeout: float | None = None) -> bool: - ready.set() - return super().wait(timeout) +body = t.review("RUNNING") +body.update(assessment_count=0, assessments=[], code_assessment=t.code_assessment("RUNNING")) +event = threading.Event() +ready = threading.Event() +real_track = t.client_module._track_sync_cancel - real_track = client_module._track_sync_cancel - def track(event_arg: Any, deadline: Any) -> None: - real_track(event_arg, deadline) - deadline.signal_event = ReadySignalEvent() +class ReadyCondition(threading.Condition): + def wait(self, timeout=None): + # The caller holds the condition lock here, so the sender cannot set + # the event until this waiter is registered and the lock is released. + ready.set() + return super().wait(timeout) - monkeypatch.setattr(client_module, "_track_sync_cancel", track) - def set_later() -> None: - assert ready.wait(1.0), "the sync backoff waiter was never registered" - event.set() +class ReadySignalEvent(threading.Event): + def __init__(self): + super().__init__() + self._cond = ReadyCondition(self._cond._lock) - setter = threading.Thread(target=set_later, daemon=True) - setter.start() - else: - real_async_wait = client_module._async_wait_for_event - async def async_wait(*args: Any, **kwargs: Any) -> bool: - helper = asyncio.create_task(real_async_wait(*args, **kwargs)) - try: - await wait_until(lambda: len(event._waiters) >= 2) - ready.set() - return await helper - finally: - helper.cancel() - await asyncio.gather(helper, return_exceptions=True) +def track(event_arg, deadline): + real_track(event_arg, deadline) + deadline.signal_event = ReadySignalEvent() - monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait) - async def set_later() -> None: - await asyncio.wait_for(ready.wait(), 1.0) - event.set() +t.client_module._track_sync_cancel = track + + +def set_later(): + if not ready.wait(2.0): + event.set() + return + event.set() + + +threading.Thread(target=set_later, daemon=True).start() +started = time.monotonic() +with t.Server(lambda request, index: t.Reply(body=body)) as server: + with t.ProoflineClient(t.SecretStr(t.TOKEN), base_url=server.url) as client: + result = client.wait_for_review( + t.ORG, t.REVIEW, timeout=5, cancel_event=event + ) +assert time.monotonic() - started < 2.0 +assert ready.is_set() +assert len(server.requests) == 1 +assert result.status == "STOPPED" +assert result.reason == "The wait was cancelled by the caller." +assert result.review is not None +assert result.review.id == t.REVIEW +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +async def test_async_wait_for_review_cancel_event_wakes_real_backoff( + monkeypatch: pytest.MonkeyPatch, +) -> None: + body = review("RUNNING") + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + event = asyncio.Event() + ready = asyncio.Event() + real_async_wait = client_module._async_wait_for_event - setter = asyncio.create_task(set_later()) + async def async_wait(*args: Any, **kwargs: Any) -> bool: + helper = asyncio.create_task(real_async_wait(*args, **kwargs)) + try: + await wait_until(lambda: len(event._waiters) >= 2) + ready.set() + return await helper + finally: + helper.cancel() + await asyncio.gather(helper, return_exceptions=True) + + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait) + async def set_later() -> None: + await asyncio.wait_for(ready.wait(), 2.0) + event.set() + + setter = asyncio.create_task(set_later()) started = time.monotonic() with Server(lambda request, index: Reply(body=body)) as server: - async with session(mode, server.url) as client: + async with session("async", server.url) as client: try: - if mode == "sync": - result = await asyncio.wait_for( - asyncio.to_thread( - client.wait_for_review, - ORG, - REVIEW, - timeout=5, - cancel_event=event, - ), - timeout=2.0, - ) - else: - result = await asyncio.wait_for( - client.wait_for_review(ORG, REVIEW, timeout=5, cancel_event=event), - timeout=2.0, - ) - finally: - if mode == "sync": - setter.join(1.0) - else: - await finish_sender(setter) + result = await asyncio.wait_for( + client.wait_for_review(ORG, REVIEW, timeout=5, cancel_event=event), + timeout=2.0, + ) + except BaseException: + await finish_sender(setter, check=False) + raise + await finish_sender(setter) assert time.monotonic() - started < 2.0 assert ready.is_set() @@ -4348,54 +4414,83 @@ def register() -> None: assert id(event) not in client_module._sync_set_watches -async def test_async_future_registration_waits_for_a_restoring_teardown( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_async_future_registration_waits_for_a_restoring_teardown() -> None: + code = """ +import asyncio +import sys +import threading + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +ready_to_restore = threading.Event() +allow_restore = threading.Event() + + +async def main(): event = asyncio.Event() future = asyncio.get_running_loop().create_future() - first = client_module._SignalDeadline(101.0) - second = client_module._SignalDeadline(101.0) - client_module._watch_async_future(future, event, first) - watch = client_module._async_future_watches[id(future)] + first = client._SignalDeadline(101.0) + second = client._SignalDeadline(101.0) + client._watch_async_future(future, event, first) + watch = client._async_future_watches[id(future)] real_restore = watch.restore - restore_started = threading.Event() - allow_restore = threading.Event() - def slow_restore() -> None: - restore_started.set() - if allow_restore.wait(1.0): + def slow_restore(): + ready_to_restore.set() + if allow_restore.wait(5.0): real_restore() - monkeypatch.setattr(watch, "restore", slow_restore) + watch.restore = slow_restore teardown = asyncio.create_task( - asyncio.to_thread(client_module._unwatch_async_future, future, first) + asyncio.to_thread(client._unwatch_async_future, future, first) ) - joiner: asyncio.Task[None] | None = None + joiner = None try: - assert await asyncio.to_thread(restore_started.wait, 1.0) + assert await asyncio.to_thread(ready_to_restore.wait, 5.0) registered = threading.Event() - def register() -> None: - client_module._watch_async_future(future, event, second) + def register(): + client._watch_async_future(future, event, second) registered.set() joiner = asyncio.create_task(asyncio.to_thread(register)) await asyncio.sleep(0.05) assert not registered.is_set(), "registration saw the outgoing future hook" allow_restore.set() - await asyncio.wait_for(teardown, 1.0) - assert await asyncio.to_thread(registered.wait, 1.0) - assert await asyncio.wait_for(joiner, 1.0) is None + await asyncio.wait_for(teardown, 2.0) + assert await asyncio.to_thread(registered.wait, 2.0) + assert await asyncio.wait_for(joiner, 2.0) is None finally: allow_restore.set() - await asyncio.gather(teardown, return_exceptions=True) - if joiner is not None: - await asyncio.gather(joiner, return_exceptions=True) - if second in getattr(client_module._async_future_watches.get(id(future)), "deadlines", ()): - client_module._unwatch_async_future(future, second) + for task in (teardown, joiner): + if task is not None: + task.cancel() + await asyncio.gather( + *(task for task in (teardown, joiner) if task is not None), + return_exceptions=True, + ) + try: + real_restore() + except Exception: + pass assert "set_result" not in getattr(future, "__dict__", {}) +asyncio.run(main()) +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + def test_condition_tracker_rolls_back_a_failing_first_assignment() -> None: class FailNotifyAllCondition(threading.Condition): def __init__(self, lock: Any) -> None: @@ -4550,3 +4645,155 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False assert "notify_all" not in vars(event.backing._cond) + + +async def test_async_signal_watch_publishes_each_pulse_to_current_deadlines( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + signal = client_module._AsyncSignalWatch(event) + client_module._async_signal_watches[id(event)] = signal + first = client_module._SignalDeadline(clock.now + 10.0) + second = client_module._SignalDeadline(clock.now + 10.0) + signal.add(first) + signal.add(second) + try: + clock.now = 100.1 + signal.note(clock.now) + assert first.signalled_at == second.signalled_at == 100.1 + + event.clear() + third = client_module._SignalDeadline(clock.now + 10.0) + signal.add(third) + clock.now = 100.2 + signal.note(clock.now) + assert first.signalled_at == 100.1 + assert second.signalled_at == 100.1 + assert third.signalled_at == 100.2 + finally: + for deadline in (first, second, third): + signal.remove(deadline) + if not signal.deadlines: + client_module._async_signal_watches.pop(id(event), None) + + +async def test_async_future_refcounts_a_deadline_across_waiters( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + other = asyncio.get_running_loop().create_future() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._watch_async_future(future, event, deadline) + client_module._watch_async_future(other, event, deadline) + signal = client_module._async_signal_watches[id(event)] + try: + assert signal.counts[deadline] == 2 + assert client_module._unwatch_async_future(future, deadline) is True + assert deadline in signal.deadlines + assert id(event) in client_module._async_signal_watches + + clock.now = 100.5 + event.set() + other.set_result(True) + assert deadline.signalled_at == 100.5 + assert client_module._unwatch_async_future(other, deadline) is True + assert id(event) not in client_module._async_signal_watches + finally: + client_module._unwatch_async_future(future, deadline) + client_module._unwatch_async_future(other, deadline) + + +def test_sync_set_watch_stamps_one_notification_once_for_all_deadlines( + monkeypatch: pytest.MonkeyPatch, +) -> None: + readings = iter((100.5, 101.5)) + monkeypatch.setattr(client_module, "monotonic", lambda: next(readings)) + event = threading.Event() + first = client_module._SignalDeadline(101.0) + second = client_module._SignalDeadline(102.0) + assert client_module._watch_sync_set(event, first) + assert client_module._watch_sync_set(event, second) + try: + event.set() + assert first.signalled_at == second.signalled_at == 100.5 + finally: + client_module._unwatch_sync_set(event, first) + client_module._unwatch_sync_set(event, second) + + +def test_sleep_with_cancel_does_not_backdate_a_late_flag_from_an_unverified_wake( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.hinted = threading.Event() + self.revealed = threading.Event() + + def is_set(self) -> bool: + return self.revealed.is_set() + + def set(self) -> None: + self.revealed.set() + self.hinted.set() + + event = GatedEvent() + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + time.sleep(0.05) + wait_event.revealed.set() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + event.hinted.set() # An early wake that does not verify the caller's flag. + assert client_module._sleep_with_cancel(0.03, event) is True + + +def test_async_waiter_registration_is_atomic_across_event_loops() -> None: + event = asyncio.Event() + results: list[str] = [] + attempted = threading.Event() + release = threading.Event() + + def run() -> None: + async def main() -> None: + deadline = client_module._SignalDeadline(time.monotonic() + 10.0) + try: + waiter = client_module._watch_async_waiter(event, deadline) + results.append("registered") + assert attempted.wait(2.0), "the competing loop never attempted registration" + assert release.wait(2.0), "the competing loop never finished" + client_module._unwatch_async_waiter(waiter, deadline) + except RuntimeError: + results.append("rejected") + finally: + attempted.set() + release.set() + + asyncio.run(main()) + + threads = [threading.Thread(target=run) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(3.0) + assert not any(thread.is_alive() for thread in threads) + assert sorted(results) == ["registered", "rejected"] + assert not event._waiters + assert id(event) not in client_module._async_signal_watches + + +async def test_async_wait_for_review_rejects_a_set_foreign_loop_event_before_a_request() -> None: + class BoundEvent(asyncio.Event): + _loop = object() + + event = BoundEvent() + event.set() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + with pytest.raises(RuntimeError, match="different event loop"): + await client.wait_for_review(ORG, REVIEW, timeout=100, cancel_event=event) + assert server.requests == [] From c8f64b2ee03db1f8142a1e724795f33aa85a8dfe Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sat, 28 Nov 2026 16:45:16 +0530 Subject: [PATCH 22/22] Address twenty-first Proofline review findings --- README.md | 4 +- proofline/client.py | 324 +++++++++--------- tests/test_http.py | 778 +++++++++++++++++++++++++++++--------------- 3 files changed, 676 insertions(+), 430 deletions(-) diff --git a/README.md b/README.md index ea34d704..f7ceb104 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,7 @@ if outcome.status != "COMPLETED": print(outcome.status, outcome.reason) ``` -`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. If `cancel_event` is also set and cancellation is observed before the deadline, cancellation takes precedence over that mismatch: the status is `STOPPED`, the mismatch or unavailable-head gap is still attached, and `reason` is the cancellation reason. The response must still pass normal validation, and a signal first delivered at or after the deadline does not override the mismatch. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. If `cancel_event` is also set and cancellation is observed before the deadline, cancellation takes precedence over that mismatch: the status is `STOPPED`, the mismatch or unavailable-head gap is still attached, and `reason` is the cancellation reason. The response must still pass normal validation. A signal first delivered at or after the deadline is ignored and does not override the mismatch; because the deadline is checked first, a mismatch observed only after expiry returns `TIMED_OUT` with the `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. ## Cancelling a wait @@ -101,7 +101,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -Cancellation is checked before the wait starts, before each poll, during the backoff, and after each read. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event. A cached bound standard `threading.Event.set()` still notifies that event's condition and works; a setter that bypasses the observed condition, or a direct mutation of a backing object, may not wake an in-progress backoff. For `asyncio.Event`, the setter must notify waiters registered on that same event; changing only a backing object's flag does not notify those waiters, though a flag that is still set can be observed at a check after a read. The SDK never binds the caller's async event to the wait's loop, so the same event may be reused later as long as it is not already bound to a different loop and has no waiters from one; those events are rejected before the first request. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request; the timeout clock starts after that initial check. Cancellation is then checked before each poll, during the backoff, and after each read. A signal delivered while arguments are validated is bounded by that entry deadline, so one delivered at or after expiry is ignored. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event. A cached bound standard `threading.Event.set()` still notifies that event's condition and works; a setter that bypasses the observed condition, or a direct mutation of a backing object, may not wake an in-progress backoff. For `asyncio.Event`, the setter must notify waiters registered on that same event; changing only a backing object's flag does not notify those waiters, though a flag that is still set can be observed at a check after a read. The SDK never binds the caller's async event to the wait's loop or assigns to the caller's `set()` attribute, so the same event may be reused later as long as it is not already bound to a different loop and has no waiters from one; those events are rejected under the waiter-registration lock before the first request. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 4c6d1906..71760685 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -13,6 +13,7 @@ from asyncio import wait as async_wait from collections import deque from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from contextlib import ExitStack from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -213,8 +214,10 @@ def _thread_event_is_set(event: threading.Event | AsyncEvent) -> bool: _notify_lock = threading.RLock() _publication_lock = threading.Lock() -# (deadline, sampled time, whether the caller's own flag was verified at delivery) +# (deadline, sampled time, whether the notification was verified at delivery) _pending_notifications: list[tuple[_SignalDeadline, float, bool]] = [] +# Synchronizes snapshots of an event's attributes with condition-hook installation. +_sync_set_lock = threading.Lock() def _stage_signals(items: tuple[tuple[_SignalDeadline, float, bool], ...]) -> None: @@ -224,11 +227,11 @@ def _stage_signals(items: tuple[tuple[_SignalDeadline, float, bool], ...]) -> No def _drain_signals() -> None: - """Publish staged notifications under the same lock used by deadline checks.""" - with _publication_lock: - items = tuple(_pending_notifications) - _pending_notifications.clear() + """Publish staged notifications under one continuous deadline-lock section.""" with _notify_lock: + with _publication_lock: + items = tuple(_pending_notifications) + _pending_notifications.clear() for deadline, now, verified in items: if verified: deadline.record(now) @@ -249,7 +252,6 @@ def __init__(self, end: float) -> None: self.end = end self.signalled_at: float | None = None self.conditions: tuple[threading.Condition, ...] = () - self.watched_set = False self.signal_event = threading.Event() def record(self, now: float) -> bool: @@ -265,20 +267,31 @@ def defer(self, now: float) -> None: self.signal_event.set() +def _event_attributes_snapshot(value: Any) -> tuple[Any, ...]: + """Read an event's instance attributes without racing hook installation.""" + with _sync_set_lock: + return tuple(_instance_attributes(value).values()) + + +def _standard_thread_is_set(value: Any) -> bool: + """Whether the predicate is the standard Event.is_set(), without an override.""" + method = getattr(value, "is_set", None) + return getattr(method, "__func__", None) is threading.Event.is_set and ( + getattr(method, "__self__", None) is value + ) + + def _flag_verified_at_delivery(caller: Any, watched: Any) -> bool: - """Check a flag without calling an override under the notifying condition.""" + """Verify a backing notification only when the caller's predicate is inspectable.""" if not bool(getattr(watched, "_flag", False)): return False if caller is watched: return True - attributes = _instance_attributes(caller) - delegates = "is_set" in attributes or type(caller).is_set is not threading.Event.is_set - sources = [value for value in attributes.values() if isinstance(value, threading.Event)] - return ( - delegates - and any(value is watched for value in sources) - and all(bool(getattr(value, "_flag", False)) for value in sources) - ) + # An overridden predicate can require state unrelated to the raw flag, so + # only the standard predicate can be verified without calling user code. + if not _standard_thread_is_set(caller) or not bool(getattr(caller, "_flag", False)): + return False + return any(value is watched for value in _event_attributes_snapshot(caller)) def _restore_method(target: Any, name: str, had_instance: bool, saved: Any, installed: Any) -> None: @@ -363,79 +376,37 @@ def notify(self, *args: Any, **kwargs: Any) -> None: self.original_notify(*args, **kwargs) def restore(self) -> None: - _restore_method( - self.condition, - "notify_all", - self.had_notify_all, - self.saved_notify_all, - self.installed_notify_all, - ) - _restore_method( - self.condition, - "notify", - self.had_notify, - self.saved_notify, - self.installed_notify, - ) + # One failing restoration must not hide the other one. + error: Exception | None = None + for name, had_instance, saved, installed in ( + ("notify_all", self.had_notify_all, self.saved_notify_all, self.installed_notify_all), + ("notify", self.had_notify, self.saved_notify, self.installed_notify), + ): + try: + _restore_method(self.condition, name, had_instance, saved, installed) + except Exception as exc: + if error is None: + error = exc + if error is not None: + raise error _notify_trackers: dict[int, _ConditionSignalTracker] = {} -_sync_set_lock = threading.Lock() -_sync_set_watches: dict[int, _SyncSetWatch] = {} - - -class _SyncSetWatch: - """Watch one event's public set(), with independent deadline subscribers.""" - - def __init__(self, event: threading.Event) -> None: - self.event = event - attributes = _instance_attributes(event) - self.had_instance = "set" in attributes - self.saved: Any = attributes.get("set") - self.original = event.set - self.deadlines: set[_SignalDeadline] = set() - - def set_event(*args: Any, **kwargs: Any) -> Any: - # Snapshot before delegation: a wait that subscribes after a - # set/clear pulse must not inherit this notification. - with _sync_set_lock: - deadlines = tuple(self.deadlines) - result = self.original(*args, **kwargs) - if not _thread_event_is_set(self.event): - return result - # One timestamp for every subscriber to this single notification. - now = monotonic() - _publish_signals(tuple((deadline, now) for deadline in deadlines)) - return result - - self.installed = set_event - - def install(self) -> None: - try: - self.event.set = self.installed # type: ignore[method-assign] - except BaseException: - _restore_method(self.event, "set", self.had_instance, self.saved, self.installed) - raise - - def restore(self) -> None: - _restore_method(self.event, "set", self.had_instance, self.saved, self.installed) - - -def _standard_thread_setter(event: threading.Event) -> bool: - """Whether a read-only property still exposes the standard Event.set().""" - return getattr(getattr(event, "set", None), "__func__", None) is threading.Event.set -def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: - """Watch the event's condition and any backing event conditions it exposes.""" +def _discover_thread_conditions( + event: threading.Event, +) -> tuple[tuple[threading.Condition, Any, bool], ...]: + """Snapshot the conditions reachable from an event's own attributes.""" + with _sync_set_lock: + attributes = tuple(_instance_attributes(event).values()) + own_condition = getattr(event, "_cond", None) watched: list[tuple[threading.Condition, Any, bool]] = [] - condition = getattr(event, "_cond", None) - if isinstance(condition, threading.Condition): - watched.append((condition, event, False)) - seen = {id(condition)} - else: - seen = set() - for value in _instance_attributes(event).values(): + seen: set[int] = set() + if isinstance(own_condition, threading.Condition): + watched.append((own_condition, event, False)) + seen.add(id(own_condition)) + for value in attributes: backing_condition = ( getattr(value, "_cond", None) if isinstance(value, threading.Event) else None ) @@ -447,6 +418,12 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ continue seen.add(id(backing_condition)) watched.append((backing_condition, value, True)) + return tuple(watched) + + +def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _SignalDeadline: + """Watch the event's condition and any backing event conditions it exposes.""" + watched = _discover_thread_conditions(event) deadline.conditions = tuple(item[0] for item in watched) with _notify_lock: for tracked, watched_event, backing in watched: @@ -485,53 +462,27 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> raise error -def _watch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> bool: - """Install the public setter hook when assignment is supported.""" - with _sync_set_lock: - watch = _sync_set_watches.get(id(event)) - if watch is None: - watch = _SyncSetWatch(event) - try: - watch.install() - except AttributeError: - # A getter-only property exposing the standard setter is safe: - # its condition hook already observes the notification. - if not _standard_thread_setter(event): - raise - deadline.watched_set = False - return False - _sync_set_watches[id(event)] = watch - watch.deadlines.add(deadline) - deadline.watched_set = True - return True - - -def _unwatch_sync_set(event: threading.Event, deadline: _SignalDeadline) -> None: - deadline.watched_set = False - with _sync_set_lock: - watch = _sync_set_watches.get(id(event)) - if watch is None: - return - watch.deadlines.discard(deadline) - if not watch.deadlines: - del _sync_set_watches[id(event)] - watch.restore() - - def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: - # Condition observers catch captured setters and backing notifications; the - # public set hook additionally catches subclasses that notify a condition - # the SDK cannot discover from instance attributes. + # Observation uses only the event's condition(s), never the caller's set(). _track_thread_signal(event, deadline) - _watch_sync_set(event, deadline) + + +def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> bool: + """Install observers and sample the initial flag under the conditions' locks.""" + conditions = tuple(item[0] for item in _discover_thread_conditions(event)) + with ExitStack() as stack: + for condition in conditions: + stack.enter_context(condition) + _track_sync_cancel(event, deadline) + _drain_signals() + if _thread_event_is_set(event): + _publish_signals(((deadline, monotonic()),)) + _drain_signals() + return deadline.signalled_at is not None def _untrack_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: - try: - if deadline.watched_set: - _unwatch_sync_set(event, deadline) - finally: - _untrack_thread_signal(event, deadline) + _untrack_thread_signal(event, deadline) def _cancelled(event: threading.Event | AsyncEvent | None) -> bool: @@ -632,7 +583,11 @@ def _event_is_set(event: AsyncEvent) -> bool: def _check_async_event_loop(event: asyncio.Event) -> None: - """Reject an event or waiter already bound to another event loop.""" + """Reject an event or waiter already bound to another event loop. + + The caller holds ``_async_future_lock`` so this scan cannot race waiter + removal on another thread. + """ loop = async_get_running_loop() event_loop = getattr(event, "_loop", None) if event_loop is not None and event_loop is not loop: @@ -650,6 +605,7 @@ def __init__(self, event: AsyncEvent) -> None: self.event = event self.deadlines: set[_SignalDeadline] = set() self.counts: dict[_SignalDeadline, int] = {} + self.dispatch_done = False def add(self, deadline: _SignalDeadline) -> None: self.counts[deadline] = self.counts.get(deadline, 0) + 1 @@ -666,11 +622,30 @@ def remove(self, deadline: _SignalDeadline) -> bool: return False def note(self, now: float) -> None: - # Every pulse reaches the deadlines subscribed at that moment. Each - # deadline latches only its own first timely signal. + # One dispatch of asyncio.Event.set() completes every waiter future; + # publish once for that dispatch, and arm again after a clear. + if self.dispatch_done and not _event_is_set(self.event): + self.dispatch_done = False + if self.dispatch_done: + return with _async_future_lock: deadlines = tuple(self.deadlines) _publish_signals(tuple((deadline, now) for deadline in deadlines)) + self.dispatch_done = True + + +def _should_publish_async_signal(event: AsyncEvent, future: AsyncFuture[Any]) -> bool: + """Publish once for this dispatch from the first watched waiter.""" + waiters = getattr(event, "_waiters", ()) or () + with _async_future_lock: + for pending in waiters: + if pending is future: + return True + if bool(getattr(pending, "done", lambda: True)()): + continue + if id(pending) in _async_future_watches: + return False + return True class _AsyncFutureWatch: @@ -689,10 +664,12 @@ def __init__( self.deadlines: set[_SignalDeadline] = set() def set_result(result: Any) -> None: - now = monotonic() if _event_is_set(event): - signal.note(now) - self.original(result) + if _should_publish_async_signal(event, future): + self.signal.note(monotonic()) + self.original(result) + # An unverified wake leaves this observer armed: a later verified + # clear/set dispatch can still complete it and deliver the signal. self.installed = set_result try: @@ -740,6 +717,8 @@ def _watch_async_future( if not signal.deadlines and _async_signal_watches.get(id(event)) is signal: _async_signal_watches.pop(id(event), None) raise + if not _event_is_set(event): + signal.dispatch_done = False if owns_signal: _async_signal_watches[id(event)] = signal @@ -1281,41 +1260,46 @@ def wait_for_review( head_commit_sha holds the outcome to that commit. A review pinned to another head ends the wait on that read and is never COMPLETED. - cancel_event stops the wait before another request. It is checked before - each poll, during the backoff, and after each read. An in-flight read is - not interrupted: cancellation waits for that read to finish, including - transport retries and their delays. Those delays count toward the overall - wait deadline rather than a single HTTP timeout. A signal first delivered - at or after the deadline is ignored; it does not change the wait's result + An event already set at entry stops the wait before any request, even + when ``timeout`` is zero; the timeout clock starts after that check. + cancel_event then stops the wait before another request. It is checked + before each poll, during the backoff, and after each read. An in-flight + read is not interrupted: cancellation waits for that read to finish, + including transport retries and their delays. Those delays count toward + the overall wait deadline rather than a single HTTP timeout. The deadline + starts at method entry, so a signal first delivered at or after it is + ignored; it does not change the wait's result, override a head mismatch, or suppress a read error that would otherwise propagate. - The signal must be observable through the supplied event's own flag and - condition. Call ``set()`` on the event passed here. A cached bound - standard setter is supported because it still notifies that event's - condition; a setter that bypasses the observed condition, or a direct - mutation of a backing object the caller does not expose, cannot wake an - in-progress backoff. A getter-only property exposing the standard - ``threading.Event.set()`` is supported through its condition. Verified - backing notifications are timestamped when they occur; unverified wakes - are rechecked against the supplied event's flag at the next checkpoint. + The signal must notify a condition reachable from the event passed here. + Call ``set()`` on that event. The SDK never assigns to its ``set()`` + attribute, so a cached bound standard setter and a getter-only property + exposing the standard setter both work through the event's condition. A + setter that bypasses the observed condition, or a direct mutation of a + backing object the caller does not expose, cannot wake an in-progress + backoff. Verified backing notifications are timestamped when they occur; + unverified wakes are rechecked against the supplied event's flag at the + next checkpoint. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") - _head_commit(head_commit_sha) if cancel_event is not None and not isinstance(cancel_event, threading.Event): raise TypeError("cancel_event must be a threading.Event.") + started = monotonic() + initially_set = _cancelled(cancel_event) + _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) - if _cancelled(cancel_event): + deadline_at = started + timeout + if initially_set: return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None - deadline_at = monotonic() + timeout read_signal = _SignalDeadline(deadline_at) deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 try: - if cancel_event is not None: - _track_sync_cancel(cancel_event, read_signal) + if cancel_event is not None and _initial_sync_signal(cancel_event, read_signal): + return _stopped(url, None, review_id, head_commit_sha) while (_transport.remaining() or 0) > 0: if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) @@ -1716,31 +1700,37 @@ async def wait_for_review( ) -> ReviewOutcome: """Wait for recorded review completion or return TIMED_OUT. - cancel_event stops the wait before another request. It is checked before - each poll, during the backoff, and after each read. An in-flight read is - not interrupted. A signal first delivered at or after the deadline is - ignored; it does not change the wait's result or suppress a read error - that would otherwise propagate. The signal must notify waiters - registered on the event passed here: call ``set()`` on that event and - do not only mutate a backing object's flag, which can still be observed - at a check after a read but will not wake an in-progress backoff. The - SDK observes the signal through its own waiter without binding the - caller's event to the loop; an event or existing waiter already bound - to another loop is rejected before the early cancellation check or the - first request. + An event already set at entry stops the wait before any request, even + when ``timeout`` is zero; the timeout clock starts after that check. + cancel_event then stops the wait before another request. It is checked + before each poll, during the backoff, and after each read. An in-flight + read is not interrupted. The deadline starts at method entry, so a signal + first delivered at or after it is ignored; it does not change the wait's + result, override a head mismatch, or suppress a read error that would + otherwise propagate. The signal must notify waiters registered on the + event passed here: call ``set()`` on that event and do not only mutate a + backing object's flag, which can still be observed at a check after a + read but will not wake an in-progress backoff. The SDK observes the + signal through its own waiter without binding the caller's event to the + loop; an event or existing waiter already bound to another loop is + rejected under the waiter-registration lock before the early check or + the first request. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") - _head_commit(head_commit_sha) if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): raise TypeError("cancel_event must be an asyncio.Event.") - url = _review_url(self._base_url, organization_id, review_id) + started = monotonic() if cancel_event is not None: - _check_async_event_loop(cancel_event) - if _cancelled(cancel_event): + with _async_future_lock: + _check_async_event_loop(cancel_event) + initially_set = _cancelled(cancel_event) + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + deadline_at = started + timeout + if initially_set: return _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None - deadline_at = monotonic() + timeout read_signal = _SignalDeadline(deadline_at) deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 diff --git a/tests/test_http.py b/tests/test_http.py index 771fa695..ccc7f61c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -130,6 +130,7 @@ def __init__( self.callback = callback self.args = args self.kwargs = kwargs or {} + self.owner = getattr(callback, "__self__", None) self.cancelled = False def fire(self) -> None: @@ -146,7 +147,11 @@ def patch_helper_timer(monkeypatch: pytest.MonkeyPatch, loop: Any) -> list[Manua real_call_at = loop.call_at def call_at(when: float, callback: Any, *args: Any, **kwargs: Any) -> Any: - if getattr(callback, "__name__", None) == "set_result" and args == (None,): + if ( + getattr(callback, "__name__", None) == "set_result" + and isinstance(getattr(callback, "__self__", None), asyncio.Future) + and args == (None,) + ): timer = ManualTimer(callback, args, kwargs) timers.append(timer) return timer @@ -174,6 +179,8 @@ def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None woke = bool(event.is_set()) if woke and deadline is not None: deadline.record(self.now) + if woke: + return True self.sleep(timeout) if event.is_set() and deadline is not None and self.now < deadline.end: deadline.record(self.now) @@ -183,9 +190,22 @@ def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None async def async_wait_for_event( self, event: Any, cutoff: float, signal: Any | None = None ) -> bool: - self.sleep(max(0.0, cutoff - self.now)) - await asyncio.sleep(0) - return bool(event.is_set()) + arrived_at = self.now if event.is_set() else None + for _ in range(10): + await asyncio.sleep(0) + if arrived_at is None and event.is_set(): + arrived_at = self.now + break + if arrived_at is None: + self.sleep(max(0.0, cutoff - self.now)) + await asyncio.sleep(0) + if event.is_set(): + arrived_at = self.now + if arrived_at is not None and arrived_at < cutoff: + if signal is not None: + signal.record(arrived_at) + return True + return False def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -1534,6 +1554,9 @@ async def test_async_wait_for_event_ignores_a_signal_after_cutoff( task = asyncio.create_task(real_wait(event, cutoff)) try: await wait_until(lambda: bool(event._waiters)) + cutoff_future = timers[0].owner + assert isinstance(cutoff_future, asyncio.Future) + assert cutoff_future not in event._waiters clock.now = cutoff + 1.0 event.set() timers[0].fire() @@ -1804,7 +1827,7 @@ def is_set() -> bool: assert deadline.signalled_at is None -def test_sync_set_watch_timestamps_a_late_flag_after_the_setter_returns( +def test_condition_hook_ignores_a_late_flag_after_the_setter_returns( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) @@ -1816,13 +1839,14 @@ def set(self) -> None: event = LateFlagEvent() deadline = client_module._SignalDeadline(101.0) - client_module._watch_sync_set(event, deadline) + client_module._track_thread_signal(event, deadline) try: event.set() assert event.is_set() assert deadline.signalled_at is None finally: - client_module._unwatch_sync_set(event, deadline) + client_module._untrack_thread_signal(event, deadline) + assert "set" not in vars(event) async def test_async_wait_for_event_supports_a_read_only_setter( @@ -1875,7 +1899,7 @@ def set(self) -> None: await asyncio.gather(task, return_exceptions=True) -def test_sync_set_watch_preserves_a_replacement_setter( +def test_condition_observation_preserves_a_replacement_setter( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) @@ -1885,11 +1909,11 @@ def test_sync_set_watch_preserves_a_replacement_setter( def replacement() -> None: return None - client_module._watch_sync_set(event, deadline) + client_module._track_thread_signal(event, deadline) try: event.set = replacement # type: ignore[method-assign] finally: - client_module._unwatch_sync_set(event, deadline) + client_module._untrack_thread_signal(event, deadline) assert event.set is replacement @@ -2316,7 +2340,7 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert clock.delays == [] -def test_sleep_with_cancel_restores_condition_after_a_set_hook_failure( +def test_sleep_with_cancel_accepts_a_read_only_setter_through_its_condition( monkeypatch: pytest.MonkeyPatch, ) -> None: real_wait = client_module._wait_for_event @@ -2334,62 +2358,73 @@ def wait(self, timeout: float | None = None) -> bool: event = ReadOnlySetEvent() condition = event._cond notify_all = condition.notify_all - with pytest.raises(AttributeError, match="set is read-only"): - client_module._sleep_with_cancel(0, event) + assert client_module._sleep_with_cancel(0, event) is True assert condition.notify_all == notify_all + assert "set" not in vars(event) -def test_sleep_with_cancel_tracks_a_backing_thread_event( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - - class BackingEvent(threading.Event): - def __init__(self) -> None: - super().__init__() - self.backing = threading.Event() +def test_sleep_with_cancel_tracks_a_backing_thread_event() -> None: + # A deadlocked notification must be terminable by the parent test. + code = """ +import sys +import threading - def is_set(self) -> bool: - return self.backing.is_set() +root = sys.argv[1] +sys.path.insert(0, root) +from tests import test_http as t - def wait(self, timeout: float | None = None) -> bool: - return self.backing.wait(timeout) +class BackingEvent(threading.Event): + def __init__(self): + super().__init__() + self.backing = threading.Event() + self.is_set = threading.Event.is_set.__get__(self, threading.Event) - def set(self) -> None: - self.backing.set() + def set(self): + super().set() + self.backing.set() - event = BackingEvent() - ready = threading.Event() - failures: list[str] = [] - real_track = client_module._track_sync_cancel +event = BackingEvent() +ready = threading.Event() +failures = [] +real_track = t.client_module._track_sync_cancel - def track(event_arg: Any, deadline: Any) -> None: - real_track(event_arg, deadline) - ready.set() +def track(event_arg, deadline): + real_track(event_arg, deadline) + ready.set() - monkeypatch.setattr(client_module, "_track_sync_cancel", track) +t.client_module._track_sync_cancel = track +t.client_module.monotonic = lambda: now[0] +now = [100.0] - def signal() -> None: - if not ready.wait(2.0): - failures.append("the cancellation observers were never installed") - clock.now = 101.5 - event.set() - return - clock.now = 100.5 +def signal(): + if not ready.wait(2.0): + failures.append("the cancellation observers were never installed") + now[0] = 101.5 event.set() - clock.now = 102.0 + return + now[0] = 100.5 + event.set() + now[0] = 102.0 - thread = threading.Thread(target=signal, daemon=True) - thread.start() - try: - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - finally: - thread.join(2.0) - assert not thread.is_alive() - assert failures == [] - assert "notify_all" not in vars(event.backing._cond) +thread = threading.Thread(target=signal, daemon=True) +thread.start() +result = t.client_module._sleep_with_cancel(5, event, cutoff=101.0) +thread.join(2.0) +assert not thread.is_alive() +assert failures == [] +assert result is False +assert "notify_all" not in vars(event.backing._cond) +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" def test_sleep_with_cancel_restores_inherited_condition_methods( @@ -2528,10 +2563,8 @@ def __init__(self) -> None: super().__init__() self.backing = threading.Event() - def is_set(self) -> bool: - return self.backing.is_set() - def set(self) -> None: + super().set() self.backing.set() event = DelegatingEvent() @@ -2736,52 +2769,70 @@ def set_later(): assert result.stdout.strip() == "OK" -async def test_async_wait_for_review_cancel_event_wakes_real_backoff( - monkeypatch: pytest.MonkeyPatch, -) -> None: - body = review("RUNNING") - body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) +def test_async_wait_for_review_cancel_event_wakes_real_backoff_in_subprocess() -> None: + # An event-loop lockup must be terminable by the parent test. + code = """ +import asyncio +import sys +import time + +root = sys.argv[1] +sys.path.insert(0, root) +from tests import test_http as t + +async def main(): + body = t.review("RUNNING") + body.update( + assessment_count=0, assessments=[], code_assessment=t.code_assessment("RUNNING") + ) event = asyncio.Event() ready = asyncio.Event() - real_async_wait = client_module._async_wait_for_event + real_wait = t.client_module._async_wait_for_event - async def async_wait(*args: Any, **kwargs: Any) -> bool: - helper = asyncio.create_task(real_async_wait(*args, **kwargs)) + async def async_wait(*args, **kwargs): + helper = asyncio.create_task(real_wait(*args, **kwargs)) try: - await wait_until(lambda: len(event._waiters) >= 2) + await t.wait_until(lambda: len(event._waiters) >= 2) ready.set() return await helper finally: helper.cancel() await asyncio.gather(helper, return_exceptions=True) - monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait) + t.client_module._async_wait_for_event = async_wait - async def set_later() -> None: + async def set_later(): await asyncio.wait_for(ready.wait(), 2.0) event.set() setter = asyncio.create_task(set_later()) started = time.monotonic() - with Server(lambda request, index: Reply(body=body)) as server: - async with session("async", server.url) as client: - try: - result = await asyncio.wait_for( - client.wait_for_review(ORG, REVIEW, timeout=5, cancel_event=event), - timeout=2.0, - ) - except BaseException: - await finish_sender(setter, check=False) - raise - await finish_sender(setter) - + with t.Server(lambda request, index: t.Reply(body=body)) as server: + async with t.session("async", server.url) as client: + result = await t.call( + client, "wait_for_review", t.ORG, t.REVIEW, timeout=5, cancel_event=event + ) + await t.finish_sender(setter) assert time.monotonic() - started < 2.0 assert ready.is_set() assert len(server.requests) == 1 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." assert result.review is not None - assert result.review.id == REVIEW + assert result.review.id == t.REVIEW + +asyncio.run(main()) +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" @MODES @@ -4365,53 +4416,71 @@ class ForeignWaiter: event._waiters.remove(foreign) # type: ignore[arg-type] -def test_sync_set_registration_waits_for_a_restoring_teardown( - monkeypatch: pytest.MonkeyPatch, -) -> None: - event = threading.Event() - first = client_module._SignalDeadline(101.0) - second = client_module._SignalDeadline(101.0) - assert client_module._watch_sync_set(event, first) - watch = client_module._sync_set_watches[id(event)] - real_restore = watch.restore - restore_started = threading.Event() - allow_restore = threading.Event() - - def slow_restore() -> None: - restore_started.set() - if allow_restore.wait(1.0): - real_restore() - - monkeypatch.setattr(watch, "restore", slow_restore) - registered = threading.Event() +def test_condition_tracker_registration_waits_for_a_restoring_teardown() -> None: + # A stuck restore must not keep the parent pytest process alive. + code = """ +import sys +import threading - def teardown() -> None: - client_module._unwatch_sync_set(event, first) +sys.path.insert(0, sys.argv[1]) +from proofline import client - def register() -> None: - client_module._watch_sync_set(event, second) - registered.set() +condition = threading.Condition() +event = threading.Event() +event._cond = condition +original_notify_all = condition.notify_all +original_notify = condition.notify +first = client._SignalDeadline(101.0) +second = client._SignalDeadline(101.0) +client._track_thread_signal(event, first) +tracker = client._notify_trackers[id(condition)] +real_restore = tracker.restore +ready_to_restore = threading.Event() +allow_restore = threading.Event() - leaver = threading.Thread(target=teardown) - joiner = threading.Thread(target=register) - leaver.start() - try: - assert restore_started.wait(1.0), "the old wrapper was never retired" - joiner.start() - assert not registered.wait(0.05), "registration saw the outgoing wrapper" - allow_restore.set() - assert registered.wait(1.0), "registration did not follow restoration" - finally: - allow_restore.set() - leaver.join(1.0) - if joiner.is_alive(): - joiner.join(1.0) - if second.watched_set: - client_module._unwatch_sync_set(event, second) - assert not leaver.is_alive() - assert not joiner.is_alive() - assert "set" not in vars(event) - assert id(event) not in client_module._sync_set_watches +def slow_restore(): + ready_to_restore.set() + if allow_restore.wait(5.0): + real_restore() + +tracker.restore = slow_restore +registered = threading.Event() + +def teardown(): + client._untrack_thread_signal(event, first) + +def register(): + client._track_thread_signal(event, second) + registered.set() + +leaver = threading.Thread(target=teardown, daemon=True) +joiner = threading.Thread(target=register, daemon=True) +leaver.start() +assert ready_to_restore.wait(2.0), "the old wrapper was never retired" +joiner.start() +assert not registered.wait(0.05), "registration saw the outgoing wrapper" +allow_restore.set() +assert registered.wait(2.0), "registration did not follow restoration" +leaver.join(2.0) +joiner.join(2.0) +assert not leaver.is_alive() +assert not joiner.is_alive() +assert id(condition) in client._notify_trackers +client._untrack_thread_signal(event, second) +assert condition.notify_all == original_notify_all +assert condition.notify == original_notify +assert id(condition) not in client._notify_trackers +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" def test_async_future_registration_waits_for_a_restoring_teardown() -> None: @@ -4461,6 +4530,7 @@ def register(): await asyncio.wait_for(teardown, 2.0) assert await asyncio.to_thread(registered.wait, 2.0) assert await asyncio.wait_for(joiner, 2.0) is None + assert client._unwatch_async_future(future, second) is True finally: allow_restore.set() for task in (teardown, joiner): @@ -4533,7 +4603,7 @@ async def test_async_future_watch_stamps_one_notification_for_all_observers( client_module._unwatch_async_future(future, second) -def test_sync_set_watch_snapshots_subscribers_before_delegating( +def test_condition_tracker_includes_a_subscriber_registered_during_notification( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) @@ -4542,19 +4612,20 @@ def test_sync_set_watch_snapshots_subscribers_before_delegating( class InterleavingEvent(threading.Event): def set(self) -> None: - client_module._watch_sync_set(self, late) + client_module._track_thread_signal(self, late) super().set() self.clear() event = InterleavingEvent() - client_module._watch_sync_set(event, early) + client_module._track_thread_signal(event, early) try: event.set() - assert early.signalled_at is None - assert late.signalled_at is None + assert early.signalled_at == clock.now + assert late.signalled_at == clock.now finally: - client_module._unwatch_sync_set(event, early) - client_module._unwatch_sync_set(event, late) + client_module._untrack_thread_signal(event, early) + client_module._untrack_thread_signal(event, late) + assert "set" not in vars(event) def test_condition_tracker_samples_time_before_the_publication_lock( @@ -4589,211 +4660,396 @@ async def test_wait_for_review_reuses_the_read_latch_for_backoff( ) -> None: clock = Clock(monkeypatch) event = asyncio.Event() if mode == "async" else threading.Event() - calls = 0 + pulses = 0 + held: list[Any] = [] real_signal = client_module._cancellation_signal def signal(event_arg: Any, deadline: Any) -> bool: - nonlocal calls - calls += 1 + nonlocal pulses result = real_signal(event_arg, deadline) - if calls == 2: + pulses += 1 + # This is the post-read check; the pulse must reach the backoff latch. + if pulses == (3 if mode == "async" else 2): event.set() event.clear() return result monkeypatch.setattr(client_module, "_cancellation_signal", signal) + + def checked(delay: float, event_arg: Any, cutoff: Any = None, latched: Any = None) -> bool: + held.append(latched) + assert latched is not None + assert real_signal(event_arg, latched) is True + return False + + async def observed_async( + delay: float, event_arg: Any, cutoff: Any = None, latched: Any = None + ) -> bool: + return checked(delay, event_arg, cutoff, latched) + + if mode == "async": + monkeypatch.setattr(client_module, "_async_sleep_with_cancel", observed_async) + else: + monkeypatch.setattr(client_module, "_sleep_with_cancel", checked) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session(mode, server.url) as client: result = await call( client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event ) assert len(server.requests) == 1 - assert calls >= 2 - assert clock.delays == [] + assert pulses == (3 if mode == "async" else 2) + assert len(held) == 1 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." assert result.review is not None assert result.review.id == REVIEW + assert clock.delays == [] + + +def test_condition_tracker_stamps_a_standard_event_once_for_all_deadlines( + monkeypatch: pytest.MonkeyPatch, +) -> None: + readings = iter((100.5, 101.5)) + monkeypatch.setattr(client_module, "monotonic", lambda: next(readings)) + event = threading.Event() + first = client_module._SignalDeadline(101.0) + second = client_module._SignalDeadline(102.0) + client_module._track_thread_signal(event, first) + client_module._track_thread_signal(event, second) + try: + event.set() + assert first.signalled_at == second.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, first) + client_module._untrack_thread_signal(event, second) -def test_sleep_with_cancel_timestamps_a_backing_notification( +def test_sleep_with_cancel_does_not_backdate_a_late_flag_from_an_unverified_wake( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) - real_wait = client_module._wait_for_event - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) - class SlowBackingEvent(threading.Event): + class GatedEvent(threading.Event): def __init__(self) -> None: super().__init__() - self.backing = threading.Event() + self.hinted = threading.Event() + self.revealed = threading.Event() def is_set(self) -> bool: - return self.backing.is_set() + return self.revealed.is_set() def set(self) -> None: - clock.now = 100.5 - self.backing.set() - clock.now = 101.5 + self.revealed.set() + self.hinted.set() - event = SlowBackingEvent() + event = GatedEvent() + ready = threading.Event() + + def track(event_arg: Any, deadline: Any) -> None: + client_module._track_thread_signal(event_arg, deadline) + ready.set() + + monkeypatch.setattr(client_module, "_track_sync_cancel", track) def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - wait_event.set() + assert ready.wait(2.0), "the cancellation observers were never installed" + clock.now = 100.5 + wait_event.hinted.set() + assert wait_event.revealed.wait(2.0), "the late signal never arrived" return False monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False - assert "notify_all" not in vars(event.backing._cond) + def signal() -> None: + assert ready.wait(2.0) + while not event.hinted.wait(0.001): + pass + clock.now = 101.5 + event.revealed.set() -async def test_async_signal_watch_publishes_each_pulse_to_current_deadlines( - monkeypatch: pytest.MonkeyPatch, -) -> None: - clock = Clock(monkeypatch) - event = asyncio.Event() - signal = client_module._AsyncSignalWatch(event) - client_module._async_signal_watches[id(event)] = signal - first = client_module._SignalDeadline(clock.now + 10.0) - second = client_module._SignalDeadline(clock.now + 10.0) - signal.add(first) - signal.add(second) + thread = threading.Thread(target=signal, daemon=True) + thread.start() try: - clock.now = 100.1 - signal.note(clock.now) - assert first.signalled_at == second.signalled_at == 100.1 - - event.clear() - third = client_module._SignalDeadline(clock.now + 10.0) - signal.add(third) - clock.now = 100.2 - signal.note(clock.now) - assert first.signalled_at == 100.1 - assert second.signalled_at == 100.1 - assert third.signalled_at == 100.2 + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True finally: - for deadline in (first, second, third): - signal.remove(deadline) - if not signal.deadlines: - client_module._async_signal_watches.pop(id(event), None) + thread.join(2.0) + assert not thread.is_alive() -async def test_async_future_refcounts_a_deadline_across_waiters( - monkeypatch: pytest.MonkeyPatch, -) -> None: +def test_async_waiter_registration_is_atomic_across_event_loops() -> None: + # Competing loops must not leave half-registered waiters behind on failure. + code = """ +import asyncio +import sys +import threading + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +event = asyncio.Event() +results = [] +attempted = threading.Event() +release = threading.Event() + +def run(): + async def main(): + deadline = client._SignalDeadline(__import__("time").monotonic() + 10.0) + try: + waiter = client._watch_async_waiter(event, deadline) + results.append("registered") + assert attempted.wait(5.0) + assert release.wait(5.0) + client._unwatch_async_waiter(waiter, deadline) + except RuntimeError: + results.append("rejected") + finally: + attempted.set() + release.set() + asyncio.run(main()) + +threads = [threading.Thread(target=run, daemon=True) for _ in range(2)] +for thread in threads: + thread.start() +for thread in threads: + thread.join(5.0) +assert not any(thread.is_alive() for thread in threads) +assert sorted(results) == ["registered", "rejected"] +assert not event._waiters +assert id(event) not in client._async_signal_watches +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +async def test_async_wait_for_review_rejects_a_set_foreign_loop_event_before_a_request() -> None: + class BoundEvent(asyncio.Event): + _loop = object() + + event = BoundEvent() + event.set() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + with pytest.raises(RuntimeError, match="different event loop"): + await client.wait_for_review(ORG, REVIEW, timeout=100, cancel_event=event) + assert server.requests == [] + + +def test_condition_tracker_drains_under_the_deadline_lock(monkeypatch: pytest.MonkeyPatch) -> None: clock = Clock(monkeypatch) - event = asyncio.Event() - future = asyncio.get_running_loop().create_future() - other = asyncio.get_running_loop().create_future() + event = threading.Event() deadline = client_module._SignalDeadline(clock.now + 10.0) - client_module._watch_async_future(future, event, deadline) - client_module._watch_async_future(other, event, deadline) - signal = client_module._async_signal_watches[id(event)] - try: - assert signal.counts[deadline] == 2 - assert client_module._unwatch_async_future(future, deadline) is True - assert deadline in signal.deadlines - assert id(event) in client_module._async_signal_watches + client_module._track_thread_signal(event, deadline) - clock.now = 100.5 + ownership: list[bool] = [] + + class CheckPublicationLock: + def __enter__(self) -> Any: + ownership.append(bool(client_module._notify_lock._is_owned())) + return self + + def __exit__(self, *args: Any) -> bool: + return False + + monkeypatch.setattr(client_module, "_publication_lock", CheckPublicationLock()) + try: event.set() - other.set_result(True) - assert deadline.signalled_at == 100.5 - assert client_module._unwatch_async_future(other, deadline) is True - assert id(event) not in client_module._async_signal_watches + assert True in ownership + assert deadline.signalled_at == clock.now finally: - client_module._unwatch_async_future(future, deadline) - client_module._unwatch_async_future(other, deadline) + client_module._untrack_thread_signal(event, deadline) -def test_sync_set_watch_stamps_one_notification_once_for_all_deadlines( +def test_condition_tracker_restores_both_hooks_after_a_failure( monkeypatch: pytest.MonkeyPatch, ) -> None: - readings = iter((100.5, 101.5)) - monkeypatch.setattr(client_module, "monotonic", lambda: next(readings)) event = threading.Event() - first = client_module._SignalDeadline(101.0) - second = client_module._SignalDeadline(102.0) - assert client_module._watch_sync_set(event, first) - assert client_module._watch_sync_set(event, second) + condition = event._cond + original_notify = condition.notify + deadline = client_module._SignalDeadline(time.monotonic() + 10.0) + client_module._track_thread_signal(event, deadline) + tracker = client_module._notify_trackers[id(condition)] + saved = tracker.saved_notify_all + installed = tracker.installed_notify_all + had_instance = tracker.had_notify_all + real_restore = client_module._restore_method + + def restore_method(target: Any, name: str, had: bool, saved_value: Any, wrapper: Any) -> None: + if name == "notify_all": + raise RuntimeError("notify_all restore failed") + real_restore(target, name, had, saved_value, wrapper) + + monkeypatch.setattr(client_module, "_restore_method", restore_method) + with pytest.raises(RuntimeError, match="notify_all restore failed"): + client_module._untrack_thread_signal(event, deadline) + assert condition.notify == original_notify + assert "notify_all" in vars(condition) + real_restore(condition, "notify_all", had_instance, saved, installed) + assert "notify_all" not in vars(condition) + + +async def test_async_event_set_publishes_once_for_all_watched_waiters( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + signal = client_module._AsyncSignalWatch(event) + client_module._async_signal_watches[id(event)] = signal + loop = asyncio.get_running_loop() + futures = [loop.create_future() for _ in range(3)] + deadlines = [client_module._SignalDeadline(clock.now + 10.0) for _ in futures] + calls: list[tuple[tuple[Any, ...], ...]] = [] + real_publish = client_module._publish_signals + + def counted(items: tuple[tuple[Any, ...], ...]) -> None: + calls.append(items) + real_publish(items) + + monkeypatch.setattr(client_module, "_publish_signals", counted) + for future, deadline in zip(futures, deadlines): + client_module._watch_async_future(future, event, deadline, signal) + event._waiters.extend(futures) try: + clock.now = 100.5 event.set() - assert first.signalled_at == second.signalled_at == 100.5 + assert len(calls) == 1 + assert all(deadline.signalled_at == 100.5 for deadline in deadlines) + assert all(future.done() for future in futures) finally: - client_module._unwatch_sync_set(event, first) - client_module._unwatch_sync_set(event, second) + for future in futures: + try: + event._waiters.remove(future) + except ValueError: + pass + for deadline in deadlines: + client_module._unwatch_async_future(future, deadline) + client_module._async_signal_watches.pop(id(event), None) -def test_sleep_with_cancel_does_not_backdate_a_late_flag_from_an_unverified_wake( +async def test_async_future_observer_stays_armed_after_an_unverified_wake( monkeypatch: pytest.MonkeyPatch, ) -> None: - class GatedEvent(threading.Event): + clock = Clock(monkeypatch) + + class GatedEvent(asyncio.Event): def __init__(self) -> None: super().__init__() - self.hinted = threading.Event() - self.revealed = threading.Event() + self.gate = False def is_set(self) -> bool: - return self.revealed.is_set() - - def set(self) -> None: - self.revealed.set() - self.hinted.set() + return self.gate and super().is_set() event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + future = waiter.future + assert future is not None + try: + clock.now = 100.1 + event.set() + assert not future.done() + assert deadline.signalled_at is None + event.clear() + clock.now = 100.2 + event.gate = True + event.set() + assert future.done() + assert deadline.signalled_at == 100.2 + finally: + client_module._unwatch_async_waiter(waiter, deadline) + + +async def test_async_wait_for_review_checks_loop_ownership_under_lock( + monkeypatch: pytest.MonkeyPatch, +) -> None: + observed: list[bool] = [] + real_check = client_module._check_async_event_loop + + def checked(event: Any) -> None: + observed.append(bool(client_module._async_future_lock._is_owned())) + real_check(event) + + monkeypatch.setattr(client_module, "_check_async_event_loop", checked) + cancel = asyncio.Event() + with Server(lambda request, index: Reply(body=review())) as server: + async with session("async", server.url) as client: + result = await client.wait_for_review(ORG, REVIEW, timeout=100, cancel_event=cancel) + assert len(server.requests) == 1 + assert result.status == "COMPLETED" + assert observed and all(observed) + + +def test_sleep_with_cancel_accepts_a_getter_only_wrapper_around_the_standard_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class WrappedEvent(threading.Event): + @property + def set(self) -> Any: + return lambda: threading.Event.set(self) + + event = WrappedEvent() def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - time.sleep(0.05) - wait_event.revealed.set() + clock.now = 100.5 + wait_event.set() + wait_event.clear() + clock.now = 102.0 return False monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - event.hinted.set() # An early wake that does not verify the caller's flag. - assert client_module._sleep_with_cancel(0.03, event) is True + assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + assert "set" not in vars(event) -def test_async_waiter_registration_is_atomic_across_event_loops() -> None: - event = asyncio.Event() - results: list[str] = [] - attempted = threading.Event() - release = threading.Event() +@MODES +async def test_wait_for_review_ignores_a_signal_delivered_during_validation( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + real_head = client_module._head_commit - def run() -> None: - async def main() -> None: - deadline = client_module._SignalDeadline(time.monotonic() + 10.0) - try: - waiter = client_module._watch_async_waiter(event, deadline) - results.append("registered") - assert attempted.wait(2.0), "the competing loop never attempted registration" - assert release.wait(2.0), "the competing loop never finished" - client_module._unwatch_async_waiter(waiter, deadline) - except RuntimeError: - results.append("rejected") - finally: - attempted.set() - release.set() - - asyncio.run(main()) - - threads = [threading.Thread(target=run) for _ in range(2)] - for thread in threads: - thread.start() - for thread in threads: - thread.join(3.0) - assert not any(thread.is_alive() for thread in threads) - assert sorted(results) == ["registered", "rejected"] - assert not event._waiters - assert id(event) not in client_module._async_signal_watches + def head(value: str | None) -> None: + if value is not None: + event.set() + real_head(value) + monkeypatch.setattr(client_module, "_head_commit", head) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=0, + head_commit_sha=HEAD, + cancel_event=event, + ) + assert len(server.requests) == 0 + assert result.status == "TIMED_OUT" + assert clock.delays == [] -async def test_async_wait_for_review_rejects_a_set_foreign_loop_event_before_a_request() -> None: - class BoundEvent(asyncio.Event): - _loop = object() - event = BoundEvent() +@MODES +async def test_wait_for_review_timeout_zero_honors_an_event_set_at_entry(mode: str) -> None: + event = asyncio.Event() if mode == "async" else threading.Event() event.set() with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: - async with session("async", server.url) as client: - with pytest.raises(RuntimeError, match="different event loop"): - await client.wait_for_review(ORG, REVIEW, timeout=100, cancel_event=event) + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=0, cancel_event=event + ) assert server.requests == [] + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller."