From 58205cfef3cd6ca71b995f76cce52fe006270333 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Tue, 24 Nov 2026 22:42:50 +0530 Subject: [PATCH 01/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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/28] 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." From 6d77f3fd8343ab2ba35893f4cd244569e0b28373 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sun, 29 Nov 2026 22:46:35 +0530 Subject: [PATCH 23/28] Address twenty-second Proofline review findings --- README.md | 7 +- proofline/client.py | 313 ++++++++++++++++----------- tests/test_http.py | 501 ++++++++++++++++++++++++++++---------------- 3 files changed, 509 insertions(+), 312 deletions(-) diff --git a/README.md b/README.md index f7ceb104..6c425d0e 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 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. +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`. The synchronous method blocks its calling thread, so set a `threading.Event` from a separate setter thread, not from a task on that same thread. For `AsyncProoflineClient`, a task on the same loop may call `cancel.set()`; 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 cancel = threading.Event() +# The wait blocks this thread; call cancel.set() from a separate setter thread. outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel) -# From another thread: cancel.set() ``` ```python @@ -98,10 +98,11 @@ outcome = await async_client.wait_for_review( review_id, cancel_event=cancel, ) +# From a task on this loop: cancel.set() # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -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. +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()` while observation is active and before the deadline 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 binds the caller's async event to the wait's loop through native registration before attaching its waiter, releases that binding when its waiter is removed, and never assigns to the caller's `set()` attribute, so the same event may be reused on another loop after the SDK waiter is gone. An event already bound to a different loop, or carrying waiters from one, is 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 71760685..82eab71c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -20,6 +20,8 @@ from typing import Any, Self, TypedDict, TypeVar, Unpack, cast from urllib.parse import quote from uuid import UUID +from weakref import WeakKeyDictionary +from weakref import ref as weak_ref import httpx2 from pydantic import SecretStr @@ -251,6 +253,7 @@ class _SignalDeadline: def __init__(self, end: float) -> None: self.end = end self.signalled_at: float | None = None + self.entry = False self.conditions: tuple[threading.Condition, ...] = () self.signal_event = threading.Event() @@ -261,6 +264,19 @@ def record(self, now: float) -> bool: return True return False + def record_entry(self, now: float) -> None: + """Latch a signal sampled before the deadline was established.""" + if self.signalled_at is None: + self.signalled_at = now + self.entry = True + self.signal_event.set() + + def cap(self, end: float) -> None: + """Apply the wait deadline to notifications observed during setup.""" + self.end = end + if not self.entry and self.signalled_at is not None and self.signalled_at >= end: + self.signalled_at = None + def defer(self, now: float) -> None: """Wake the waiter without treating an unverified notification as evidence.""" if self.signalled_at is None and now < self.end: @@ -281,19 +297,6 @@ def _standard_thread_is_set(value: Any) -> bool: ) -def _flag_verified_at_delivery(caller: Any, watched: Any) -> bool: - """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 - # 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: """Restore one hooked attribute only while it still holds our wrapper.""" if getattr(target, name, None) is not installed: @@ -318,7 +321,7 @@ class _ConditionSignalTracker: """Watch one condition, preserving whether overrides were instance attributes.""" def __init__(self, condition: threading.Condition) -> None: - self.condition = condition + self.condition_ref = weak_ref(condition) attributes = vars(condition) self.had_notify_all = "notify_all" in attributes self.saved_notify_all: Any = attributes.get("notify_all") @@ -355,6 +358,8 @@ def __init__(self, condition: threading.Condition) -> None: def record(self) -> None: # Sample and stage before contending for the deadline decision lock, so # a paused notifier cannot hide a timely signal from the final check. + # Overridable predicates are never called while the condition is locked; + # only a standard predicate on the event itself proves delivery here. now = monotonic() with self._subscription_lock: subscribers = tuple(self.subscribers.items()) @@ -362,7 +367,7 @@ def record(self) -> None: 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) + verified = not backing and watched is caller and _standard_thread_is_set(caller) staged.append((deadline, now, verified)) _stage_signals(tuple(staged)) _drain_signals() @@ -376,6 +381,10 @@ def notify(self, *args: Any, **kwargs: Any) -> None: self.original_notify(*args, **kwargs) def restore(self) -> None: + # Retained for explicit cleanup; teardown never unwraps caller hooks. + condition = self.condition_ref() + if condition is None: + return # One failing restoration must not hide the other one. error: Exception | None = None for name, had_instance, saved, installed in ( @@ -383,7 +392,7 @@ def restore(self) -> None: ("notify", self.had_notify, self.saved_notify, self.installed_notify), ): try: - _restore_method(self.condition, name, had_instance, saved, installed) + _restore_method(condition, name, had_instance, saved, installed) except Exception as exc: if error is None: error = exc @@ -391,7 +400,9 @@ def restore(self) -> None: raise error -_notify_trackers: dict[int, _ConditionSignalTracker] = {} +_notify_trackers: WeakKeyDictionary[threading.Condition, _ConditionSignalTracker] = ( + WeakKeyDictionary() +) def _discover_thread_conditions( @@ -427,39 +438,30 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ deadline.conditions = tuple(item[0] for item in watched) with _notify_lock: for tracked, watched_event, backing in watched: - key = id(tracked) - tracker = _notify_trackers.get(key) + tracker = _notify_trackers.get(tracked) if tracker is None: tracker = _ConditionSignalTracker(tracked) - _notify_trackers[key] = tracker + _notify_trackers[tracked] = tracker with tracker._subscription_lock: tracker.subscribers[deadline] = (watched_event, backing, event) return deadline def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: - error: Exception | None = None - try: - with _notify_lock: - for condition in deadline.conditions: - key = id(condition) - tracker = _notify_trackers.get(key) - if tracker is None: - continue - with tracker._subscription_lock: - tracker.subscribers.pop(deadline, None) - empty = not tracker.subscribers - if empty: - del _notify_trackers[key] - try: - tracker.restore() - except Exception as exc: - if error is None: - error = exc - finally: - deadline.conditions = () - if error is not None: - raise error + """Detach one deadline without ever unwinding a caller-owned hook. + + A tracker stays registered after its last subscriber leaves. Reusing it on + the next wait avoids stacking wrappers, and never restoring it avoids a + check-then-restore race with a caller that replaces the method. + """ + with _notify_lock: + for condition in deadline.conditions: + tracker = _notify_trackers.get(condition) + if tracker is None: + continue + with tracker._subscription_lock: + tracker.subscribers.pop(deadline, None) + deadline.conditions = () def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: @@ -467,18 +469,24 @@ def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> Non _track_thread_signal(event, deadline) -def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> bool: - """Install observers and sample the initial flag under the conditions' locks.""" +def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> tuple[bool, float]: + """Install observers and sample the entry flag under the condition locks. + + The caller's predicate is read only after those locks are released, so an + override that acquires the same non-reentrant lock cannot deadlock setup. + """ 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 + sampled = monotonic() + flagged = bool(getattr(event, "_flag", False)) + entry_set = flagged and _thread_event_is_set(event) + if entry_set: + deadline.record_entry(sampled) + _drain_signals() + return bool(entry_set), sampled def _untrack_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: @@ -554,9 +562,9 @@ 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) - # 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. + # The deadline's own signal is set by observers installed on the event's + # condition. Waiting on it never calls an overridable wait() and never polls + # in short slices; a set/clear is latched by the notification timestamp. end = min(monotonic() + timeout, deadline.end) while True: if _record_signal_before(event, deadline, deadline.end): @@ -582,12 +590,32 @@ def _event_is_set(event: AsyncEvent) -> bool: return False +def _async_flag_is_set(event: AsyncEvent) -> bool: + """Read asyncio's raw flag without calling an overridable predicate.""" + return bool(getattr(event, "_value", getattr(event, "_flag", False))) + + +def _standard_async_is_set(event: AsyncEvent) -> bool: + """Whether the predicate is the standard Event.is_set(), without an override.""" + method = getattr(event, "is_set", None) + return getattr(method, "__func__", None) is asyncio.Event.is_set and ( + getattr(method, "__self__", None) is event + ) + + def _check_async_event_loop(event: asyncio.Event) -> None: - """Reject an event or waiter already bound to another event loop. + """Bind ownership with native registration before scanning waiters. - The caller holds ``_async_future_lock`` so this scan cannot race waiter - removal on another thread. + The caller holds ``_async_future_lock``, so a competing native ``wait()`` + cannot bind the event to a different loop between the check and the SDK + attaching its own waiter. """ + binder = getattr(event, "_get_loop", None) + if binder is not None: + try: + binder() + except RuntimeError: + raise RuntimeError("cancel_event is already bound to a different event loop.") from None loop = async_get_running_loop() event_loop = getattr(event, "_loop", None) if event_loop is not None and event_loop is not loop: @@ -622,30 +650,19 @@ def remove(self, deadline: _SignalDeadline) -> bool: return False def note(self, now: float) -> None: - # 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 + # The caller has already checked the O(1) dispatch latch. Publishing is + # bounded by the number of deadlines, never by the waiter deque. 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 + def defer(self, now: float) -> None: + """Wake watchers without treating an overridden predicate as evidence.""" + with _async_future_lock: + deadlines = tuple(self.deadlines) + _stage_signals(tuple((deadline, now, False) for deadline in deadlines)) + _drain_signals() class _AsyncFutureWatch: @@ -664,12 +681,20 @@ def __init__( self.deadlines: set[_SignalDeadline] = set() def set_result(result: Any) -> None: - if _event_is_set(event): - if _should_publish_async_signal(event, future): + # asyncio.Event.set() completes watched futures without yielding. + # The first hook publishes once for all deadlines; later hooks + # only complete their own future. Verification never calls the + # event's overridable predicate from inside this dispatch. + if not _async_flag_is_set(event): + return + if not self.signal.dispatch_done: + if _standard_async_is_set(event): 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. + else: + # An overridden predicate is verified later by the waiter, + # outside the setter; this only wakes it for that check. + self.signal.defer(monotonic()) + self.original(result) self.installed = set_result try: @@ -717,8 +742,9 @@ 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 + # Registration happens outside a set() dispatch, so it starts a new + # publication generation. No overridable predicate is consulted here. + signal.dispatch_done = False if owns_signal: _async_signal_watches[id(event)] = signal @@ -747,14 +773,17 @@ class _AsyncSignalWaiter: def __init__(self) -> None: self.event: AsyncEvent | None = None self.future: AsyncFuture[Any] | None = None + self.bound_loop: Any | None = None + self.unbind_loop = False def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: - """Observe a signal without binding the caller's event to this loop.""" + """Observe a signal with native loop ownership until this waiter leaves.""" waiter = _AsyncSignalWaiter() if not isinstance(event, asyncio.Event): return waiter with _async_future_lock: + previous_loop = getattr(event, "_loop", None) _check_async_event_loop(event) loop = async_get_running_loop() waiters = getattr(event, "_waiters", None) @@ -765,6 +794,8 @@ def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncS waiters.append(future) waiter.event = event waiter.future = future + waiter.bound_loop = loop + waiter.unbind_loop = previous_loop is None try: _watch_async_future(future, event, deadline) except BaseException: @@ -775,6 +806,9 @@ def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncS future.cancel() waiter.event = None waiter.future = None + if waiter.unbind_loop and getattr(event, "_loop", None) is loop: + event._loop = None # type: ignore[attr-defined] + waiter.unbind_loop = False raise return waiter @@ -795,6 +829,13 @@ def _unwatch_async_waiter(waiter: _AsyncSignalWaiter, deadline: _SignalDeadline) waiters.remove(future) except ValueError: pass + if ( + waiter.unbind_loop + and not waiters + and getattr(event, "_loop", None) is waiter.bound_loop + ): + event._loop = None # type: ignore[attr-defined] + waiter.unbind_loop = False if not future.done(): future.cancel() @@ -1266,10 +1307,13 @@ def wait_for_review( 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 overall wait deadline rather than a single HTTP timeout. The timeout + clock starts after validation and URL construction; a cancellable wait + samples its entry deadline before validation and applies that deadline + to notifications observed during setup. A signal first delivered at or + after the deadline 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 a condition reachable from the event passed here. Call ``set()`` on that event. The SDK never assigns to its ``set()`` @@ -1286,20 +1330,26 @@ def wait_for_review( raise ValueError("The review timeout must be a finite nonnegative number of seconds.") 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) - deadline_at = started + timeout - if initially_set: - return _stopped(url, None, review_id, head_commit_sha) - last: CustomerReviewDetail | None = None - read_signal = _SignalDeadline(deadline_at) - deadline = _transport.DEADLINE.set(deadline_at) - interval = 5.0 + read_signal = _SignalDeadline(float("inf")) + initially_set = False + deadline_set = False try: - if cancel_event is not None and _initial_sync_signal(cancel_event, read_signal): + if cancel_event is not None: + initially_set, sampled = _initial_sync_signal(cancel_event, read_signal) + deadline_at = sampled + timeout + read_signal.cap(deadline_at) + else: + deadline_at = 0.0 + _head_commit(head_commit_sha) + if cancel_event is None: + deadline_at = monotonic() + timeout + if initially_set: return _stopped(url, None, review_id, head_commit_sha) + last: CustomerReviewDetail | None = None + deadline = _transport.DEADLINE.set(deadline_at) + deadline_set = True + interval = 5.0 while (_transport.remaining() or 0) > 0: if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) @@ -1336,7 +1386,8 @@ def wait_for_review( if cancel_event is not None: _untrack_sync_cancel(cancel_event, read_signal) finally: - _transport.DEADLINE.reset(deadline) + if deadline_set: + _transport.DEADLINE.reset(deadline) class AsyncProoflineClient(AsyncOperations): @@ -1704,42 +1755,50 @@ async def wait_for_review( 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. + read is not interrupted. The timeout clock starts after validation and + URL construction; a cancellable wait samples its entry deadline before + validation and applies that deadline to signals observed during setup. A + signal first delivered at or after the deadline 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. Native + event registration establishes loop ownership under the waiter lock; + an event or existing waiter already bound to another loop is rejected + before the early check or the first request. That SDK-owned binding is + released when the last waiter is removed, so the event can be reused on + another loop later. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): raise TypeError("cancel_event must be an asyncio.Event.") - started = monotonic() - if cancel_event is not None: - 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 - read_signal = _SignalDeadline(deadline_at) - deadline = _transport.DEADLINE.set(deadline_at) - interval = 5.0 + read_signal = _SignalDeadline(float("inf")) read_waiter = _AsyncSignalWaiter() + initially_set = False + deadline_set = False try: if cancel_event is not None: 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) + initially_set = _cancelled(cancel_event) + sampled = monotonic() + deadline_at = sampled + timeout + read_signal.cap(deadline_at) + else: + deadline_at = 0.0 + _head_commit(head_commit_sha) + if cancel_event is None: + deadline_at = monotonic() + timeout + if initially_set: + return _stopped(url, None, review_id, head_commit_sha) + if cancel_event is not None and _cancellation_signal(cancel_event, read_signal): + return _stopped(url, None, review_id, head_commit_sha) + last: CustomerReviewDetail | None = None + deadline = _transport.DEADLINE.set(deadline_at) + deadline_set = True + interval = 5.0 while (_transport.remaining() or 0) > 0: if _cancellation_signal(cancel_event, read_signal): return _stopped(url, last, review_id, head_commit_sha) @@ -1773,6 +1832,8 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: try: - _unwatch_async_waiter(read_waiter, read_signal) + if cancel_event is not None: + _unwatch_async_waiter(read_waiter, read_signal) finally: - _transport.DEADLINE.reset(deadline) + if deadline_set: + _transport.DEADLINE.reset(deadline) diff --git a/tests/test_http.py b/tests/test_http.py index ccc7f61c..e2e0c592 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -125,12 +125,17 @@ class ManualTimer: """A call_at handle that fires only when the test explicitly says so.""" def __init__( - self, callback: Any, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None + self, + callback: Any, + args: tuple[Any, ...], + kwargs: dict[str, Any] | None = None, + deadline: float | None = None, ) -> None: self.callback = callback self.args = args self.kwargs = kwargs or {} self.owner = getattr(callback, "__self__", None) + self.deadline = deadline self.cancelled = False def fire(self) -> None: @@ -141,20 +146,29 @@ 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.""" +def patch_helper_timer( + monkeypatch: pytest.MonkeyPatch, loop: Any, deadlines: tuple[float, ...] = () +) -> list[ManualTimer]: + """Control named helper cutoffs without capturing loop watchdogs.""" timers: list[ManualTimer] = [] real_call_at = loop.call_at + real_loop_time = loop.time def call_at(when: float, callback: Any, *args: Any, **kwargs: Any) -> Any: + owner = getattr(callback, "__self__", None) if ( getattr(callback, "__name__", None) == "set_result" - and isinstance(getattr(callback, "__self__", None), asyncio.Future) + and isinstance(owner, asyncio.Future) and args == (None,) + and not owner.done() ): - timer = ManualTimer(callback, args, kwargs) - timers.append(timer) - return timer + actual_delay = when - real_loop_time() + for deadline in deadlines: + expected_delay = max(0.0, deadline - client_module.monotonic()) + if abs(actual_delay - expected_delay) < 1e-6: + timer = ManualTimer(callback, args, kwargs, deadline) + timers.append(timer) + return timer return real_call_at(when, callback, *args, **kwargs) monkeypatch.setattr(loop, "call_at", call_at) @@ -201,7 +215,8 @@ async def async_wait_for_event( await asyncio.sleep(0) if event.is_set(): arrived_at = self.now - if arrived_at is not None and arrived_at < cutoff: + publication_deadline = signal.end if signal is not None else cutoff + if arrived_at is not None and arrived_at < publication_deadline: if signal is not None: signal.record(arrived_at) return True @@ -1548,9 +1563,9 @@ async def test_async_wait_for_event_ignores_a_signal_after_cutoff( ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) event = asyncio.Event() cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) task = asyncio.create_task(real_wait(event, cutoff)) try: await wait_until(lambda: bool(event._waiters)) @@ -1678,10 +1693,11 @@ async def test_async_wait_for_event_overlapping_waits_keep_both_waiters( ) -> 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)) + short_cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (short_cutoff,)) + first = asyncio.create_task(real_wait(event, short_cutoff)) second = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: await wait_until(lambda: len(event._waiters) >= 2) @@ -1706,10 +1722,11 @@ async def test_async_wait_for_event_restores_the_waiter_without_touching_the_set ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) event = asyncio.Event() setter = event.set - task = asyncio.create_task(real_wait(event, clock.now + 0.01)) + task = asyncio.create_task(real_wait(event, cutoff)) try: await wait_until(lambda: bool(event._waiters)) future = next(iter(event._waiters)) @@ -1875,7 +1892,12 @@ def set(self) -> Any: timer.cancel() -async def test_async_wait_for_event_requires_notification_on_the_event() -> None: +async def test_async_wait_for_event_requires_notification_on_the_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + class BackingOnlyEvent(asyncio.Event): def __init__(self) -> None: super().__init__() @@ -1888,15 +1910,20 @@ def set(self) -> None: self.backing.set() event = BackingOnlyEvent() - task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 0.05)) + cutoff = clock.now + 0.05 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + task = asyncio.create_task(real_wait(event, cutoff)) try: await wait_until(lambda: bool(event._waiters)) event.set() - assert await asyncio.wait_for(task, 1.0) is False assert event.is_set() + 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() def test_condition_observation_preserves_a_replacement_setter( @@ -1922,14 +1949,15 @@ async def test_async_wait_for_event_preserves_a_replacement_setter( ) -> None: real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) event = asyncio.Event() def replacement() -> None: return None event.set = replacement # type: ignore[method-assign] - task = asyncio.create_task(real_wait(event, clock.now + 0.01)) + task = asyncio.create_task(real_wait(event, cutoff)) try: await wait_until(lambda: bool(event._waiters)) timers[0].fire() @@ -1966,7 +1994,8 @@ 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) + cutoff = loop.time() + 100.0 + timers = patch_helper_timer(monkeypatch, loop, (cutoff,)) event = asyncio.Event() real_restore = client_module._AsyncFutureWatch.restore captured: list[Any] = [] @@ -1976,7 +2005,7 @@ def raise_on_restore(watch: Any) -> None: raise RuntimeError("restore failed") monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", raise_on_restore) - task = asyncio.create_task(client_module._async_wait_for_event(event, loop.time() + 100.0)) + task = asyncio.create_task(client_module._async_wait_for_event(event, cutoff)) try: await wait_until(lambda: bool(event._waiters)) future = next(iter(event._waiters)) @@ -2037,7 +2066,7 @@ def test_condition_tracker_validates_each_subscriber_event( assert second_deadline.signalled_at is None client_module._untrack_thread_signal(first, first_deadline) - tracker = client_module._notify_trackers.get(id(condition)) + tracker = client_module._notify_trackers.get(condition) assert tracker is not None assert len(tracker.subscribers) == 1 @@ -2061,12 +2090,14 @@ def replacement() -> None: return None client_module._track_thread_signal(event, deadline) + tracker = client_module._notify_trackers[condition] 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) + assert condition.notify is tracker.installed_notify + assert tracker.subscribers == {} def test_condition_tracker_stamps_one_notification_once_for_all_deadlines( @@ -2109,7 +2140,7 @@ def __setattr__(self, name: str, value: Any) -> None: 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 + assert condition not in client_module._notify_trackers def test_sync_deadline_lock_is_reentrant_for_signal_handlers() -> None: @@ -2252,7 +2283,7 @@ def test_sleep_with_cancel_records_a_set_clear_before_wait_registration( clock = Clock(monkeypatch) event = threading.Event() condition = event._cond - notify_all = condition.notify_all + original_notify_all = condition.notify_all setter = event.set def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: @@ -2264,8 +2295,12 @@ 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 + tracker = client_module._notify_trackers[condition] assert event.set == setter - assert condition.notify_all == notify_all + assert condition.notify_all is tracker.installed_notify_all + assert condition.notify is tracker.installed_notify + assert tracker.original_notify_all == original_notify_all + assert tracker.subscribers == {} assert clock.delays == [] @@ -2299,9 +2334,11 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) event = InheritedEvent() condition = event._cond assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False + tracker = client_module._notify_trackers[condition] assert clock.delays == [] - assert "notify_all" not in vars(condition) - assert "notify" not in vars(condition) + assert condition.notify_all is tracker.installed_notify_all + assert condition.notify is tracker.installed_notify + assert tracker.subscribers == {} def test_sleep_with_cancel_ignores_an_unrelated_condition( @@ -2359,7 +2396,9 @@ def wait(self, timeout: float | None = None) -> bool: condition = event._cond notify_all = condition.notify_all assert client_module._sleep_with_cancel(0, event) is True - assert condition.notify_all == notify_all + tracker = client_module._notify_trackers[condition] + assert condition.notify_all is tracker.installed_notify_all + assert tracker.original_notify_all == notify_all assert "set" not in vars(event) @@ -2413,7 +2452,10 @@ def signal(): assert not thread.is_alive() assert failures == [] assert result is False -assert "notify_all" not in vars(event.backing._cond) +backing_condition = event.backing._cond +tracker = t.client_module._notify_trackers[backing_condition] +assert backing_condition.notify_all is tracker.installed_notify_all +assert tracker.subscribers == {} print("OK") """ root = Path(__file__).resolve().parents[1] @@ -2449,10 +2491,12 @@ def __init__(self) -> None: 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 + tracker = client_module._notify_trackers[condition] + assert condition.notify_all is tracker.installed_notify_all + assert condition.notify is tracker.installed_notify + assert tracker.original_notify_all.__func__ is ClassCondition.notify_all + assert tracker.original_notify.__func__ is ClassCondition.notify + assert tracker.subscribers == {} def test_sleep_with_cancel_preserves_an_instance_condition_override( @@ -2469,7 +2513,9 @@ 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 + tracker = client_module._notify_trackers[condition] + assert tracker.saved_notify_all is notify_all + assert condition.notify_all is tracker.installed_notify_all def test_sleep_with_cancel_ignores_a_nested_marker_event( @@ -2487,7 +2533,8 @@ 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 True - assert "notify_all" not in vars(event.marker._cond) # type: ignore[attr-defined] + tracker = client_module._notify_trackers[event.marker._cond] + assert tracker.subscribers == {} def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( @@ -2548,8 +2595,9 @@ 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 + original_tracker = client_module._notify_trackers[original_condition] assert clock.delays == [] - assert "notify_all" not in vars(original_condition) + assert original_condition.notify_all is original_tracker.installed_notify_all assert "notify_all" not in vars(event.backing._cond) @@ -2580,47 +2628,67 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert "set" not in vars(event) -def test_sleep_with_cancel_supports_an_instance_wait_override( - monkeypatch: pytest.MonkeyPatch, -) -> None: - real_wait = client_module._wait_for_event - clock = Clock(monkeypatch) - monkeypatch.setattr(client_module, "_wait_for_event", real_wait) +def test_sleep_with_cancel_supports_an_instance_wait_override() -> None: + # A deadlocked inline wait must be terminable by the parent test. + code = """ +import sys +import threading - class NeverWaitEvent(threading.Event): - def wait(self, timeout: float | None = None) -> bool: - raise AssertionError("the SDK must not call the caller's wait() override") +sys.path.insert(0, sys.argv[1]) +from proofline import client - event = NeverWaitEvent() - ready = threading.Event() - failures: list[str] = [] - real_track = client_module._track_sync_cancel +clock = [100.0] +client.monotonic = lambda: clock[0] - def track(event_arg: Any, deadline: Any) -> None: - real_track(event_arg, deadline) - ready.set() - monkeypatch.setattr(client_module, "_track_sync_cancel", track) +class NeverWaitEvent(threading.Event): + def wait(self, timeout=None): + raise AssertionError("the SDK must not call the caller's wait() override") - 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 + +event = NeverWaitEvent() +ready = threading.Event() +failures = [] +real_track = client._track_sync_cancel + + +def track(event_arg, deadline): + real_track(event_arg, deadline) + ready.set() + + +client._track_sync_cancel = track + + +def signal(): + if not ready.wait(2.0): + failures.append("the cancellation observers were never installed") + clock[0] = 101.5 event.set() - clock.now = 102.0 + return + clock[0] = 100.5 + event.set() + clock[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 clock.delays == [] + +thread = threading.Thread(target=signal, daemon=True) +thread.start() +result = client._sleep_with_cancel(5, event, cutoff=101.0) +thread.join(2.0) +assert not thread.is_alive() +assert failures == [] +assert result is False +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 @@ -4416,8 +4484,8 @@ class ForeignWaiter: event._waiters.remove(foreign) # type: ignore[arg-type] -def test_condition_tracker_registration_waits_for_a_restoring_teardown() -> None: - # A stuck restore must not keep the parent pytest process alive. +def test_condition_tracker_registration_waits_for_a_held_notification_lock() -> None: + # A held tracker lock must not keep the parent pytest process alive. code = """ import sys import threading @@ -4428,48 +4496,67 @@ def test_condition_tracker_registration_waits_for_a_restoring_teardown() -> None 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() +real_lock = client._notify_lock +lock_held = threading.Event() +allow_lock = threading.Event() +register_attempted = threading.Event() + + +class ProbeLock: + def __enter__(self): + name = threading.current_thread().name + if name == "teardown": + real_lock.acquire() + lock_held.set() + assert allow_lock.wait(5.0) + return self + if name == "register": + register_attempted.set() + real_lock.acquire() + return self + + def __exit__(self, *exc): + real_lock.release() + return False + + def _is_owned(self): + return real_lock._is_owned() -def slow_restore(): - ready_to_restore.set() - if allow_restore.wait(5.0): - real_restore() -tracker.restore = slow_restore +client._notify_lock = ProbeLock() 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 = threading.Thread(target=teardown, name="teardown", daemon=True) +joiner = threading.Thread(target=register, name="register", daemon=True) leaver.start() -assert ready_to_restore.wait(2.0), "the old wrapper was never retired" +assert lock_held.wait(2.0), "teardown never held the tracker lock" 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" +assert register_attempted.wait(2.0), "registration never reached the lock" +assert not registered.is_set(), "registration skipped the held lock" +allow_lock.set() +assert registered.wait(2.0), "registration did not follow teardown" 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 +tracker = client._notify_trackers[condition] +assert set(tracker.subscribers) == {second} +assert condition.notify_all is tracker.installed_notify_all 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 +assert tracker.subscribers == {} print("OK") """ root = Path(__file__).resolve().parents[1] @@ -4483,7 +4570,7 @@ def register(): assert result.stdout.strip() == "OK" -def test_async_future_registration_waits_for_a_restoring_teardown() -> None: +def test_async_future_registration_waits_for_a_held_future_lock() -> None: code = """ import asyncio import sys @@ -4492,8 +4579,35 @@ def test_async_future_registration_waits_for_a_restoring_teardown() -> None: sys.path.insert(0, sys.argv[1]) from proofline import client -ready_to_restore = threading.Event() -allow_restore = threading.Event() +state = threading.local() +lock_held = threading.Event() +allow_lock = threading.Event() +register_attempted = threading.Event() +real_lock = client._async_future_lock + + +class ProbeLock: + def __enter__(self): + mode = getattr(state, "mode", None) + if mode == "teardown": + real_lock.acquire() + lock_held.set() + assert allow_lock.wait(5.0) + return self + if mode == "register": + register_attempted.set() + real_lock.acquire() + return self + + def __exit__(self, *exc): + real_lock.release() + return False + + def _is_owned(self): + return real_lock._is_owned() + + +client._async_future_lock = ProbeLock() async def main(): @@ -4502,48 +4616,38 @@ async def main(): 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 + registered = threading.Event() - def slow_restore(): - ready_to_restore.set() - if allow_restore.wait(5.0): - real_restore() + def teardown(): + state.mode = "teardown" + client._unwatch_async_future(future, first) - watch.restore = slow_restore - teardown = asyncio.create_task( - asyncio.to_thread(client._unwatch_async_future, future, first) - ) + def register(): + state.mode = "register" + client._watch_async_future(future, event, second) + registered.set() + + teardown_task = asyncio.create_task(asyncio.to_thread(teardown)) joiner = None try: - assert await asyncio.to_thread(ready_to_restore.wait, 5.0) - registered = threading.Event() - - def register(): - client._watch_async_future(future, event, second) - registered.set() - + assert await asyncio.to_thread(lock_held.wait, 5.0) 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, 2.0) + assert await asyncio.to_thread(register_attempted.wait, 5.0) + assert not registered.is_set(), "registration skipped the held lock" + allow_lock.set() + await asyncio.wait_for(teardown_task, 2.0) assert await asyncio.to_thread(registered.wait, 2.0) - assert await asyncio.wait_for(joiner, 2.0) is None + await asyncio.wait_for(joiner, 2.0) assert client._unwatch_async_future(future, second) is True finally: - allow_restore.set() - for task in (teardown, joiner): + allow_lock.set() + for task in (teardown_task, joiner): if task is not None: task.cancel() await asyncio.gather( - *(task for task in (teardown, joiner) if task is not None), + *(task for task in (teardown_task, joiner) if task is not None), return_exceptions=True, ) - try: - real_restore() - except Exception: - pass assert "set_result" not in getattr(future, "__dict__", {}) @@ -4580,7 +4684,7 @@ def __setattr__(self, name: str, value: Any) -> None: 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 + assert condition not in client_module._notify_trackers async def test_async_future_watch_stamps_one_notification_for_all_observers( @@ -4729,52 +4833,71 @@ def test_sleep_with_cancel_does_not_backdate_a_late_flag_from_an_unverified_wake monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) + real_track = client_module._track_sync_cancel + + class CheckpointCondition(threading.Condition): + def notify_all(self) -> None: + if not event.pulsed.is_set(): + event.pulsed.set() + assert event.proceed.wait(2.0), "the late checkpoint never arrived" + super().notify_all() class GatedEvent(threading.Event): def __init__(self) -> None: super().__init__() - self.hinted = threading.Event() - self.revealed = threading.Event() + self.revealed = False + self.installed = threading.Event() + self.pulsed = threading.Event() + self.proceed = threading.Event() + self._cond = CheckpointCondition(threading.Lock()) def is_set(self) -> bool: - return self.revealed.is_set() - - def set(self) -> None: - self.revealed.set() - self.hinted.set() + return self.revealed + + def pulse(self) -> None: + with self._cond: + self._flag = True + self._cond.notify_all() + self._flag = False + + def reveal_late(self) -> None: + self.revealed = True + self.proceed.set() + with self._cond: + self._flag = True + self._cond.notify_all() + self._flag = False event = GatedEvent() - ready = threading.Event() def track(event_arg: Any, deadline: Any) -> None: - client_module._track_thread_signal(event_arg, deadline) - ready.set() + real_track(event_arg, deadline) + event.installed.set() monkeypatch.setattr(client_module, "_track_sync_cancel", track) - def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: - assert ready.wait(2.0), "the cancellation observers were never installed" + def signal() -> None: + assert event.installed.wait(2.0), "cancellation was never observed" clock.now = 100.5 - wait_event.hinted.set() - assert wait_event.revealed.wait(2.0), "the late signal never arrived" - return False + event.pulse() - monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) - - def signal() -> None: - assert ready.wait(2.0) - while not event.hinted.wait(0.001): - pass + def late() -> None: + assert event.pulsed.wait(2.0), "the early wake never arrived" clock.now = 101.5 - event.revealed.set() + event.reveal_late() - thread = threading.Thread(target=signal, daemon=True) - thread.start() + early_thread = threading.Thread(target=signal, daemon=True) + late_thread = threading.Thread(target=late, daemon=True) + early_thread.start() + late_thread.start() try: assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True finally: - thread.join(2.0) - assert not thread.is_alive() + event.proceed.set() + early_thread.join(2.0) + late_thread.join(2.0) + assert not early_thread.is_alive() + assert not late_thread.is_alive() def test_async_waiter_registration_is_atomic_across_event_loops() -> None: @@ -4868,32 +4991,34 @@ def __exit__(self, *args: Any) -> bool: client_module._untrack_thread_signal(event, deadline) -def test_condition_tracker_restores_both_hooks_after_a_failure( +def test_condition_tracker_keeps_one_reusable_hook_after_teardown( monkeypatch: pytest.MonkeyPatch, ) -> None: event = threading.Event() 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 + first = client_module._SignalDeadline(time.monotonic() + 10.0) + second = client_module._SignalDeadline(time.monotonic() + 10.0) + attempts: list[tuple[Any, ...]] = [] - 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) + def forbid_restore(*args: Any) -> None: + attempts.append(args) + raise AssertionError("teardown must not unwind a caller-owned hook") - 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) + monkeypatch.setattr(client_module, "_restore_method", forbid_restore) + client_module._track_thread_signal(event, first) + tracker = client_module._notify_trackers[condition] + installed = tracker.installed_notify_all + try: + client_module._untrack_thread_signal(event, first) + client_module._track_thread_signal(event, second) + assert client_module._notify_trackers[condition] is tracker + assert condition.notify_all is installed + assert condition.notify is tracker.installed_notify + assert set(tracker.subscribers) == {second} + finally: + client_module._untrack_thread_signal(event, second) + assert tracker.subscribers == {} + assert attempts == [] async def test_async_event_set_publishes_once_for_all_watched_waiters( @@ -4929,12 +5054,14 @@ def counted(items: tuple[tuple[Any, ...], ...]) -> None: event._waiters.remove(future) except ValueError: pass - for deadline in deadlines: - client_module._unwatch_async_future(future, deadline) + for future, deadline in zip(futures, deadlines): + assert client_module._unwatch_async_future(future, deadline) is True + assert all(id(future) not in client_module._async_future_watches for future in futures) + assert all("set_result" not in getattr(future, "__dict__", {}) for future in futures) client_module._async_signal_watches.pop(id(event), None) -async def test_async_future_observer_stays_armed_after_an_unverified_wake( +async def test_async_future_observer_defers_an_unverified_wake( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) @@ -4948,23 +5075,31 @@ def is_set(self) -> bool: 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) + early = client_module._SignalDeadline(clock.now + 10.0) + waiter = client_module._watch_async_waiter(event, early) 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 + assert future.done() + assert early.signalled_at is None + finally: + client_module._unwatch_async_waiter(waiter, early) + + late = client_module._SignalDeadline(clock.now + 10.0) + fresh = client_module._watch_async_waiter(event, late) + try: event.clear() - clock.now = 100.2 event.gate = True + clock.now = 100.2 event.set() - assert future.done() - assert deadline.signalled_at == 100.2 + assert fresh.future is not None and fresh.future.done() + assert late.signalled_at is None + assert client_module._record_signal_before(event, late, late.end) is True + assert late.signalled_at == 100.2 finally: - client_module._unwatch_async_waiter(waiter, deadline) + client_module._unwatch_async_waiter(fresh, late) async def test_async_wait_for_review_checks_loop_ownership_under_lock( From bb817be9c5383a8f5de2f990e897d81090bcea2e Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sun, 29 Nov 2026 23:16:50 +0530 Subject: [PATCH 24/28] Address twenty-third Proofline review findings --- README.md | 2 +- proofline/client.py | 339 +++++++++++++++++++------- tests/test_http.py | 575 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 701 insertions(+), 215 deletions(-) diff --git a/README.md b/README.md index 6c425d0e..62f9fd9e 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -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()` while observation is active and before the deadline 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 binds the caller's async event to the wait's loop through native registration before attaching its waiter, releases that binding when its waiter is removed, and never assigns to the caller's `set()` attribute, so the same event may be reused on another loop after the SDK waiter is gone. An event already bound to a different loop, or carrying waiters from one, is 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. +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. A subclass whose `is_set()` forwards to the standard predicate is supported: native waiter delivery is latched directly, so a same-task `set()` followed by `clear()` is observed without the SDK calling that override. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter, releases that binding when its waiter is removed, and never assigns to the caller's `set()` attribute, so the same event may be reused on another loop after the SDK waiter is gone. An event already bound to a different loop, or carrying waiters from one, is 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 82eab71c..91385dcc 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -317,6 +317,115 @@ def _rollback_condition_hook( pass +class _WeakBoundMethod: + """A callable bound method that does not keep its owner alive.""" + + def __init__(self, owner_ref: Any, func: Any) -> None: + self._owner_ref = owner_ref + self.__func__ = func + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + owner = self._owner_ref() + if owner is None: + raise ReferenceError("the condition owned by this hook was collected") + return self.__func__(owner, *args, **kwargs) + + def __eq__(self, other: Any) -> bool: + owner = self._owner_ref() + return ( + owner is not None + and getattr(other, "__self__", None) is owner + and getattr(other, "__func__", None) is self.__func__ + ) + + def __hash__(self) -> int: + return hash((id(self._owner_ref()), self.__func__)) + + +def _weak_bound_method(value: Any) -> Any: + """Use a weak owner for bound methods, leaving other callables unchanged.""" + owner = getattr(value, "__self__", None) + func = getattr(value, "__func__", None) + if owner is None or func is None: + return value + try: + owner_ref = weak_ref(owner) + except TypeError: + return value + return _WeakBoundMethod(owner_ref, func) + + +def _restore_bound_method(value: Any) -> Any: + """Rebuild a bound method stored through a weak owner.""" + if not isinstance(value, _WeakBoundMethod): + return value + owner = value._owner_ref() + if owner is None: + return value.__func__ + return value.__func__.__get__(owner, type(owner)) + + +class _WeakTrackerRegistry: + """Map conditions to trackers without keeping either side alive.""" + + def __init__(self) -> None: + self._conditions: dict[int, Any] = {} + self._trackers: dict[int, Any] = {} + + def _discard(self, key: int, tracker_ref: Any = None) -> None: + if tracker_ref is None or self._trackers.get(key) is tracker_ref: + self._trackers.pop(key, None) + self._conditions.pop(key, None) + + def __setitem__(self, condition: threading.Condition, tracker: Any) -> None: + key = id(condition) + self._discard(key) + + def tracker_gone(tracker_ref: Any) -> None: + self._discard(key, tracker_ref) + + def condition_gone(_: Any) -> None: + self._discard(key) + + self._conditions[key] = weak_ref(condition, condition_gone) + self._trackers[key] = weak_ref(tracker, tracker_gone) + + def get(self, condition: threading.Condition) -> Any | None: + key = id(condition) + condition_ref = self._conditions.get(key) + tracker_ref = self._trackers.get(key) + if condition_ref is None or tracker_ref is None: + return None + tracker = tracker_ref() + if tracker is None or condition_ref() is not condition: + self._discard(key) + return None + return tracker + + def __getitem__(self, condition: threading.Condition) -> Any: + tracker = self.get(condition) + if tracker is None: + raise KeyError(condition) + return tracker + + def __contains__(self, condition: object) -> bool: + return isinstance(condition, threading.Condition) and self.get(condition) is not None + + def __delitem__(self, condition: threading.Condition) -> None: + self._discard(id(condition)) + + def values(self) -> tuple[Any, ...]: + live: list[Any] = [] + for key, tracker_ref in tuple(self._trackers.items()): + condition_ref = self._conditions.get(key) + tracker = tracker_ref() + if tracker is None or condition_ref is None or condition_ref() is None: + self._discard(key) + continue + live.append(tracker) + return tuple(live) + + class _ConditionSignalTracker: """Watch one condition, preserving whether overrides were instance attributes.""" @@ -327,12 +436,16 @@ def __init__(self, condition: threading.Condition) -> None: 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.original_notify_all = _weak_bound_method(condition.notify_all) + self.original_notify = _weak_bound_method(condition.notify) # (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() + # Condition.notify_all() delegates to notify(); publish only once for + # the outer dispatch so a subscriber added while an override delegates + # cannot consume a notification that began before it subscribed. + self._dispatching = False self.installed_notify_all = self.notify_all self.installed_notify = self.notify try: @@ -372,13 +485,21 @@ def record(self) -> None: _stage_signals(tuple(staged)) _drain_signals() + def _dispatch(self, original: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + if self._dispatching: + return original(*args, **kwargs) + self._dispatching = True + try: + self.record() + return original(*args, **kwargs) + finally: + self._dispatching = False + def notify_all(self) -> None: - self.record() - self.original_notify_all() + self._dispatch(self.original_notify_all) def notify(self, *args: Any, **kwargs: Any) -> None: - self.record() - self.original_notify(*args, **kwargs) + self._dispatch(self.original_notify, *args, **kwargs) def restore(self) -> None: # Retained for explicit cleanup; teardown never unwraps caller hooks. @@ -392,7 +513,9 @@ def restore(self) -> None: ("notify", self.had_notify, self.saved_notify, self.installed_notify), ): try: - _restore_method(condition, name, had_instance, saved, installed) + _restore_method( + condition, name, had_instance, _restore_bound_method(saved), installed + ) except Exception as exc: if error is None: error = exc @@ -400,9 +523,7 @@ def restore(self) -> None: raise error -_notify_trackers: WeakKeyDictionary[threading.Condition, _ConditionSignalTracker] = ( - WeakKeyDictionary() -) +_notify_trackers = _WeakTrackerRegistry() def _discover_thread_conditions( @@ -476,8 +597,11 @@ def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> t override that acquires the same non-reentrant lock cannot deadlock setup. """ conditions = tuple(item[0] for item in _discover_thread_conditions(event)) + # Mutually linked events expose the same conditions in opposite order. A + # single identity order prevents two setup threads from acquiring them in + # opposite directions and deadlocking before any wait deadline applies. with ExitStack() as stack: - for condition in conditions: + for condition in sorted(conditions, key=id): stack.enter_context(condition) _track_sync_cancel(event, deadline) sampled = monotonic() @@ -501,6 +625,8 @@ 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.""" + if event is None: + return False _drain_signals() if deadline.signalled_at is not None: return True @@ -595,14 +721,6 @@ def _async_flag_is_set(event: AsyncEvent) -> bool: return bool(getattr(event, "_value", getattr(event, "_flag", False))) -def _standard_async_is_set(event: AsyncEvent) -> bool: - """Whether the predicate is the standard Event.is_set(), without an override.""" - method = getattr(event, "is_set", None) - return getattr(method, "__func__", None) is asyncio.Event.is_set and ( - getattr(method, "__self__", None) is event - ) - - def _check_async_event_loop(event: asyncio.Event) -> None: """Bind ownership with native registration before scanning waiters. @@ -688,12 +806,9 @@ def set_result(result: Any) -> None: if not _async_flag_is_set(event): return if not self.signal.dispatch_done: - if _standard_async_is_set(event): - self.signal.note(monotonic()) - else: - # An overridden predicate is verified later by the waiter, - # outside the setter; this only wakes it for that check. - self.signal.defer(monotonic()) + # Native delivery on this event proves the signal regardless of + # an is_set() override; the raw flag was checked by the caller. + self.signal.note(monotonic()) self.original(result) self.installed = set_result @@ -767,48 +882,94 @@ def _unwatch_async_future(future: AsyncFuture[Any], deadline: _SignalDeadline) - return last +class _AsyncLoopBinding: + """SDK ownership of a native event binding, shared by every SDK waiter.""" + + def __init__(self, loop: Any, owned: bool) -> None: + self.loop = loop + self.owned = owned + self.count = 0 + + +_async_loop_bindings: WeakKeyDictionary[AsyncEvent, _AsyncLoopBinding] = WeakKeyDictionary() + + class _AsyncSignalWaiter: """A future registered directly on the event, without driving overrides.""" def __init__(self) -> None: self.event: AsyncEvent | None = None self.future: AsyncFuture[Any] | None = None - self.bound_loop: Any | None = None - self.unbind_loop = False + self.binding: _AsyncLoopBinding | None = None + + +def _release_async_binding(waiter: _AsyncSignalWaiter) -> None: + """Release one SDK waiter, clearing a temporary binding when the last leaves.""" + binding = waiter.binding + event = waiter.event + waiter.binding = None + if binding is None or event is None: + return + binding.count -= 1 + if binding.count > 0: + return + if _async_loop_bindings.get(event) is binding: + del _async_loop_bindings[event] + waiters = getattr(event, "_waiters", None) + if binding.owned and not waiters and getattr(event, "_loop", None) is binding.loop: + event._loop = None # type: ignore[attr-defined] def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: - """Observe a signal with native loop ownership until this waiter leaves.""" + """Observe a signal with native loop ownership shared by all SDK waiters.""" waiter = _AsyncSignalWaiter() if not isinstance(event, asyncio.Event): return waiter with _async_future_lock: + binding = _async_loop_bindings.get(event) previous_loop = getattr(event, "_loop", None) _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) + if binding is None: + binding = _AsyncLoopBinding( + loop, previous_loop is None and getattr(event, "_loop", None) is loop + ) + _async_loop_bindings[event] = binding + elif binding.loop is not loop: + # A native check may have rebound a temporarily cleared event to + # this loop; undo that before rejecting the foreign registration. + if previous_loop is None and getattr(event, "_loop", None) is loop: + event._loop = None # type: ignore[attr-defined] + raise RuntimeError("cancel_event is already bound to a different event loop.") + binding.count += 1 waiter.event = event - waiter.future = future - waiter.bound_loop = loop - waiter.unbind_loop = previous_loop is None + waiter.binding = binding try: - _watch_async_future(future, event, deadline) + waiters = getattr(event, "_waiters", None) + if waiters is None: + waiters = deque() + event._waiters = waiters + created_future: AsyncFuture[Any] = loop.create_future() + waiters.append(created_future) + waiter.future = created_future + _watch_async_future(created_future, event, deadline) except BaseException: - try: - waiters.remove(future) - except ValueError: - pass - future.cancel() + future = waiter.future + if future is not None: + try: + _unwatch_async_future(future, deadline) + except Exception: + pass + waiters = getattr(event, "_waiters", None) + if waiters is not None: + try: + waiters.remove(future) + except ValueError: + pass + future.cancel() + _release_async_binding(waiter) waiter.event = None waiter.future = None - if waiter.unbind_loop and getattr(event, "_loop", None) is loop: - event._loop = None # type: ignore[attr-defined] - waiter.unbind_loop = False raise return waiter @@ -829,15 +990,18 @@ def _unwatch_async_waiter(waiter: _AsyncSignalWaiter, deadline: _SignalDeadline) waiters.remove(future) except ValueError: pass - if ( - waiter.unbind_loop - and not waiters - and getattr(event, "_loop", None) is waiter.bound_loop - ): - event._loop = None # type: ignore[attr-defined] - waiter.unbind_loop = False if not future.done(): future.cancel() + _release_async_binding(waiter) + waiter.event = None + waiter.future = None + + +def _schedule_cutoff_timer( + loop: Any, when: float, callback: Any, args: tuple[Any, ...], *, deadline: float +) -> Any: + """Schedule one helper cutoff, with its absolute deadline visible to tests.""" + return loop.call_at(when, callback, *args) async def _async_wait_for_event( @@ -850,7 +1014,13 @@ async def _async_wait_for_event( return False 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) + handle = _schedule_cutoff_timer( + loop, + loop.time() + max(0.0, cutoff - monotonic()), + timer.set_result, + (None,), + deadline=cutoff, + ) waiter = _AsyncSignalWaiter() try: waiter = _watch_async_waiter(event, deadline) @@ -1302,18 +1472,19 @@ def wait_for_review( another head ends the wait on that read and is never COMPLETED. 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 timeout - clock starts after validation and URL construction; a cancellable wait - samples its entry deadline before validation and applies that deadline - to notifications observed during setup. A signal first delivered at or - after the deadline is ignored; it does not change the wait's result, - override a head mismatch, or suppress a read error that would otherwise - propagate. + when ``timeout`` is zero. 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. A cancellable wait samples its deadline before validation, so + validation and URL construction count toward the polling budget and can + exhaust it without a request; notifications observed during setup use + that same deadline. Without a cancellation event, validation and URL + construction happen before the timeout clock starts. A signal first + delivered at or after the deadline 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 a condition reachable from the event passed here. Call ``set()`` on that event. The SDK never assigns to its ``set()`` @@ -1330,7 +1501,6 @@ def wait_for_review( raise ValueError("The review timeout must be a finite nonnegative number of seconds.") 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) read_signal = _SignalDeadline(float("inf")) initially_set = False deadline_set = False @@ -1339,10 +1509,11 @@ def wait_for_review( initially_set, sampled = _initial_sync_signal(cancel_event, read_signal) deadline_at = sampled + timeout read_signal.cap(deadline_at) + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) else: - deadline_at = 0.0 - _head_commit(head_commit_sha) - if cancel_event is None: + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) deadline_at = monotonic() + timeout if initially_set: return _stopped(url, None, review_id, head_commit_sha) @@ -1752,15 +1923,17 @@ async def wait_for_review( """Wait for recorded review completion or return TIMED_OUT. 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 timeout clock starts after validation and - URL construction; a cancellable wait samples its entry deadline before - validation and applies that deadline to signals observed during setup. A - signal first delivered at or after the deadline 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 + when ``timeout`` is zero. 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. A cancellable wait + samples its deadline before validation, so validation and URL + construction count toward the polling budget and can exhaust it without + a request; notifications observed during setup use that same deadline. + Without a cancellation event, validation and URL construction happen + before the timeout clock starts. A signal first delivered at or after + the deadline 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. Native @@ -1774,7 +1947,6 @@ async def wait_for_review( raise ValueError("The review timeout must be a finite nonnegative number of seconds.") 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) read_signal = _SignalDeadline(float("inf")) read_waiter = _AsyncSignalWaiter() initially_set = False @@ -1786,10 +1958,11 @@ async def wait_for_review( sampled = monotonic() deadline_at = sampled + timeout read_signal.cap(deadline_at) + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) else: - deadline_at = 0.0 - _head_commit(head_commit_sha) - if cancel_event is None: + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) deadline_at = monotonic() + timeout if initially_set: return _stopped(url, None, review_id, head_commit_sha) diff --git a/tests/test_http.py b/tests/test_http.py index e2e0c592..7c6fb9b2 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2,6 +2,7 @@ import asyncio import csv +import gc import gzip import inspect import io @@ -14,6 +15,7 @@ import time import tomllib import traceback +import weakref from collections.abc import AsyncIterator from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta @@ -149,29 +151,21 @@ def cancel(self) -> None: def patch_helper_timer( monkeypatch: pytest.MonkeyPatch, loop: Any, deadlines: tuple[float, ...] = () ) -> list[ManualTimer]: - """Control named helper cutoffs without capturing loop watchdogs.""" + """Control named helper cutoffs through the helper's explicit schedule hook.""" timers: list[ManualTimer] = [] - real_call_at = loop.call_at - real_loop_time = loop.time - - def call_at(when: float, callback: Any, *args: Any, **kwargs: Any) -> Any: - owner = getattr(callback, "__self__", None) - if ( - getattr(callback, "__name__", None) == "set_result" - and isinstance(owner, asyncio.Future) - and args == (None,) - and not owner.done() - ): - actual_delay = when - real_loop_time() - for deadline in deadlines: - expected_delay = max(0.0, deadline - client_module.monotonic()) - if abs(actual_delay - expected_delay) < 1e-6: - timer = ManualTimer(callback, args, kwargs, deadline) - timers.append(timer) - return timer - return real_call_at(when, callback, *args, **kwargs) - - monkeypatch.setattr(loop, "call_at", call_at) + real_schedule = client_module._schedule_cutoff_timer + + def schedule( + hooked_loop: Any, _when: float, callback: Any, args: tuple[Any, ...], *, deadline: float + ) -> Any: + assert hooked_loop is loop + if deadline in deadlines: + timer = ManualTimer(callback, args, None, deadline) + timers.append(timer) + return timer + return real_schedule(loop, _when, callback, args, deadline=deadline) + + monkeypatch.setattr(client_module, "_schedule_cutoff_timer", schedule) return timers @@ -179,6 +173,8 @@ class Clock: def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 self.delays: list[float] = [] + self.publication = threading.Event() + self.deadline_reached = threading.Event() monkeypatch.setattr(client_module, "monotonic", lambda: self.now) monkeypatch.setattr(_transport, "monotonic", lambda: self.now) monkeypatch.setattr(_sync_http, "monotonic", lambda: self.now) @@ -189,6 +185,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 publish(self) -> None: + """Mark a cancellation as explicitly published at the current fake time.""" + self.publication.set() + + def reach_deadline(self) -> None: + """Explicitly authorize the fake async wait to advance to its deadline.""" + self.deadline_reached.set() + 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: @@ -201,26 +205,28 @@ def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None woke = True return woke + def _record_async_arrival(self, event: Any, deadline: float, signal: Any | None) -> bool: + if not event.is_set() or self.now >= deadline: + return False + if signal is not None: + signal.record(self.now) + return True + async def async_wait_for_event( self, event: Any, cutoff: float, signal: Any | None = None ) -> bool: - 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 - publication_deadline = signal.end if signal is not None else cutoff - if arrived_at is not None and arrived_at < publication_deadline: - if signal is not None: - signal.record(arrived_at) + deadline = signal.end if signal is not None else cutoff + if self.publication.is_set(): + self.publication.clear() + if self._record_async_arrival(event, deadline, signal): + return True + if self._record_async_arrival(event, deadline, signal): return True - return False + if not self.deadline_reached.is_set(): + raise AssertionError("advance the fake async deadline explicitly") + self.deadline_reached.clear() + self.sleep(max(0.0, deadline - self.now)) + return self._record_async_arrival(event, deadline, signal) def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -3057,10 +3063,17 @@ async def get_review(*args: Any, **kwargs: Any) -> Any: async def test_wait_for_review_cancel_event_during_erroring_read_keeps_last_record( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: - Clock(monkeypatch) + 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 == "async": + + async def skip_backoff(wait_event: Any, cutoff: float, signal: Any | None = None) -> bool: + clock.sleep(max(0.0, cutoff - clock.now)) + return False + + monkeypatch.setattr(client_module, "_async_wait_for_event", skip_backoff) with Server(lambda request, index: Reply(body=body)) as server: async with session(mode, server.url) as client: real_get_review = client.get_review @@ -3169,6 +3182,9 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) nonlocal calls calls += 1 assert calls == 1, "the backoff should not poll again after the signal" + assert timeout == pytest.approx(5.0) + assert deadline is not None + assert deadline.end == pytest.approx(clock.now + 100.0) clock.now = 105.0 wait_event.set() wait_event.clear() @@ -3184,6 +3200,9 @@ async def async_wait_for_event( nonlocal calls calls += 1 assert calls == 1, "the backoff should not poll again after the signal" + assert cutoff == pytest.approx(clock.now + 5.0) + assert signal is not None + assert signal.end == pytest.approx(clock.now + 100.0) clock.now = 105.0 wait_event.set() wait_event.clear() @@ -4829,116 +4848,185 @@ def test_condition_tracker_stamps_a_standard_event_once_for_all_deadlines( client_module._untrack_thread_signal(event, second) -def test_sleep_with_cancel_does_not_backdate_a_late_flag_from_an_unverified_wake( - monkeypatch: pytest.MonkeyPatch, -) -> None: - clock = Clock(monkeypatch) - real_track = client_module._track_sync_cancel +def test_sleep_with_cancel_does_not_backdate_a_late_flag_from_an_unverified_wake() -> None: + # A stalled notifier must not hang pytest; the whole probe is bounded. + code = """ +import sys +import threading - class CheckpointCondition(threading.Condition): - def notify_all(self) -> None: - if not event.pulsed.is_set(): - event.pulsed.set() - assert event.proceed.wait(2.0), "the late checkpoint never arrived" - super().notify_all() +sys.path.insert(0, sys.argv[1]) +from proofline import client - class GatedEvent(threading.Event): - def __init__(self) -> None: - super().__init__() - self.revealed = False - self.installed = threading.Event() - self.pulsed = threading.Event() - self.proceed = threading.Event() - self._cond = CheckpointCondition(threading.Lock()) +now = [100.0] +client.monotonic = lambda: now[0] +real_track = client._track_sync_cancel - def is_set(self) -> bool: - return self.revealed - def pulse(self) -> None: - with self._cond: - self._flag = True - self._cond.notify_all() - self._flag = False +class CheckpointCondition(threading.Condition): + def notify_all(self): + if not event.pulsed.is_set(): + event.pulsed.set() + assert event.proceed.wait(5.0), "the late checkpoint never arrived" + super().notify_all() - def reveal_late(self) -> None: - self.revealed = True - self.proceed.set() - with self._cond: - self._flag = True - self._cond.notify_all() - self._flag = False - event = GatedEvent() +class GatedEvent(threading.Event): + def __init__(self): + super().__init__() + self.revealed = False + self.installed = threading.Event() + self.pulsed = threading.Event() + self.proceed = threading.Event() + self._cond = CheckpointCondition(threading.Lock()) - def track(event_arg: Any, deadline: Any) -> None: - real_track(event_arg, deadline) - event.installed.set() + def is_set(self): + return self.revealed - monkeypatch.setattr(client_module, "_track_sync_cancel", track) + def pulse(self): + with self._cond: + self._flag = True + self._cond.notify_all() + self._flag = False - def signal() -> None: - assert event.installed.wait(2.0), "cancellation was never observed" - clock.now = 100.5 - event.pulse() + def reveal_late(self): + self.revealed = True + self.proceed.set() + with self._cond: + self._flag = True + self._cond.notify_all() + self._flag = False - def late() -> None: - assert event.pulsed.wait(2.0), "the early wake never arrived" - clock.now = 101.5 - event.reveal_late() - early_thread = threading.Thread(target=signal, daemon=True) - late_thread = threading.Thread(target=late, daemon=True) - early_thread.start() - late_thread.start() - try: - assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is True - finally: - event.proceed.set() - early_thread.join(2.0) - late_thread.join(2.0) - assert not early_thread.is_alive() - assert not late_thread.is_alive() +event = GatedEvent() + + +def track(event_arg, deadline): + real_track(event_arg, deadline) + event.installed.set() + + +client._track_sync_cancel = track + + +def signal(): + assert event.installed.wait(5.0), "cancellation was never observed" + now[0] = 100.5 + event.pulse() + + +def late(): + assert event.pulsed.wait(5.0), "the early wake never arrived" + now[0] = 101.5 + event.reveal_late() + + +early_thread = threading.Thread(target=signal, daemon=True) +late_thread = threading.Thread(target=late, daemon=True) +early_thread.start() +late_thread.start() +try: + assert client._sleep_with_cancel(5, event, cutoff=101.0) is True +finally: + event.proceed.set() + early_thread.join(5.0) + late_thread.join(5.0) +assert not early_thread.is_alive() +assert not late_thread.is_alive() +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_waiter_registration_is_atomic_across_event_loops() -> None: - # Competing loops must not leave half-registered waiters behind on failure. + # The competing registration must try the lock while the first is paused + # inside its critical section, so native ownership alone cannot satisfy it. code = """ import asyncio import sys import threading +import time sys.path.insert(0, sys.argv[1]) from proofline import client event = asyncio.Event() results = [] -attempted = threading.Event() +registered = threading.Event() release = threading.Event() +second_done = threading.Event() +attempts = [] +real_lock = client._async_future_lock +real_watch_future = client._watch_async_future + + +class InstrumentedLock: + def __enter__(self): + attempts.append(threading.get_ident()) + return real_lock.__enter__() + + def __exit__(self, *args): + return real_lock.__exit__(*args) + + +client._async_future_lock = InstrumentedLock() + + +def paused_registration(*args, **kwargs): + result = real_watch_future(*args, **kwargs) + registered.set() + assert release.wait(5.0), "the first registration was never released" + return result + + +client._watch_async_future = paused_registration + def run(): async def main(): - deadline = client._SignalDeadline(__import__("time").monotonic() + 10.0) + deadline = client._SignalDeadline(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) + assert second_done.wait(5.0) client._unwatch_async_waiter(waiter, deadline) except RuntimeError: results.append("rejected") + second_done.set() finally: - attempted.set() + registered.set() release.set() + second_done.set() + asyncio.run(main()) + threads = [threading.Thread(target=run, daemon=True) for _ in range(2)] for thread in threads: thread.start() +assert registered.wait(5.0), "the first registration never started" +second_ident = threads[1].ident +for _ in range(500): + if second_ident in attempts: + break + time.sleep(0.01) +else: + raise AssertionError("the second registration did not attempt the lock") +assert not release.is_set(), "the first registration resumed before the lock attempt" +release.set() 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 event not in client._async_loop_bindings assert id(event) not in client._async_signal_watches print("OK") """ @@ -5061,45 +5149,28 @@ def counted(items: tuple[tuple[Any, ...], ...]) -> None: client_module._async_signal_watches.pop(id(event), None) -async def test_async_future_observer_defers_an_unverified_wake( +async def test_async_future_observer_latches_a_forwarding_is_set_override( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) - class GatedEvent(asyncio.Event): - def __init__(self) -> None: - super().__init__() - self.gate = False - + class ForwardingEvent(asyncio.Event): def is_set(self) -> bool: - return self.gate and super().is_set() + return super().is_set() - event = GatedEvent() - early = client_module._SignalDeadline(clock.now + 10.0) - waiter = client_module._watch_async_waiter(event, early) - future = waiter.future - assert future is not None + event = ForwardingEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + assert waiter.future is not None try: clock.now = 100.1 event.set() - assert future.done() - assert early.signalled_at is None - finally: - client_module._unwatch_async_waiter(waiter, early) - - late = client_module._SignalDeadline(clock.now + 10.0) - fresh = client_module._watch_async_waiter(event, late) - try: event.clear() - event.gate = True - clock.now = 100.2 - event.set() - assert fresh.future is not None and fresh.future.done() - assert late.signalled_at is None - assert client_module._record_signal_before(event, late, late.end) is True - assert late.signalled_at == 100.2 + assert waiter.future.done() + assert not event.is_set() + assert deadline.signalled_at == 100.1 finally: - client_module._unwatch_async_waiter(fresh, late) + client_module._unwatch_async_waiter(waiter, deadline) async def test_async_wait_for_review_checks_loop_ownership_under_lock( @@ -5188,3 +5259,245 @@ async def test_wait_for_review_timeout_zero_honors_an_event_set_at_entry(mode: s assert server.requests == [] assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." + + +def test_condition_tracker_registry_does_not_retain_discarded_events() -> None: + event = threading.Event() + deadline = client_module._SignalDeadline(101.0) + client_module._track_thread_signal(event, deadline) + condition = event._cond + tracker = client_module._notify_trackers[condition] + condition_ref = weakref.ref(condition) + tracker_ref = weakref.ref(tracker) + client_module._untrack_thread_signal(event, deadline) + del tracker, condition, deadline, event + gc.collect() + assert condition_ref() is None + assert tracker_ref() is None + + +def test_condition_tracker_publishes_once_per_dispatch(monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + early = client_module._SignalDeadline(clock.now + 10.0) + late = client_module._SignalDeadline(clock.now + 10.0) + + class InterleavingCondition(threading.Condition): + def notify_all(self) -> None: + client_module._track_thread_signal(event, late) + super().notify_all() + + event = threading.Event() + event._cond = InterleavingCondition(threading.Lock()) + client_module._track_thread_signal(event, early) + try: + event.set() + assert early.signalled_at == clock.now + assert late.signalled_at is None + finally: + client_module._untrack_thread_signal(event, early) + client_module._untrack_thread_signal(event, late) + + +def test_initial_sync_signal_orders_linked_condition_locks() -> None: + # Two events that reference each other expose the same locks in opposite + # order; a regression must be caught by the subprocess watchdog. + code = """ +import sys +import threading +import time + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +first = threading.Event() +second = threading.Event() +first.other = second +second.other = first +barrier = threading.Barrier(2) +errors = [] + + +def run(event): + try: + barrier.wait(5.0) + deadline = client._SignalDeadline(time.monotonic() + 5.0) + client._initial_sync_signal(event, deadline) + client._untrack_sync_cancel(event, deadline) + except BaseException as error: + errors.append(repr(error)) + + +threads = [threading.Thread(target=run, args=(event,), daemon=True) for event in (first, second)] +for thread in threads: + thread.start() +for thread in threads: + thread.join(5.0) +assert not any(thread.is_alive() for thread in threads), "linked setup deadlocked" +assert errors == [], errors +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_waiter_releases_a_shared_loop_binding_with_its_last_waiter() -> None: + event = asyncio.Event() + + def overlapping_waits() -> None: + async def main() -> None: + loop = asyncio.get_running_loop() + end = loop.time() + 10.0 + first = client_module._SignalDeadline(end) + second = client_module._SignalDeadline(end) + first_waiter = client_module._watch_async_waiter(event, first) + second_waiter = client_module._watch_async_waiter(event, second) + assert event._loop is loop + assert len(event._waiters) == 2 + client_module._unwatch_async_waiter(first_waiter, first) + assert event._loop is loop + assert len(event._waiters) == 1 + assert event in client_module._async_loop_bindings + client_module._unwatch_async_waiter(second_waiter, second) + assert event._loop is None + assert not event._waiters + assert event not in client_module._async_loop_bindings + + asyncio.run(main()) + + def reuse_on_another_loop() -> None: + async def main() -> None: + loop = asyncio.get_running_loop() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + try: + assert event._loop is loop + finally: + client_module._unwatch_async_waiter(waiter, deadline) + + asyncio.run(main()) + + overlapping_waits() + reuse_on_another_loop() + assert event._loop is None + + +async def test_async_waiter_setup_failure_releases_the_loop_binding( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = asyncio.Event() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + + def fail(*args: Any, **kwargs: Any) -> None: + raise RuntimeError("future hook failed") + + monkeypatch.setattr(client_module, "_watch_async_future", fail) + with pytest.raises(RuntimeError, match="future hook failed"): + client_module._watch_async_waiter(event, deadline) + assert event._loop is None + assert not event._waiters + assert event not in client_module._async_loop_bindings + + +def test_record_signal_before_skips_drain_without_an_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail() -> None: + raise AssertionError("no pending signal may be drained without an event") + + monkeypatch.setattr(client_module, "_drain_signals", fail) + deadline = client_module._SignalDeadline(101.0) + assert client_module._record_signal_before(None, deadline, deadline.end) is False + + +@MODES +async def test_wait_for_review_validates_head_before_building_the_url( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + + def fail_url(*args: Any, **kwargs: Any) -> str: + raise RuntimeError("URL construction failed") + + monkeypatch.setattr(client_module, "_review_url", fail_url) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError, match="head commit"): + await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + head_commit_sha="not-a-sha", + ) + assert server.requests == [] + + +@MODES +async def test_wait_for_review_counts_validation_toward_the_cancellable_budget( + 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 slow_head(value: str | None) -> None: + clock.sleep(5.0) + real_head(value) + + monkeypatch.setattr(client_module, "_head_commit", slow_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=5, cancel_event=event + ) + assert server.requests == [] + assert result.status == "TIMED_OUT" + assert clock.delays == [5.0] + + +@MODES +async def test_wait_for_review_without_an_event_starts_the_budget_after_validation( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + real_head = client_module._head_commit + + def slow_head(value: str | None) -> None: + clock.sleep(5.0) + real_head(value) + + monkeypatch.setattr(client_module, "_head_commit", slow_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=5) + assert len(server.requests) == 1 + assert result.status == "TIMED_OUT" + assert clock.delays == [5.0, 5.0] + + +async def test_clock_async_wait_uses_an_explicit_deadline_gate( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + with pytest.raises(AssertionError, match="explicitly"): + await clock.async_wait_for_event(event, clock.now + 10.0) + assert clock.delays == [] + clock.reach_deadline() + assert await clock.async_wait_for_event(event, clock.now + 10.0) is False + assert clock.delays == [10.0] + + clock.now = 100.1 + event.set() + clock.publish() + signal = client_module._SignalDeadline(clock.now + 10.0) + assert await clock.async_wait_for_event(event, signal.end, signal) is True + assert signal.signalled_at == 100.1 From 6590fa7d9e3bf31ea38f655e7cf5067accda80f1 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Sun, 29 Nov 2026 23:47:04 +0530 Subject: [PATCH 25/28] Address twenty-fifth Proofline review findings --- README.md | 4 +- proofline/client.py | 248 ++++++++++++++++++++++++++++------- tests/test_http.py | 306 ++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 488 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 62f9fd9e..e9b11b56 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. 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. +`head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. Argument validation comes first: an already set `cancel_event` returns `STOPPED` only after validation succeeds. 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 @@ -102,7 +102,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. A subclass whose `is_set()` forwards to the standard predicate is supported: native waiter delivery is latched directly, so a same-task `set()` followed by `clear()` is observed without the SDK calling that override. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter, releases that binding when its waiter is removed, and never assigns to the caller's `set()` attribute, so the same event may be reused on another loop after the SDK waiter is gone. An event already bound to a different loop, or carrying waiters from one, is 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. +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` forwards to the standard predicate are supported for both event types: native delivery is latched directly from the event's own flag, so a timely `set()` followed by `clear()` is observed without the SDK calling that override. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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 91385dcc..2d64f6ea 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -20,7 +20,6 @@ from typing import Any, Self, TypedDict, TypeVar, Unpack, cast from urllib.parse import quote from uuid import UUID -from weakref import WeakKeyDictionary from weakref import ref as weak_ref import httpx2 @@ -289,12 +288,31 @@ def _event_attributes_snapshot(value: Any) -> tuple[Any, ...]: 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 _event_has_standard_predicate(value: Any) -> bool: + """Whether the instance uses the standard predicate, without invoking descriptors.""" + if "is_set" in _instance_attributes(value): + return False + for cls in type(value).__mro__: + if "is_set" in cls.__dict__: + return cls.__dict__["is_set"] is threading.Event.is_set + return False + + +def _thread_predicate_for_notification(value: Any) -> Callable[[], bool] | None: + """Resolve a callable predicate without invoking a property descriptor.""" + attributes = _instance_attributes(value) + if "is_set" in attributes: + candidate = attributes["is_set"] + if callable(candidate) and not isinstance(candidate, property): + return lambda: bool(candidate()) + return None + for cls in type(value).__mro__: + if "is_set" in cls.__dict__: + raw = cls.__dict__["is_set"] + if isinstance(raw, property) or not callable(raw): + return None + return lambda: bool(raw(value)) + return None def _restore_method(target: Any, name: str, had_instance: bool, saved: Any, installed: Any) -> None: @@ -468,6 +486,52 @@ def __init__(self, condition: threading.Condition) -> None: ) raise + def _hooks_installed(self) -> bool: + condition = self.condition_ref() + return condition is not None and ( + getattr(condition, "notify_all", None) is self.installed_notify_all + and getattr(condition, "notify", None) is self.installed_notify + ) + + def _rehook(self) -> None: + """Wrap the current methods when a caller has replaced either hook.""" + condition = self.condition_ref() + if condition is None: + return + attributes = _instance_attributes(condition) + changed: list[tuple[str, bool, Any, Any]] = [] + try: + for name, original_name, had_name, saved_name, installed in ( + ( + "notify_all", + "original_notify_all", + "had_notify_all", + "saved_notify_all", + self.installed_notify_all, + ), + ( + "notify", + "original_notify", + "had_notify", + "saved_notify", + self.installed_notify, + ), + ): + if getattr(condition, name, None) is installed: + continue + had_instance = name in attributes + saved = attributes.get(name) + method = getattr(condition, name) + setattr(self, had_name, had_instance) + setattr(self, saved_name, saved) + setattr(self, original_name, _weak_bound_method(method)) + setattr(condition, name, installed) + changed.append((name, had_instance, saved, installed)) + except BaseException: + for name, had_instance, saved, installed in changed: + _rollback_condition_hook(condition, name, had_instance, saved, installed) + raise + def record(self) -> None: # Sample and stage before contending for the deadline decision lock, so # a paused notifier cannot hide a timely signal from the final check. @@ -480,7 +544,10 @@ def record(self) -> None: for deadline, (watched, backing, caller) in subscribers: if not bool(getattr(watched, "_flag", False)): continue - verified = not backing and watched is caller and _standard_thread_is_set(caller) + verified = not backing and watched is caller + if verified: + predicate = _thread_predicate_for_notification(caller) + verified = predicate is not None and bool(predicate()) staged.append((deadline, now, verified)) _stage_signals(tuple(staged)) _drain_signals() @@ -563,6 +630,8 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ if tracker is None: tracker = _ConditionSignalTracker(tracked) _notify_trackers[tracked] = tracker + elif not tracker._hooks_installed(): + tracker._rehook() with tracker._subscription_lock: tracker.subscribers[deadline] = (watched_event, backing, event) return deadline @@ -590,23 +659,35 @@ def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> Non _track_thread_signal(event, deadline) +def _ordered_condition_locks( + conditions: tuple[threading.Condition, ...], +) -> tuple[Any, ...]: + """Dedupe shared locks and return one stable acquisition order.""" + locks: dict[int, Any] = {} + for condition in conditions: + lock = getattr(condition, "_lock", condition) + locks.setdefault(id(lock), lock) + return tuple(sorted(locks.values(), key=id)) + + def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> tuple[bool, float]: """Install observers and sample the entry flag under the condition locks. - The caller's predicate is read only after those locks are released, so an - override that acquires the same non-reentrant lock cannot deadlock setup. + Every distinct underlying lock is acquired once in identity order, so linked + conditions and conditions sharing one non-reentrant lock cannot deadlock + setup. An overridden predicate is read only after those locks are released. """ conditions = tuple(item[0] for item in _discover_thread_conditions(event)) - # Mutually linked events expose the same conditions in opposite order. A - # single identity order prevents two setup threads from acquiring them in - # opposite directions and deadlocking before any wait deadline applies. + standard_predicate = _event_has_standard_predicate(event) with ExitStack() as stack: - for condition in sorted(conditions, key=id): - stack.enter_context(condition) + for lock in _ordered_condition_locks(conditions): + stack.enter_context(lock) _track_sync_cancel(event, deadline) sampled = monotonic() flagged = bool(getattr(event, "_flag", False)) - entry_set = flagged and _thread_event_is_set(event) + # A standard predicate cannot race the locked flag sample. An override is + # still consulted outside the locks so it cannot re-enter a held lock. + entry_set = flagged if standard_predicate else flagged and _thread_event_is_set(event) if entry_set: deadline.record_entry(sampled) _drain_signals() @@ -722,26 +803,25 @@ def _async_flag_is_set(event: AsyncEvent) -> bool: def _check_async_event_loop(event: asyncio.Event) -> None: - """Bind ownership with native registration before scanning waiters. + """Reject foreign waiters before native registration can bind the event. The caller holds ``_async_future_lock``, so a competing native ``wait()`` - cannot bind the event to a different loop between the check and the SDK - attaching its own waiter. + cannot register a waiter between the scan and the SDK attaching its own. """ + loop = async_get_running_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.") + 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.") binder = getattr(event, "_get_loop", None) if binder is not None: try: binder() except RuntimeError: raise RuntimeError("cancel_event is already bound to a different event loop.") from None - 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: @@ -889,9 +969,53 @@ def __init__(self, loop: Any, owned: bool) -> None: self.loop = loop self.owned = owned self.count = 0 + self.cleanup_armed = False -_async_loop_bindings: WeakKeyDictionary[AsyncEvent, _AsyncLoopBinding] = WeakKeyDictionary() +class _AsyncBindingRegistry: + """Identity-keyed weak bindings, including events that are unhashable.""" + + def __init__(self) -> None: + self._events: dict[int, Any] = {} + self._bindings: dict[int, _AsyncLoopBinding] = {} + + def _discard(self, key: int, binding: _AsyncLoopBinding | None = None) -> None: + if binding is None or self._bindings.get(key) is binding: + self._bindings.pop(key, None) + self._events.pop(key, None) + + def __setitem__(self, event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + key = id(event) + self._discard(key) + + def event_gone(_: Any) -> None: + self._discard(key) + + self._events[key] = weak_ref(event, event_gone) + self._bindings[key] = binding + + def get(self, event: AsyncEvent) -> _AsyncLoopBinding | None: + key = id(event) + event_ref = self._events.get(key) + binding = self._bindings.get(key) + if event_ref is None or binding is None: + return None + if event_ref() is not event: + self._discard(key) + return None + return binding + + def discard(self, event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + self._discard(id(event), binding) + + def __contains__(self, event: object) -> bool: + return isinstance(event, asyncio.Event) and self.get(event) is not None + + def __delitem__(self, event: AsyncEvent) -> None: + self._discard(id(event)) + + +_async_loop_bindings = _AsyncBindingRegistry() class _AsyncSignalWaiter: @@ -903,8 +1027,20 @@ def __init__(self) -> None: self.binding: _AsyncLoopBinding | None = None +def _clear_temporary_async_binding(event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + """Clear a temporary ownership once the last native waiter has drained.""" + with _async_future_lock: + if binding.count or _async_loop_bindings.get(event) is not binding: + return + if getattr(event, "_waiters", None): + return + _async_loop_bindings.discard(event, binding) + if binding.owned and getattr(event, "_loop", None) is binding.loop: + event._loop = None # type: ignore[attr-defined] + + def _release_async_binding(waiter: _AsyncSignalWaiter) -> None: - """Release one SDK waiter, clearing a temporary binding when the last leaves.""" + """Release one SDK waiter, retaining ownership until native waiters drain.""" binding = waiter.binding event = waiter.event waiter.binding = None @@ -913,11 +1049,28 @@ def _release_async_binding(waiter: _AsyncSignalWaiter) -> None: binding.count -= 1 if binding.count > 0: return - if _async_loop_bindings.get(event) is binding: - del _async_loop_bindings[event] waiters = getattr(event, "_waiters", None) - if binding.owned and not waiters and getattr(event, "_loop", None) is binding.loop: - event._loop = None # type: ignore[attr-defined] + if waiters: + if not binding.cleanup_armed: + binding.cleanup_armed = True + + def drain(_: Any) -> None: + try: + binding.loop.call_soon(_clear_temporary_async_binding, event, binding) + except RuntimeError: + pass + + for pending in tuple(waiters): + try: + pending.add_done_callback(drain) + except Exception: + pass + try: + binding.loop.call_soon(_clear_temporary_async_binding, event, binding) + except RuntimeError: + pass + return + _clear_temporary_async_binding(event, binding) def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: @@ -1472,10 +1625,11 @@ def wait_for_review( another head ends the wait on that read and is never COMPLETED. An event already set at entry stops the wait before any request, even - when ``timeout`` is zero. 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 + when ``timeout`` is zero, once argument validation has succeeded. + 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. A cancellable wait samples its deadline before validation, so validation and URL construction count toward the polling budget and can @@ -1494,7 +1648,9 @@ def wait_for_review( 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. + next checkpoint. A subclass whose ``is_set()`` forwards to the standard + predicate is supported because native delivery is latched from the raw + flag; an override that hides that flag is not. """ if not math.isfinite(timeout) or timeout < 0: @@ -1923,10 +2079,11 @@ async def wait_for_review( """Wait for recorded review completion or return TIMED_OUT. An event already set at entry stops the wait before any request, even - when ``timeout`` is zero. 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. A cancellable wait - samples its deadline before validation, so validation and URL + when ``timeout`` is zero, once argument validation has succeeded. + 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. A cancellable wait samples its deadline before + validation, so validation and URL construction count toward the polling budget and can exhaust it without a request; notifications observed during setup use that same deadline. Without a cancellation event, validation and URL construction happen @@ -1939,9 +2096,10 @@ async def wait_for_review( a check after a read but will not wake an in-progress backoff. Native event registration establishes loop ownership under the waiter lock; an event or existing waiter already bound to another loop is rejected - before the early check or the first request. That SDK-owned binding is - released when the last waiter is removed, so the event can be reused on - another loop later. + before the early check or the first request. An SDK-owned temporary + binding is released when its last waiter is removed; if native waiters + remain, ownership is retained until they drain, so reuse on another loop + is possible only after both SDK and native waiters are gone. """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") diff --git a/tests/test_http.py b/tests/test_http.py index 7c6fb9b2..d66af3ed 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -205,28 +205,27 @@ def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None woke = True return woke - def _record_async_arrival(self, event: Any, deadline: float, signal: Any | None) -> bool: - if not event.is_set() or self.now >= deadline: + def _record_async_arrival( + self, event: Any, cutoff: float, signal: Any | None, published: bool = False + ) -> bool: + if not published or not event.is_set() or self.now >= cutoff: return False if signal is not None: - signal.record(self.now) + signal.record(min(self.now, signal.end)) return True async def async_wait_for_event( self, event: Any, cutoff: float, signal: Any | None = None ) -> bool: - deadline = signal.end if signal is not None else cutoff if self.publication.is_set(): self.publication.clear() - if self._record_async_arrival(event, deadline, signal): + if self._record_async_arrival(event, cutoff, signal, published=True): return True - if self._record_async_arrival(event, deadline, signal): - return True if not self.deadline_reached.is_set(): raise AssertionError("advance the fake async deadline explicitly") self.deadline_reached.clear() - self.sleep(max(0.0, deadline - self.now)) - return self._record_async_arrival(event, deadline, signal) + self.sleep(max(0.0, cutoff - self.now)) + return self._record_async_arrival(event, cutoff, signal) def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -2423,9 +2422,18 @@ def __init__(self): super().__init__() self.backing = threading.Event() self.is_set = threading.Event.is_set.__get__(self, threading.Event) + self.primary_notifications = 0 + original_notify_all = self._cond.notify_all + + def notify_all(*args, **kwargs): + self.primary_notifications += 1 + return original_notify_all(*args, **kwargs) + + self._cond.notify_all = notify_all def set(self): - super().set() + # Publish on the backing condition only; never notify the primary one. + self._flag = True self.backing.set() event = BackingEvent() @@ -2440,15 +2448,29 @@ def track(event_arg, deadline): t.client_module._track_sync_cancel = track t.client_module.monotonic = lambda: now[0] now = [100.0] +woke_at = [] +waiting = threading.Event() +revealed = threading.Event() +real_wait = t.client_module._wait_for_event + +def wait_for_event(event_arg, timeout, deadline=None): + waiting.set() + woke = real_wait(event_arg, timeout, deadline) + woke_at.append(now[0]) + revealed.set() + return woke + +t.client_module._wait_for_event = wait_for_event def signal(): - if not ready.wait(2.0): - failures.append("the cancellation observers were never installed") + if not ready.wait(2.0) or not waiting.wait(2.0): + failures.append("the waiter was never registered") now[0] = 101.5 event.set() return now[0] = 100.5 event.set() + assert revealed.wait(2.0), "the waiter did not observe the backing wake" now[0] = 102.0 thread = threading.Thread(target=signal, daemon=True) @@ -2458,6 +2480,8 @@ def signal(): assert not thread.is_alive() assert failures == [] assert result is False +assert woke_at and woke_at[0] < 101.0 +assert event.primary_notifications == 0 backing_condition = event.backing._cond tracker = t.client_module._notify_trackers[backing_condition] assert backing_condition.notify_all is tracker.installed_notify_all @@ -2886,14 +2910,18 @@ async def set_later(): 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 == t.REVIEW + verified = False + try: + 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 + verified = True + finally: + await t.finish_sender(setter, check=verified) asyncio.run(main()) print("OK") @@ -4498,9 +4526,56 @@ class ForeignWaiter: with pytest.raises(RuntimeError, match="different event loop"): client_module._watch_async_waiter(event, deadline) assert list(event._waiters) == [foreign] + assert event._loop is None assert id(event) not in client_module._async_signal_watches + assert event not in client_module._async_loop_bindings finally: event._waiters.remove(foreign) # type: ignore[arg-type] + waiter = client_module._watch_async_waiter(event, deadline) + try: + assert event._loop is asyncio.get_running_loop() + finally: + client_module._unwatch_async_waiter(waiter, deadline) + assert event._loop is None + + +async def test_async_waiter_keeps_a_temporary_binding_until_native_waiters_drain() -> None: + event = asyncio.Event() + loop = asyncio.get_running_loop() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + client_module._unwatch_async_waiter(sdk_waiter, deadline) + assert event in client_module._async_loop_bindings + assert event._loop is loop + assert len(event._waiters) == 1 + + native.cancel() + with pytest.raises(asyncio.CancelledError): + await native + await wait_until( + lambda: event._loop is None and event not in client_module._async_loop_bindings + ) + assert not event._waiters + + +async def test_wait_for_review_accepts_an_unhashable_async_event_already_set( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class UnhashableEvent(asyncio.Event): + __hash__ = None # type: ignore[assignment] + + Clock(monkeypatch) + event = UnhashableEvent() + event.set() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + result = await 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." + assert event not in client_module._async_loop_bindings def test_condition_tracker_registration_waits_for_a_held_notification_lock() -> None: @@ -5300,7 +5375,7 @@ def notify_all(self) -> None: def test_initial_sync_signal_orders_linked_condition_locks() -> None: # Two events that reference each other expose the same locks in opposite - # order; a regression must be caught by the subprocess watchdog. + # order; each setup must record the same identity order under a watchdog. code = """ import sys import threading @@ -5309,11 +5384,48 @@ def test_initial_sync_signal_orders_linked_condition_locks() -> None: sys.path.insert(0, sys.argv[1]) from proofline import client + +class TrackingLock: + def __init__(self, order): + self._lock = threading.Lock() + self._order = order + + def __enter__(self): + self._order.append((threading.get_ident(), id(self))) + self._lock.acquire() + return self + + def __exit__(self, *exc): + self._lock.release() + return False + + def acquire(self, *args, **kwargs): + acquired = self._lock.acquire(*args, **kwargs) + if acquired: + self._order.append((threading.get_ident(), id(self))) + return acquired + + def release(self): + self._lock.release() + + def locked(self): + return self._lock.locked() + + def _is_owned(self): + return self._lock._is_owned() + + +order_log = [] +first_lock = TrackingLock(order_log) +second_lock = TrackingLock(order_log) first = threading.Event() second = threading.Event() +first._cond = threading.Condition(first_lock) +second._cond = threading.Condition(second_lock) first.other = second second.other = first barrier = threading.Barrier(2) +orders = [first, second] errors = [] @@ -5327,13 +5439,19 @@ def run(event): errors.append(repr(error)) -threads = [threading.Thread(target=run, args=(event,), daemon=True) for event in (first, second)] +threads = [threading.Thread(target=run, args=(event,), daemon=True) for event in orders] for thread in threads: thread.start() for thread in threads: thread.join(5.0) assert not any(thread.is_alive() for thread in threads), "linked setup deadlocked" assert errors == [], errors +by_thread = {} +for thread_id, lock_id in order_log: + by_thread.setdefault(thread_id, []).append(lock_id) +assert len(by_thread) == 2 +assert all(len(order) == 2 and tuple(order) == tuple(sorted(order)) for order in by_thread.values()) +assert len({tuple(order) for order in by_thread.values()}) == 1 print("OK") """ root = Path(__file__).resolve().parents[1] @@ -5347,6 +5465,141 @@ def run(event): assert result.stdout.strip() == "OK" +def test_initial_sync_signal_uses_a_shared_non_reentrant_lock_once() -> None: + # Holding one lock twice would hang before any wait deadline is established. + code = """ +import sys +import threading +import time + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +lock = threading.Lock() +first = threading.Event() +second = threading.Event() +first._cond = threading.Condition(lock) +second._cond = threading.Condition(lock) +first.backing = second +deadline = client._SignalDeadline(time.monotonic() + 5.0) +client._initial_sync_signal(first, deadline) +client._untrack_sync_cancel(first, deadline) +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_notification_does_not_invoke_an_is_set_descriptor() -> None: + code = """ +import sys +import threading + +sys.path.insert(0, sys.argv[1]) +from proofline import client + + +class DescriptorEvent(threading.Event): + @property + def is_set(self): + assert not self._cond._lock.locked(), "descriptor invoked under the condition" + return bool(self._flag) + + +event = DescriptorEvent() +now = [100.0] +client.monotonic = lambda: now[0] + + +def wait_for_event(wait_event, timeout, deadline=None): + now[0] = 100.5 + wait_event.set() + wait_event.clear() + return False + + +client._wait_for_event = wait_for_event +result = client._sleep_with_cancel(5, event, cutoff=101.0) +assert result is True +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_latches_a_forwarding_is_set_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class ForwardingEvent(threading.Event): + def is_set(self) -> bool: + return super().is_set() + + clock = Clock(monkeypatch) + event = ForwardingEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert not event.is_set() + assert deadline.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_rewraps_replaced_hooks_before_reuse( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + standard_all = threading.Condition.notify_all + standard_notify = threading.Condition.notify + first = client_module._SignalDeadline(clock.now + 10.0) + second = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, first) + tracker = client_module._notify_trackers[condition] + + def replacement_all(*args: Any, **kwargs: Any) -> None: + standard_all(condition, *args, **kwargs) + + def replacement_notify(*args: Any, **kwargs: Any) -> None: + standard_notify(condition, *args, **kwargs) + + condition.notify_all = replacement_all # type: ignore[method-assign] + condition.notify = replacement_notify # type: ignore[method-assign] + client_module._track_thread_signal(event, second) + try: + assert condition.notify_all is tracker.installed_notify_all + assert condition.notify is tracker.installed_notify + assert tracker.saved_notify_all is replacement_all + assert tracker.saved_notify is replacement_notify + clock.now = 100.5 + event.set() + event.clear() + 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_async_waiter_releases_a_shared_loop_binding_with_its_last_waiter() -> None: event = asyncio.Event() @@ -5497,7 +5750,14 @@ async def test_clock_async_wait_uses_an_explicit_deadline_gate( clock.now = 100.1 event.set() - clock.publish() signal = client_module._SignalDeadline(clock.now + 10.0) + clock.reach_deadline() + assert await clock.async_wait_for_event(event, signal.end, signal) is False + assert signal.signalled_at is None + assert clock.delays == [10.0, 10.0] + + clock.now = 100.1 + signal = client_module._SignalDeadline(clock.now + 10.0) + clock.publish() assert await clock.async_wait_for_event(event, signal.end, signal) is True assert signal.signalled_at == 100.1 From f091efc275c9370b8867dcf1f0a4157051509ae8 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Mon, 30 Nov 2026 00:05:46 +0530 Subject: [PATCH 26/28] Address twenty-sixth Proofline review findings --- README.md | 2 +- proofline/client.py | 284 ++++++++++++++++++++++++++++++----------- tests/test_http.py | 299 +++++++++++++++++++++++++++++++++++++++----- 3 files changed, 486 insertions(+), 99 deletions(-) diff --git a/README.md b/README.md index e9b11b56..5275cee8 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` forwards to the standard predicate are supported for both event types: native delivery is latched directly from the event's own flag, so a timely `set()` followed by `clear()` is observed without the SDK calling that override. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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. +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` forwards to the standard predicate are supported for both event types: a timely `set()` followed by `clear()` is observed without the SDK calling that override. For a standard synchronous predicate, delivery is verified from the raw flag under the notification; an overridden synchronous predicate is checked after the condition lock is released, so it cannot deadlock that `set()` call. For `asyncio.Event`, native delivery wakes the wait and is recorded as cancellation only when the supplied predicate agrees. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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 2d64f6ea..753ebefa 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -215,13 +215,14 @@ def _thread_event_is_set(event: threading.Event | AsyncEvent) -> bool: _notify_lock = threading.RLock() _publication_lock = threading.Lock() -# (deadline, sampled time, whether the notification was verified at delivery) -_pending_notifications: list[tuple[_SignalDeadline, float, bool]] = [] +# (deadline, sampled time, verification: True, False, or a deferred predicate) +_Verification = bool | Callable[[], bool] | None +_pending_notifications: list[tuple[_SignalDeadline, float, _Verification]] = [] # 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: +def _stage_signals(items: tuple[tuple[_SignalDeadline, float, _Verification], ...]) -> None: """Make sampled notifications visible before contending for the deadline lock.""" with _publication_lock: _pending_notifications.extend(items) @@ -233,11 +234,30 @@ def _drain_signals() -> None: with _publication_lock: items = tuple(_pending_notifications) _pending_notifications.clear() - for deadline, now, verified in items: - if verified: + for deadline, now, verification in items: + if verification is True: deadline.record(now) - else: + elif verification is False or verification is None: deadline.defer(now) + else: + deadline.defer_verified(now, verification) + + +def _verify_deferred_signals(deadline: _SignalDeadline, end: float) -> None: + """Resolve deferred predicates only after the condition lock has been released.""" + with _notify_lock: + pending = tuple(deadline.pending) + deadline.pending.clear() + for now, predicate in pending: + try: + verified = bool(predicate()) + except Exception: + verified = False + with _notify_lock: + if verified: + deadline.record(now) + elif deadline.signalled_at is None and now < end: + deadline.signal_event.set() def _publish_signals(items: tuple[tuple[_SignalDeadline, float], ...]) -> None: @@ -255,6 +275,7 @@ def __init__(self, end: float) -> None: self.entry = False self.conditions: tuple[threading.Condition, ...] = () self.signal_event = threading.Event() + self.pending: list[tuple[float, Callable[[], bool]]] = [] def record(self, now: float) -> bool: if self.signalled_at is None and now < self.end: @@ -281,6 +302,12 @@ def defer(self, now: float) -> None: if self.signalled_at is None and now < self.end: self.signal_event.set() + def defer_verified(self, now: float, predicate: Callable[[], bool]) -> None: + """Wake now, with an out-of-lock predicate check deferred to a checkpoint.""" + if self.signalled_at is None and now < self.end: + self.pending.append((now, predicate)) + self.signal_event.set() + def _event_attributes_snapshot(value: Any) -> tuple[Any, ...]: """Read an event's instance attributes without racing hook installation.""" @@ -288,13 +315,33 @@ def _event_attributes_snapshot(value: Any) -> tuple[Any, ...]: return tuple(_instance_attributes(value).values()) -def _event_has_standard_predicate(value: Any) -> bool: - """Whether the instance uses the standard predicate, without invoking descriptors.""" - if "is_set" in _instance_attributes(value): +def _forwards_is_set(method: Any) -> bool: + """Whether a method only delegates to the inherited standard predicate.""" + function = getattr(method, "__func__", method) + code = getattr(function, "__code__", None) + if code is None: return False + return ( + code.co_names == ("super", "is_set") + and "__class__" in code.co_freevars + and "self" in code.co_varnames + ) + + +def _event_has_standard_predicate(value: Any) -> bool: + """Whether the resolved predicate is safe to read from the raw flag.""" + attributes = _instance_attributes(value) + if "is_set" in attributes: + candidate = attributes["is_set"] + if getattr(candidate, "__func__", None) is threading.Event.is_set and ( + getattr(candidate, "__self__", None) is value + ): + return True + return _forwards_is_set(candidate) and getattr(candidate, "__self__", None) is value for cls in type(value).__mro__: if "is_set" in cls.__dict__: - return cls.__dict__["is_set"] is threading.Event.is_set + raw = cls.__dict__["is_set"] + return raw is threading.Event.is_set or _forwards_is_set(raw) return False @@ -464,11 +511,10 @@ def __init__(self, condition: threading.Condition) -> None: # the outer dispatch so a subscriber added while an override delegates # cannot consume a notification that began before it subscribed. self._dispatching = False - self.installed_notify_all = self.notify_all - self.installed_notify = self.notify + self.installed_notify_all: Any = None + self.installed_notify: Any = None try: - condition.notify_all = self.installed_notify_all # type: ignore[method-assign] - condition.notify = self.installed_notify # type: ignore[method-assign] + self._install_initial_hooks(condition) except BaseException: _rollback_condition_hook( condition, @@ -486,6 +532,45 @@ def __init__(self, condition: threading.Condition) -> None: ) raise + def _new_hook(self, delegate: Any) -> Callable[..., Any]: + """Create a wrapper whose delegate is fixed at installation time.""" + + def installed(*args: Any, **kwargs: Any) -> Any: + return self._dispatch(delegate, *args, **kwargs) + + return installed + + def _install_initial_hooks(self, condition: threading.Condition) -> None: + installed_all = self._new_hook(self.original_notify_all) + installed_notify = self._new_hook(self.original_notify) + changed: list[tuple[str, bool, Any, Any]] = [] + try: + for name, had_name, saved_name, installed_name, installed in ( + ( + "notify_all", + "had_notify_all", + "saved_notify_all", + "installed_notify_all", + installed_all, + ), + ( + "notify", + "had_notify", + "saved_notify", + "installed_notify", + installed_notify, + ), + ): + changed.append( + (name, getattr(self, had_name), getattr(self, saved_name), installed) + ) + setattr(self, installed_name, installed) + setattr(condition, name, installed) + except BaseException: + for name, had_instance, saved, installed in changed: + _rollback_condition_hook(condition, name, had_instance, saved, installed) + raise + def _hooks_installed(self) -> bool: condition = self.condition_ref() return condition is not None and ( @@ -494,61 +579,71 @@ def _hooks_installed(self) -> bool: ) def _rehook(self) -> None: - """Wrap the current methods when a caller has replaced either hook.""" + """Wrap current methods with fresh wrappers after a caller replaces hooks.""" condition = self.condition_ref() if condition is None: return attributes = _instance_attributes(condition) changed: list[tuple[str, bool, Any, Any]] = [] try: - for name, original_name, had_name, saved_name, installed in ( + for name, original_name, had_name, saved_name, installed_name in ( ( "notify_all", "original_notify_all", "had_notify_all", "saved_notify_all", - self.installed_notify_all, + "installed_notify_all", ), ( "notify", "original_notify", "had_notify", "saved_notify", - self.installed_notify, + "installed_notify", ), ): + installed = getattr(self, installed_name) if getattr(condition, name, None) is installed: continue had_instance = name in attributes saved = attributes.get(name) method = getattr(condition, name) + fresh = self._new_hook(method) + # Journal the attempted assignment before invoking a setter that + # may store the wrapper and then raise. + changed.append((name, had_instance, saved, fresh)) setattr(self, had_name, had_instance) setattr(self, saved_name, saved) setattr(self, original_name, _weak_bound_method(method)) - setattr(condition, name, installed) - changed.append((name, had_instance, saved, installed)) + setattr(self, installed_name, fresh) + setattr(condition, name, fresh) except BaseException: for name, had_instance, saved, installed in changed: _rollback_condition_hook(condition, name, had_instance, saved, installed) raise def record(self) -> None: - # Sample and stage before contending for the deadline decision lock, so - # a paused notifier cannot hide a timely signal from the final check. - # Overridable predicates are never called while the condition is locked; - # only a standard predicate on the event itself proves delivery here. - now = monotonic() + # Sample the clock and snapshot subscribers in one critical section, so + # a subscriber registered during this dispatch cannot receive its time. with self._subscription_lock: + now = monotonic() subscribers = tuple(self.subscribers.items()) - staged: list[tuple[_SignalDeadline, float, bool]] = [] + staged: list[tuple[_SignalDeadline, float, _Verification]] = [] for deadline, (watched, backing, caller) in subscribers: if not bool(getattr(watched, "_flag", False)): continue - verified = not backing and watched is caller - if verified: - predicate = _thread_predicate_for_notification(caller) - verified = predicate is not None and bool(predicate()) - staged.append((deadline, now, verified)) + if _event_has_standard_predicate(caller): + # The raw flag is the standard predicate; it is safe to verify + # here even while the condition lock is held. + staged.append((deadline, now, bool(getattr(caller, "_flag", False)))) + continue + predicate = _thread_predicate_for_notification(caller) + if predicate is None: + staged.append((deadline, now, False)) + else: + # An override may re-enter the condition lock, so defer its + # predicate to a checkpoint outside notification. + staged.append((deadline, now, predicate)) _stage_signals(tuple(staged)) _drain_signals() @@ -624,16 +719,24 @@ def _track_thread_signal(event: threading.Event, deadline: _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) + added: list[_ConditionSignalTracker] = [] with _notify_lock: - for tracked, watched_event, backing in watched: - tracker = _notify_trackers.get(tracked) - if tracker is None: - tracker = _ConditionSignalTracker(tracked) - _notify_trackers[tracked] = tracker - elif not tracker._hooks_installed(): - tracker._rehook() - with tracker._subscription_lock: - tracker.subscribers[deadline] = (watched_event, backing, event) + try: + for tracked, watched_event, backing in watched: + tracker = _notify_trackers.get(tracked) + if tracker is None: + tracker = _ConditionSignalTracker(tracked) + _notify_trackers[tracked] = tracker + elif not tracker._hooks_installed(): + tracker._rehook() + with tracker._subscription_lock: + tracker.subscribers[deadline] = (watched_event, backing, event) + added.append(tracker) + except BaseException: + for tracker in added: + with tracker._subscription_lock: + tracker.subscribers.pop(deadline, None) + raise return deadline @@ -709,9 +812,10 @@ def _record_signal_before( if event is None: return False _drain_signals() + _verify_deferred_signals(deadline, end) if deadline.signalled_at is not None: return True - if event is None or not _thread_event_is_set(event): + if not _thread_event_is_set(event): return False with _notify_lock: if deadline.signalled_at is not None: @@ -757,8 +861,9 @@ def _stopped( def _sync_deadline_state(deadline: _SignalDeadline) -> tuple[float | None, float]: - """Drain pending publications, then read the latch and clock under one lock.""" + """Resolve deferred predicates, drain publications, then read the latch.""" _drain_signals() + _verify_deferred_signals(deadline, deadline.end) with _notify_lock: return deadline.signalled_at, monotonic() @@ -821,6 +926,10 @@ def _check_async_event_loop(event: asyncio.Event) -> None: try: binder() except RuntimeError: + # A failing override may have bound the event before raising. Roll + # back only a binding it created here, never a preexisting one. + if event_loop is None and getattr(event, "_loop", None) is loop: + event._loop = None # type: ignore[attr-defined] raise RuntimeError("cancel_event is already bound to a different event loop.") from None @@ -886,9 +995,12 @@ def set_result(result: Any) -> None: if not _async_flag_is_set(event): return if not self.signal.dispatch_done: - # Native delivery on this event proves the signal regardless of - # an is_set() override; the raw flag was checked by the caller. - self.signal.note(monotonic()) + # Native delivery is evidence only when the supplied predicate + # agrees; an override that stays closed merely wakes the wait. + if _event_is_set(event): + self.signal.note(monotonic()) + else: + self.signal.defer(monotonic()) self.original(result) self.installed = set_result @@ -970,6 +1082,7 @@ def __init__(self, loop: Any, owned: bool) -> None: self.owned = owned self.count = 0 self.cleanup_armed = False + self.watched: set[int] = set() class _AsyncBindingRegistry: @@ -1027,12 +1140,51 @@ def __init__(self) -> None: self.binding: _AsyncLoopBinding | None = None +def _schedule_binding_recheck(event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + """Ask the owning loop to recheck native waiters once they settle.""" + try: + binding.loop.call_soon(_clear_temporary_async_binding, event, binding) + except RuntimeError: + pass + + +def _arm_native_waiter_cleanup( + event: AsyncEvent, + binding: _AsyncLoopBinding, + waiters: tuple[AsyncFuture[Any], ...], + *, + recheck: bool, +) -> None: + """Watch each pending native waiter, including ones added after teardown.""" + binding.cleanup_armed = True + for pending in waiters: + key = id(pending) + if key in binding.watched: + continue + binding.watched.add(key) + + def done(_: Any, key: int = key) -> None: + binding.watched.discard(key) + _schedule_binding_recheck(event, binding) + + try: + pending.add_done_callback(done) + except Exception: + binding.watched.discard(key) + if recheck: + _schedule_binding_recheck(event, binding) + + def _clear_temporary_async_binding(event: AsyncEvent, binding: _AsyncLoopBinding) -> None: - """Clear a temporary ownership once the last native waiter has drained.""" + """Clear a temporary ownership once every native waiter has drained.""" with _async_future_lock: if binding.count or _async_loop_bindings.get(event) is not binding: return - if getattr(event, "_waiters", None): + waiters = tuple( + pending for pending in getattr(event, "_waiters", None) or () if not pending.done() + ) + if waiters: + _arm_native_waiter_cleanup(event, binding, waiters, recheck=False) return _async_loop_bindings.discard(event, binding) if binding.owned and getattr(event, "_loop", None) is binding.loop: @@ -1049,26 +1201,11 @@ def _release_async_binding(waiter: _AsyncSignalWaiter) -> None: binding.count -= 1 if binding.count > 0: return - waiters = getattr(event, "_waiters", None) + waiters = tuple( + pending for pending in getattr(event, "_waiters", None) or () if not pending.done() + ) if waiters: - if not binding.cleanup_armed: - binding.cleanup_armed = True - - def drain(_: Any) -> None: - try: - binding.loop.call_soon(_clear_temporary_async_binding, event, binding) - except RuntimeError: - pass - - for pending in tuple(waiters): - try: - pending.add_done_callback(drain) - except Exception: - pass - try: - binding.loop.call_soon(_clear_temporary_async_binding, event, binding) - except RuntimeError: - pass + _arm_native_waiter_cleanup(event, binding, waiters, recheck=True) return _clear_temporary_async_binding(event, binding) @@ -1653,6 +1790,9 @@ def wait_for_review( flag; an override that hides that flag is not. """ + # A cancellable wait's budget includes validation; sample its start + # before validating so a slow conversion cannot extend the deadline. + start = monotonic() if cancel_event is not None else None if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, threading.Event): @@ -1662,8 +1802,9 @@ def wait_for_review( deadline_set = False try: if cancel_event is not None: - initially_set, sampled = _initial_sync_signal(cancel_event, read_signal) - deadline_at = sampled + timeout + initially_set, _ = _initial_sync_signal(cancel_event, read_signal) + assert start is not None + deadline_at = start + timeout read_signal.cap(deadline_at) _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) @@ -2101,6 +2242,9 @@ async def wait_for_review( remain, ownership is retained until they drain, so reuse on another loop is possible only after both SDK and native waiters are gone. """ + # A cancellable wait's budget includes validation; sample its start + # before validating so a slow conversion cannot extend the deadline. + start = monotonic() if cancel_event is not None else None if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): @@ -2113,8 +2257,8 @@ async def wait_for_review( if cancel_event is not None: read_waiter = _watch_async_waiter(cancel_event, read_signal) initially_set = _cancelled(cancel_event) - sampled = monotonic() - deadline_at = sampled + timeout + assert start is not None + deadline_at = start + timeout read_signal.cap(deadline_at) _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) diff --git a/tests/test_http.py b/tests/test_http.py index d66af3ed..f0519969 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -174,6 +174,7 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 self.delays: list[float] = [] self.publication = threading.Event() + self.publication_at: float | None = None self.deadline_reached = threading.Event() monkeypatch.setattr(client_module, "monotonic", lambda: self.now) monkeypatch.setattr(_transport, "monotonic", lambda: self.now) @@ -187,6 +188,7 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: def publish(self) -> None: """Mark a cancellation as explicitly published at the current fake time.""" + self.publication_at = self.now self.publication.set() def reach_deadline(self) -> None: @@ -206,12 +208,18 @@ def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None return woke def _record_async_arrival( - self, event: Any, cutoff: float, signal: Any | None, published: bool = False + self, + event: Any, + cutoff: float, + signal: Any | None, + published: bool = False, + arrival: float | None = None, ) -> bool: - if not published or not event.is_set() or self.now >= cutoff: + when = self.now if arrival is None else arrival + if not published or not event.is_set() or when >= cutoff: return False if signal is not None: - signal.record(min(self.now, signal.end)) + signal.record(min(when, signal.end)) return True async def async_wait_for_event( @@ -219,7 +227,8 @@ async def async_wait_for_event( ) -> bool: if self.publication.is_set(): self.publication.clear() - if self._record_async_arrival(event, cutoff, signal, published=True): + arrival, self.publication_at = self.publication_at, None + if self._record_async_arrival(event, cutoff, signal, published=True, arrival=arrival): return True if not self.deadline_reached.is_set(): raise AssertionError("advance the fake async deadline explicitly") @@ -2212,19 +2221,28 @@ def record(now: float) -> bool: 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 + task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) + try: + await wait_until(lambda: bool(event._waiters)) + assert event.set == setter + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) assert not event._waiters 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 + try: + await wait_until(lambda: bool(event._waiters)) + assert len(event._waiters) == 1 + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + finally: + await asyncio.gather(task, return_exceptions=True) + assert not event._waiters def test_sleep_with_cancel_returns_true_at_deadline_without_a_signal( @@ -2889,8 +2907,18 @@ async def main(): async def async_wait(*args, **kwargs): helper = asyncio.create_task(real_wait(*args, **kwargs)) + + async def wait_for_waiters(): + for _ in range(200): + if helper.done(): + await helper + if len(event._waiters) >= 2: + return + await asyncio.sleep(0) + raise AssertionError("the backoff waiter was never registered") + try: - await t.wait_until(lambda: len(event._waiters) >= 2) + await wait_for_waiters() ready.set() return await helper finally: @@ -2905,13 +2933,13 @@ async def set_later(): setter = asyncio.create_task(set_later()) started = time.monotonic() - 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 - ) verified = False try: + 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 + ) assert time.monotonic() - started < 2.0 assert ready.is_set() assert len(server.requests) == 1 @@ -3040,6 +3068,8 @@ def get_review(*args: Any, **kwargs: Any) -> Any: nonlocal calls calls += 1 clock.now += 101.0 + event.set() + assert event.is_set() raise _transport.invalid_response() monkeypatch.setattr(client, "get_review", get_review) @@ -3049,7 +3079,7 @@ def get_review(*args: Any, **kwargs: Any) -> Any: assert calls == 1 assert result.status == "TIMED_OUT" assert result.review is None - assert not event.is_set() + assert event.is_set() @MODES @@ -4785,6 +4815,8 @@ async def test_async_future_watch_stamps_one_notification_for_all_observers( monkeypatch: pytest.MonkeyPatch, ) -> None: clock = Clock(monkeypatch) + samples = iter((100.02, 100.03, 100.04)) + monkeypatch.setattr(client_module, "monotonic", lambda: next(samples, 100.04)) event = asyncio.Event() future = asyncio.get_running_loop().create_future() first = client_module._SignalDeadline(clock.now + 0.1) @@ -4792,10 +4824,10 @@ async def test_async_future_watch_stamps_one_notification_for_all_observers( 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 + assert first.signalled_at == 100.02 + assert second.signalled_at == 100.02 finally: client_module._unwatch_async_future(future, first) client_module._unwatch_async_future(future, second) @@ -5038,6 +5070,7 @@ def test_async_waiter_registration_is_atomic_across_event_loops() -> None: release = threading.Event() second_done = threading.Event() attempts = [] +paused_ident = [] real_lock = client._async_future_lock real_watch_future = client._watch_async_future @@ -5055,10 +5088,11 @@ def __exit__(self, *args): def paused_registration(*args, **kwargs): - result = real_watch_future(*args, **kwargs) - registered.set() - assert release.wait(5.0), "the first registration was never released" - return result + if not paused_ident: + paused_ident.append(threading.get_ident()) + registered.set() + assert release.wait(5.0), "the paused registration was never released" + return real_watch_future(*args, **kwargs) client._watch_async_future = paused_registration @@ -5086,14 +5120,14 @@ async def main(): threads = [threading.Thread(target=run, daemon=True) for _ in range(2)] for thread in threads: thread.start() -assert registered.wait(5.0), "the first registration never started" -second_ident = threads[1].ident +assert registered.wait(5.0), "the paused registration never started" +assert paused_ident for _ in range(500): - if second_ident in attempts: + if any(ident != paused_ident[0] for ident in attempts): break time.sleep(0.01) else: - raise AssertionError("the second registration did not attempt the lock") + raise AssertionError("the contending registration did not attempt the lock") assert not release.is_set(), "the first registration resumed before the lock attempt" release.set() for thread in threads: @@ -5761,3 +5795,212 @@ async def test_clock_async_wait_uses_an_explicit_deadline_gate( clock.publish() assert await clock.async_wait_for_event(event, signal.end, signal) is True assert signal.signalled_at == 100.1 + + +def test_condition_tracker_rehook_preserves_a_captured_wrapper_delegate( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + first = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, first) + captured = condition.notify_all + + def forwarding(*args: Any, **kwargs: Any) -> Any: + return captured(*args, **kwargs) + + condition.notify_all = forwarding # type: ignore[method-assign] + second = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, second) + try: + clock.now = 100.5 + 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_a_hook_that_fails_after_storing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class RaisingCondition(threading.Condition): + def __setattr__(self, name: str, value: Any) -> None: + if name == "notify_all" and getattr(self, "_fail", False): + super().__setattr__(name, value) + raise RuntimeError("hook failed") + super().__setattr__(name, value) + + condition = RaisingCondition(threading.Lock()) + event = threading.Event() + event._cond = condition + first = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, first) + tracker = client_module._notify_trackers[condition] + + def replacement(*args: Any, **kwargs: Any) -> None: + threading.Condition.notify_all(condition, *args, **kwargs) + + condition.notify_all = replacement # type: ignore[method-assign] + condition._fail = True # type: ignore[attr-defined] + second = client_module._SignalDeadline(clock.now + 10.0) + with pytest.raises(RuntimeError, match="hook failed"): + client_module._track_thread_signal(event, second) + condition._fail = False # type: ignore[attr-defined] + assert condition.notify_all is replacement + assert first in tracker.subscribers + assert second not in tracker.subscribers + client_module._untrack_thread_signal(event, first) + + +def test_condition_tracker_defers_an_overridden_predicate_until_a_checkpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.gate = False + + def is_set(self) -> bool: + return self.gate and super().is_set() + + clock = Clock(monkeypatch) + event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.signalled_at is None + event.gate = True + event.set() + assert client_module._record_signal_before(event, deadline, deadline.end) is True + assert deadline.signalled_at is not None + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_verifies_a_backing_notification_from_the_supplied_flag( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class BackingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.backing = threading.Event() + self.is_set = threading.Event.is_set.__get__(self, threading.Event) + + def set(self) -> None: + self._flag = True + self.backing.set() + + clock = Clock(monkeypatch) + event = BackingEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, deadline) + + +async def test_async_future_watch_wakes_without_stopping_when_predicate_is_closed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.gate = False + + def is_set(self) -> bool: + return self.gate and super().is_set() + + clock = Clock(monkeypatch) + event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.signalled_at is None + event.gate = True + event.set() + await asyncio.sleep(0) + assert client_module._record_signal_before(event, deadline, deadline.end) is True + assert deadline.signalled_at is not None + finally: + client_module._unwatch_async_waiter(waiter, deadline) + + +async def test_async_binding_clears_for_a_native_waiter_registered_after_teardown() -> None: + event = asyncio.Event() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + first_native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + client_module._unwatch_async_waiter(sdk_waiter, deadline) + + second_native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + first_native.cancel() + with pytest.raises(asyncio.CancelledError): + await first_native + await wait_until(lambda: len(event._waiters) == 1) + + second_native.cancel() + with pytest.raises(asyncio.CancelledError): + await second_native + await wait_until( + lambda: event._loop is None and event not in client_module._async_loop_bindings + ) + assert not event._waiters + + +async def test_async_waiter_rolls_back_a_binding_created_by_a_failing_binder() -> None: + class BindingThenFailingEvent(asyncio.Event): + def _get_loop(self) -> None: + self._loop = asyncio.get_running_loop() + raise RuntimeError("bind failed") + + event = BindingThenFailingEvent() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + with pytest.raises(RuntimeError, match="different event loop"): + client_module._watch_async_waiter(event, deadline) + assert event._loop is None + assert event not in client_module._async_loop_bindings + + +@MODES +async def test_cancellable_wait_budget_starts_before_timeout_validation( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + class SlowTimeout: + def __float__(self) -> float: + clock.now += 2.0 + return 1.0 + + def __lt__(self, other: object) -> bool: + return float(self) < float(other) # type: ignore[arg-type] + + def __radd__(self, other: float) -> float: + return other + float(self) + + 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=SlowTimeout(), cancel_event=event + ) + assert server.requests == [] + assert result.status == "TIMED_OUT" From 9f3e7e4f2b9805b4b0c03405871f66078fe9f47a Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Mon, 30 Nov 2026 00:57:40 +0530 Subject: [PATCH 27/28] Address twenty-seventh Proofline review findings --- README.md | 2 +- proofline/client.py | 159 ++++++++++++------ tests/test_http.py | 400 ++++++++++++++++++++++++++++++++++++++------ 3 files changed, 451 insertions(+), 110 deletions(-) diff --git a/README.md b/README.md index 5275cee8..939dec9f 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` forwards to the standard predicate are supported for both event types: a timely `set()` followed by `clear()` is observed without the SDK calling that override. For a standard synchronous predicate, delivery is verified from the raw flag under the notification; an overridden synchronous predicate is checked after the condition lock is released, so it cannot deadlock that `set()` call. For `asyncio.Event`, native delivery wakes the wait and is recorded as cancellation only when the supplied predicate agrees. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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. +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` directly delegates to the standard predicate are supported for both event types: a timely `set()` followed by `clear()` is observed. For a standard or directly delegating synchronous predicate, delivery is verified from the raw flag under the notification; other overridden synchronous predicates are checked after the condition lock is released, so they cannot deadlock that `set()` call. For `asyncio.Event`, native delivery verifies the supplied predicate inline and records cancellation only when it agrees; a rejected pulse leaves the waiter pending for a later verified signal. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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 753ebefa..7249643a 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import dis import math import threading from asyncio import FIRST_COMPLETED @@ -248,15 +249,18 @@ def _verify_deferred_signals(deadline: _SignalDeadline, end: float) -> None: with _notify_lock: pending = tuple(deadline.pending) deadline.pending.clear() - for now, predicate in pending: + for _sampled, predicate in pending: + # An unverified backing wake is only a hint. If the predicate is true + # now, timestamp the check now rather than backdating the earlier wake. + checked = monotonic() try: verified = bool(predicate()) except Exception: verified = False with _notify_lock: - if verified: - deadline.record(now) - elif deadline.signalled_at is None and now < end: + if verified and checked < end: + deadline.record(checked) + elif deadline.signalled_at is None and checked < end: deadline.signal_event.set() @@ -316,16 +320,24 @@ def _event_attributes_snapshot(value: Any) -> tuple[Any, ...]: def _forwards_is_set(method: Any) -> bool: - """Whether a method only delegates to the inherited standard predicate.""" + """Whether a method directly returns the inherited standard predicate.""" function = getattr(method, "__func__", method) code = getattr(function, "__code__", None) - if code is None: + if code is None or code.co_names != ("super", "is_set") or code.co_consts != (None,): return False - return ( - code.co_names == ("super", "is_set") - and "__class__" in code.co_freevars - and "self" in code.co_varnames - ) + operations = [ + instruction.opname + for instruction in dis.get_instructions(code) + if instruction.opname not in {"COPY_FREE_VARS", "RESUME", "PRECALL", "CACHE", "NOP"} + ] + return operations == [ + "LOAD_GLOBAL", + "LOAD_DEREF", + "LOAD_FAST", + "LOAD_SUPER_ATTR", + "CALL", + "RETURN_VALUE", + ] def _event_has_standard_predicate(value: Any) -> bool: @@ -741,12 +753,7 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: - """Detach one deadline without ever unwinding a caller-owned hook. - - A tracker stays registered after its last subscriber leaves. Reusing it on - the next wait avoids stacking wrappers, and never restoring it avoids a - check-then-restore race with a caller that replaces the method. - """ + """Detach one deadline and restore SDK hooks when the last observer leaves.""" with _notify_lock: for condition in deadline.conditions: tracker = _notify_trackers.get(condition) @@ -754,6 +761,15 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> continue with tracker._subscription_lock: tracker.subscribers.pop(deadline, None) + empty = not tracker.subscribers + if empty and tracker._hooks_installed(): + # The tracker stays registered for reuse, but an idle wrapper + # must not keep acquiring SDK locks on later caller `set()`s. + # `_restore_method` leaves caller replacements untouched. + try: + tracker.restore() + except Exception: + pass deadline.conditions = () @@ -773,12 +789,15 @@ def _ordered_condition_locks( return tuple(sorted(locks.values(), key=id)) -def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> tuple[bool, float]: - """Install observers and sample the entry flag under the condition locks. +def _initial_sync_signal( + event: threading.Event, deadline: _SignalDeadline, entry_flag: bool, entry_time: float +) -> bool: + """Install observers and verify a flag first seen during setup. - Every distinct underlying lock is acquired once in identity order, so linked - conditions and conditions sharing one non-reentrant lock cannot deadlock - setup. An overridden predicate is read only after those locks are released. + The caller samples the entry flag before validation; this helper only + records signals first observed after observer setup, and bounds them by the + deadline derived from that original sample. Every distinct lock is acquired + once in identity order, and an overridden predicate is read after release. """ conditions = tuple(item[0] for item in _discover_thread_conditions(event)) standard_predicate = _event_has_standard_predicate(event) @@ -788,13 +807,14 @@ def _initial_sync_signal(event: threading.Event, deadline: _SignalDeadline) -> t _track_sync_cancel(event, deadline) sampled = monotonic() flagged = bool(getattr(event, "_flag", False)) - # A standard predicate cannot race the locked flag sample. An override is - # still consulted outside the locks so it cannot re-enter a held lock. - entry_set = flagged if standard_predicate else flagged and _thread_event_is_set(event) - if entry_set: - deadline.record_entry(sampled) + if entry_flag: + with _notify_lock: + deadline.record_entry(entry_time) + elif flagged and sampled < deadline.end: + if standard_predicate or _thread_event_is_set(event): + _publish_signals(((deadline, sampled),)) _drain_signals() - return bool(entry_set), sampled + return entry_flag def _untrack_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: @@ -907,6 +927,20 @@ def _async_flag_is_set(event: AsyncEvent) -> bool: return bool(getattr(event, "_value", getattr(event, "_flag", False))) +def _initial_async_signal( + event: AsyncEvent, deadline: _SignalDeadline, entry_flag: bool, entry_time: float +) -> bool: + """Record a flag first observed after validation against the entry deadline.""" + now = monotonic() + if entry_flag: + with _notify_lock: + deadline.record_entry(entry_time) + elif _async_flag_is_set(event) and now < deadline.end and _event_is_set(event): + _publish_signals(((deadline, now),)) + _drain_signals() + return entry_flag + + def _check_async_event_loop(event: asyncio.Event) -> None: """Reject foreign waiters before native registration can bind the event. @@ -925,12 +959,17 @@ def _check_async_event_loop(event: asyncio.Event) -> None: if binder is not None: try: binder() - except RuntimeError: + except BaseException as error: # A failing override may have bound the event before raising. Roll - # back only a binding it created here, never a preexisting one. + # back only a binding it created here, never a preexisting one, and + # preserve the original exception for non-loop failures. if event_loop is None and getattr(event, "_loop", None) is loop: event._loop = None # type: ignore[attr-defined] - raise RuntimeError("cancel_event is already bound to a different event loop.") from None + if isinstance(error, RuntimeError): + raise RuntimeError( + "cancel_event is already bound to a different event loop." + ) from None + raise class _AsyncSignalWatch: @@ -989,19 +1028,20 @@ def __init__( def set_result(result: Any) -> None: # asyncio.Event.set() completes watched futures without yielding. - # The first hook publishes once for all deadlines; later hooks - # only complete their own future. Verification never calls the - # event's overridable predicate from inside this dispatch. + # The first hook verifies the supplied predicate inline and + # publishes once for all deadlines. A rejected native pulse leaves + # the future pending so a later verified pulse can still complete it. if not _async_flag_is_set(event): return + verified = True if not self.signal.dispatch_done: - # Native delivery is evidence only when the supplied predicate - # agrees; an override that stays closed merely wakes the wait. if _event_is_set(event): self.signal.note(monotonic()) else: self.signal.defer(monotonic()) - self.original(result) + verified = False + if verified: + self.original(result) self.installed = set_result try: @@ -1180,11 +1220,11 @@ def _clear_temporary_async_binding(event: AsyncEvent, binding: _AsyncLoopBinding with _async_future_lock: if binding.count or _async_loop_bindings.get(event) is not binding: return - waiters = tuple( - pending for pending in getattr(event, "_waiters", None) or () if not pending.done() - ) + # A done future can still occupy the native waiter deque until its task + # resumes and removes it; ownership must survive that interval too. + waiters = tuple(getattr(event, "_waiters", None) or ()) if waiters: - _arm_native_waiter_cleanup(event, binding, waiters, recheck=False) + _arm_native_waiter_cleanup(event, binding, waiters, recheck=True) return _async_loop_bindings.discard(event, binding) if binding.owned and getattr(event, "_loop", None) is binding.loop: @@ -1201,9 +1241,7 @@ def _release_async_binding(waiter: _AsyncSignalWaiter) -> None: binding.count -= 1 if binding.count > 0: return - waiters = tuple( - pending for pending in getattr(event, "_waiters", None) or () if not pending.done() - ) + waiters = tuple(getattr(event, "_waiters", None) or ()) if waiters: _arm_native_waiter_cleanup(event, binding, waiters, recheck=True) return @@ -1785,14 +1823,17 @@ def wait_for_review( 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. A subclass whose ``is_set()`` forwards to the standard - predicate is supported because native delivery is latched from the raw - flag; an override that hides that flag is not. + next checkpoint. A subclass whose ``is_set()`` directly delegates to the + standard predicate is verified from the raw flag under the condition; + other overrides are checked after the lock is released. An override + that hides the event's flag is not supported. """ - # A cancellable wait's budget includes validation; sample its start - # before validating so a slow conversion cannot extend the deadline. + # A cancellable wait's budget and entry state are both sampled before + # validation, so a slow conversion cannot extend the deadline or turn a + # flag raised during validation into an entry cancellation. start = monotonic() if cancel_event is not None else None + entry_flag = _thread_event_is_set(cancel_event) if cancel_event is not None else False if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, threading.Event): @@ -1802,10 +1843,10 @@ def wait_for_review( deadline_set = False try: if cancel_event is not None: - initially_set, _ = _initial_sync_signal(cancel_event, read_signal) assert start is not None deadline_at = start + timeout read_signal.cap(deadline_at) + initially_set = _initial_sync_signal(cancel_event, read_signal, entry_flag, start) _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) else: @@ -1824,6 +1865,8 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: + if error.status in (401, 403): + raise cancelled = _cancellation_signal(cancel_event, read_signal) if _invalid_response(error) and cancelled: raise @@ -2240,11 +2283,15 @@ async def wait_for_review( before the early check or the first request. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so reuse on another loop - is possible only after both SDK and native waiters are gone. + is possible only after both SDK and native waiters are gone. Native + delivery verifies the supplied event's predicate inline; a rejected + pulse leaves the waiter pending for a later verified signal. """ - # A cancellable wait's budget includes validation; sample its start - # before validating so a slow conversion cannot extend the deadline. + # A cancellable wait's budget and entry state are both sampled before + # validation, so a slow conversion cannot extend the deadline or turn a + # flag raised during validation into an entry cancellation. start = monotonic() if cancel_event is not None else None + entry_flag = _event_is_set(cancel_event) if cancel_event is not None else False if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): @@ -2255,11 +2302,11 @@ async def wait_for_review( deadline_set = False try: if cancel_event is not None: - read_waiter = _watch_async_waiter(cancel_event, read_signal) - initially_set = _cancelled(cancel_event) assert start is not None deadline_at = start + timeout read_signal.cap(deadline_at) + read_waiter = _watch_async_waiter(cancel_event, read_signal) + initially_set = _initial_async_signal(cancel_event, read_signal, entry_flag, start) _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) else: @@ -2280,6 +2327,8 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: + if error.status in (401, 403): + raise cancelled = _cancellation_signal(cancel_event, read_signal) if _invalid_response(error) and cancelled: raise diff --git a/tests/test_http.py b/tests/test_http.py index f0519969..81cab06d 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -139,9 +139,11 @@ def __init__( self.owner = getattr(callback, "__self__", None) self.deadline = deadline self.cancelled = False + self.fired = False def fire(self) -> None: - if not self.cancelled: + if not self.cancelled and not self.fired: + self.fired = True self.callback(*self.args, **self.kwargs) def cancel(self) -> None: @@ -187,8 +189,9 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(client_module, "_async_wait_for_event", self.async_wait_for_event) def publish(self) -> None: - """Mark a cancellation as explicitly published at the current fake time.""" - self.publication_at = self.now + """Mark a cancellation as published, preserving the first pending time.""" + if self.publication_at is None: + self.publication_at = self.now self.publication.set() def reach_deadline(self) -> None: @@ -1542,8 +1545,11 @@ def unexpected_async_event_wait(*args: Any, **kwargs: Any) -> bool: assert len(server.requests) == 8 -async def wait_until(predicate: Any) -> None: +async def wait_until(predicate: Any, task: Any | None = None) -> None: for _ in range(200): + if task is not None and task.done(): + # Surface the original helper failure instead of a generic timeout. + await task if predicate(): return await asyncio.sleep(0) @@ -1559,7 +1565,7 @@ async def test_async_wait_for_event_latches_a_set_then_clear( event = asyncio.Event() task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) clock.now = 100.5 event.set() event.clear() @@ -1582,7 +1588,7 @@ async def test_async_wait_for_event_ignores_a_signal_after_cutoff( timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) task = asyncio.create_task(real_wait(event, cutoff)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) cutoff_future = timers[0].owner assert isinstance(cutoff_future, asyncio.Future) assert cutoff_future not in event._waiters @@ -1608,7 +1614,7 @@ async def test_async_wait_for_event_latches_a_captured_setter_on_the_waiter_futu setter = event.set task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) clock.now = 100.5 setter() assert await asyncio.wait_for(task, 1.0) is True @@ -1632,7 +1638,7 @@ class InheritedEvent(asyncio.Event): event = InheritedEvent() task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) clock.now = 100.5 event.set() assert await asyncio.wait_for(task, 1.0) is True @@ -1662,7 +1668,7 @@ async def wait(self) -> bool: event = CountingEvent() task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) clock.now = 100.5 event.set() assert await asyncio.wait_for(task, 1.0) is True @@ -1690,7 +1696,7 @@ async def wait_override() -> bool: event.wait = wait_override # type: ignore[method-assign] task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) clock.now = 100.5 event.set() assert await asyncio.wait_for(task, 1.0) is True @@ -1714,7 +1720,7 @@ async def test_async_wait_for_event_overlapping_waits_keep_both_waiters( first = asyncio.create_task(real_wait(event, short_cutoff)) second = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: len(event._waiters) >= 2) + await wait_until(lambda: len(event._waiters) >= 2, first) timers[0].fire() assert await asyncio.wait_for(first, 1.0) is False assert event.set == setter @@ -1742,7 +1748,7 @@ async def test_async_wait_for_event_restores_the_waiter_without_touching_the_set setter = event.set task = asyncio.create_task(real_wait(event, cutoff)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) future = next(iter(event._waiters)) timers[0].fire() assert await asyncio.wait_for(task, 1.0) is False @@ -1895,7 +1901,7 @@ def set(self) -> Any: event = ReadOnlySetEvent() task = asyncio.create_task(real_wait(event, clock.now + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) clock.now = 100.5 event.set() assert await asyncio.wait_for(task, 1.0) is True @@ -1928,7 +1934,7 @@ def set(self) -> None: timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) task = asyncio.create_task(real_wait(event, cutoff)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) event.set() assert event.is_set() timers[0].fire() @@ -1973,7 +1979,7 @@ def replacement() -> None: event.set = replacement # type: ignore[method-assign] task = asyncio.create_task(real_wait(event, cutoff)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) timers[0].fire() assert await asyncio.wait_for(task, 1.0) is False assert event.set is replacement @@ -2021,7 +2027,7 @@ def raise_on_restore(watch: Any) -> None: monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", raise_on_restore) task = asyncio.create_task(client_module._async_wait_for_event(event, cutoff)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) future = next(iter(event._waiters)) timers[0].fire() with pytest.raises(RuntimeError, match="restore failed"): @@ -2223,7 +2229,7 @@ async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: setter = event.set task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) try: - await wait_until(lambda: bool(event._waiters)) + await wait_until(lambda: bool(event._waiters), task) assert event.set == setter finally: task.cancel() @@ -2231,18 +2237,49 @@ async def test_async_wait_for_event_does_not_replace_the_event_setter() -> None: assert not event._waiters -async def test_async_wait_for_event_propagates_external_cancellation() -> None: +def test_async_wait_for_event_propagates_external_cancellation() -> None: + # A cleanup lockup must be terminated by the parent test. + code = """ +import asyncio +import sys +import time + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +async def main(): event = asyncio.Event() - task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) - try: - await wait_until(lambda: bool(event._waiters)) - assert len(event._waiters) == 1 - task.cancel() - with pytest.raises(asyncio.CancelledError): + task = asyncio.create_task(client._async_wait_for_event(event, time.monotonic() + 10.0)) + for _ in range(200): + if task.done(): await task - finally: - await asyncio.gather(task, return_exceptions=True) + if event._waiters: + break + await asyncio.sleep(0) + else: + raise AssertionError("the helper never registered a waiter") + assert len(event._waiters) == 1 + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + else: + raise AssertionError("external cancellation was not propagated") assert not event._waiters + print("OK") + +asyncio.run(main()) +""" + 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_returns_true_at_deadline_without_a_signal( @@ -2307,6 +2344,7 @@ def test_sleep_with_cancel_records_a_set_clear_before_wait_registration( event = threading.Event() condition = event._cond original_notify_all = condition.notify_all + original_notify = condition.notify setter = event.set def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: @@ -2320,8 +2358,10 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False tracker = client_module._notify_trackers[condition] assert event.set == setter - assert condition.notify_all is tracker.installed_notify_all - assert condition.notify is tracker.installed_notify + # The tracker stays cached for reuse, but its hooks are restored when the + # last observer leaves so later caller `set()` calls never take SDK locks. + assert condition.notify_all == original_notify_all + assert condition.notify == original_notify assert tracker.original_notify_all == original_notify_all assert tracker.subscribers == {} assert clock.delays == [] @@ -2359,8 +2399,8 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False tracker = client_module._notify_trackers[condition] assert clock.delays == [] - assert condition.notify_all is tracker.installed_notify_all - assert condition.notify is tracker.installed_notify + assert condition.notify_all.__func__ is tracker.original_notify_all.__func__ + assert condition.notify.__func__ is tracker.original_notify.__func__ assert tracker.subscribers == {} @@ -2420,7 +2460,7 @@ def wait(self, timeout: float | None = None) -> bool: notify_all = condition.notify_all assert client_module._sleep_with_cancel(0, event) is True tracker = client_module._notify_trackers[condition] - assert condition.notify_all is tracker.installed_notify_all + assert condition.notify_all == notify_all assert tracker.original_notify_all == notify_all assert "set" not in vars(event) @@ -2502,7 +2542,7 @@ def signal(): assert event.primary_notifications == 0 backing_condition = event.backing._cond tracker = t.client_module._notify_trackers[backing_condition] -assert backing_condition.notify_all is tracker.installed_notify_all +assert backing_condition.notify_all == tracker.original_notify_all assert tracker.subscribers == {} print("OK") """ @@ -2540,8 +2580,8 @@ def __init__(self) -> None: condition = event._cond assert client_module._sleep_with_cancel(0, event) is True tracker = client_module._notify_trackers[condition] - assert condition.notify_all is tracker.installed_notify_all - assert condition.notify is tracker.installed_notify + assert condition.notify_all.__func__ is ClassCondition.notify_all + assert condition.notify.__func__ is ClassCondition.notify assert tracker.original_notify_all.__func__ is ClassCondition.notify_all assert tracker.original_notify.__func__ is ClassCondition.notify assert tracker.subscribers == {} @@ -2563,7 +2603,7 @@ def notify_all() -> None: assert client_module._sleep_with_cancel(0, event) is True tracker = client_module._notify_trackers[condition] assert tracker.saved_notify_all is notify_all - assert condition.notify_all is tracker.installed_notify_all + assert condition.notify_all is notify_all def test_sleep_with_cancel_ignores_a_nested_marker_event( @@ -2593,9 +2633,12 @@ def test_sleep_with_cancel_does_not_call_is_set_under_the_condition( monkeypatch.setattr(client_module, "_wait_for_event", real_wait) held = False + calls = 0 class ReentrantEvent(threading.Event): def is_set(self) -> bool: + nonlocal calls + calls += 1 assert not held, "is_set called under the condition" return bool(self._flag) @@ -2603,6 +2646,10 @@ def is_set(self) -> bool: def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: nonlocal held + # The inherited setter establishes a true raw flag. Then notify again + # while the condition is held, so the tracker must take the true-flag + # branch without calling an overridden predicate under that lock. + threading.Event.set(wait_event) with wait_event._cond: held = True try: @@ -2614,6 +2661,7 @@ 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 True + assert calls > 0 def test_sleep_with_cancel_does_not_wrap_a_replaced_backing_condition( @@ -2645,7 +2693,7 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert client_module._sleep_with_cancel(5, event, cutoff=101.0) is False original_tracker = client_module._notify_trackers[original_condition] assert clock.delays == [] - assert original_condition.notify_all is original_tracker.installed_notify_all + assert original_condition.notify_all == original_tracker.original_notify_all assert "notify_all" not in vars(event.backing._cond) @@ -2851,21 +2899,25 @@ def track(event_arg, deadline): t.client_module._track_sync_cancel = track +published = [] + + def set_later(): if not ready.wait(2.0): event.set() return + published.append(time.monotonic()) 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 published +assert time.monotonic() - published[0] < 2.0 assert ready.is_set() assert len(server.requests) == 1 assert result.status == "STOPPED" @@ -2927,12 +2979,14 @@ async def wait_for_waiters(): t.client_module._async_wait_for_event = async_wait + published = [] + async def set_later(): await asyncio.wait_for(ready.wait(), 2.0) + published.append(time.monotonic()) event.set() setter = asyncio.create_task(set_later()) - started = time.monotonic() verified = False try: with t.Server(lambda request, index: t.Reply(body=body)) as server: @@ -2940,7 +2994,8 @@ async def set_later(): result = await t.call( client, "wait_for_review", t.ORG, t.REVIEW, timeout=5, cancel_event=event ) - assert time.monotonic() - started < 2.0 + assert published + assert time.monotonic() - published[0] < 2.0 assert ready.is_set() assert len(server.requests) == 1 assert result.status == "STOPPED" @@ -3054,6 +3109,29 @@ def respond(request: Request, index: int) -> Reply: assert len(server.requests) == 1 +@MODES +@pytest.mark.parametrize("status", [401, 403]) +async def test_wait_for_review_timely_cancellation_keeps_auth_read_error( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + clock.now += 101.0 + raise ProoflineError(status, "urn:proofline:sdk:test", "denied") + + 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(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) + assert raised.value.status == status + assert len(server.requests) == 0 + assert event.is_set() + + @MODES async def test_wait_for_review_invalid_response_after_deadline_keeps_timeout( mode: str, monkeypatch: pytest.MonkeyPatch @@ -3082,6 +3160,28 @@ def get_review(*args: Any, **kwargs: Any) -> Any: assert event.is_set() +@MODES +async def test_wait_for_review_timely_cancellation_keeps_invalid_response_error( + 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: + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + clock.now += 101.0 + 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 + assert event.is_set() + + @MODES async def test_wait_for_review_late_cancellation_after_read_keeps_timeout( mode: str, monkeypatch: pytest.MonkeyPatch @@ -4870,7 +4970,7 @@ def test_condition_tracker_samples_time_before_the_publication_lock( class AdvancingLock: def __enter__(self) -> Any: - clock.now = 101.5 + clock.now = 111.0 return self def __exit__(self, *args: Any) -> bool: @@ -5103,11 +5203,11 @@ async def main(): deadline = client._SignalDeadline(time.monotonic() + 10.0) try: waiter = client._watch_async_waiter(event, deadline) - results.append("registered") + results.append((threading.get_ident(), "registered")) assert second_done.wait(5.0) client._unwatch_async_waiter(waiter, deadline) except RuntimeError: - results.append("rejected") + results.append((threading.get_ident(), "rejected")) second_done.set() finally: registered.set() @@ -5133,7 +5233,11 @@ async def main(): for thread in threads: thread.join(5.0) assert not any(thread.is_alive() for thread in threads) -assert sorted(results) == ["registered", "rejected"] +by_ident = dict(results) +assert by_ident.get(paused_ident[0]) == "registered" +contenders = [ident for ident in by_ident if ident != paused_ident[0]] +assert len(contenders) == 1 +assert by_ident[contenders[0]] == "rejected" assert not event._waiters assert event not in client._async_loop_bindings assert id(event) not in client._async_signal_watches @@ -5188,7 +5292,7 @@ def __exit__(self, *args: Any) -> bool: client_module._untrack_thread_signal(event, deadline) -def test_condition_tracker_keeps_one_reusable_hook_after_teardown( +def test_condition_tracker_restores_idle_hooks_and_reuses_the_tracker( monkeypatch: pytest.MonkeyPatch, ) -> None: event = threading.Event() @@ -5196,26 +5300,59 @@ def test_condition_tracker_keeps_one_reusable_hook_after_teardown( first = client_module._SignalDeadline(time.monotonic() + 10.0) second = client_module._SignalDeadline(time.monotonic() + 10.0) attempts: list[tuple[Any, ...]] = [] + real_restore = client_module._restore_method - def forbid_restore(*args: Any) -> None: + def record_restore(*args: Any) -> None: attempts.append(args) - raise AssertionError("teardown must not unwind a caller-owned hook") + real_restore(*args) - monkeypatch.setattr(client_module, "_restore_method", forbid_restore) + monkeypatch.setattr(client_module, "_restore_method", record_restore) client_module._track_thread_signal(event, first) tracker = client_module._notify_trackers[condition] - installed = tracker.installed_notify_all + first_installed = tracker.installed_notify_all try: client_module._untrack_thread_signal(event, first) + assert len(attempts) == 2 + assert condition.notify_all.__func__ is tracker.original_notify_all.__func__ + assert condition.notify.__func__ is tracker.original_notify.__func__ client_module._track_thread_signal(event, second) assert client_module._notify_trackers[condition] is tracker - assert condition.notify_all is installed - assert condition.notify is tracker.installed_notify assert set(tracker.subscribers) == {second} + assert condition.notify_all is tracker.installed_notify_all + assert tracker.installed_notify_all is not first_installed + assert condition.notify is tracker.installed_notify finally: client_module._untrack_thread_signal(event, second) assert tracker.subscribers == {} - assert attempts == [] + assert len(attempts) == 4 + + +def test_condition_tracker_restore_preserves_a_caller_replacement( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = threading.Event() + condition = event._cond + first = client_module._SignalDeadline(time.monotonic() + 10.0) + client_module._track_thread_signal(event, first) + client_module._untrack_thread_signal(event, first) + + def replacement_all(*args: Any, **kwargs: Any) -> None: + return None + + def replacement_notify(*args: Any, **kwargs: Any) -> None: + return None + + condition.notify_all = replacement_all # type: ignore[method-assign] + condition.notify = replacement_notify # type: ignore[method-assign] + second = client_module._SignalDeadline(time.monotonic() + 10.0) + client_module._track_thread_signal(event, second) + try: + assert condition.notify_all is not replacement_all + assert condition.notify is not replacement_notify + finally: + client_module._untrack_thread_signal(event, second) + assert condition.notify_all is replacement_all + assert condition.notify is replacement_notify async def test_async_event_set_publishes_once_for_all_watched_waiters( @@ -5370,6 +5507,39 @@ async def test_wait_for_review_timeout_zero_honors_an_event_set_at_entry(mode: s assert result.reason == "The wait was cancelled by the caller." +@MODES +async def test_wait_for_review_timeout_validation_signal_does_not_become_entry_state( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + class ValidationTimeout: + def __float__(self) -> float: + event.set() + return 0.0 + + def __lt__(self, other: float) -> bool: + return float(self) < other + + def __radd__(self, other: float) -> float: + return other + float(self) + + 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=ValidationTimeout(), # type: ignore[arg-type] + cancel_event=event, + ) + assert server.requests == [] + assert result.status == "TIMED_OUT" + assert event.is_set() + + def test_condition_tracker_registry_does_not_retain_discarded_events() -> None: event = threading.Event() deadline = client_module._SignalDeadline(101.0) @@ -5467,7 +5637,7 @@ def run(event): try: barrier.wait(5.0) deadline = client._SignalDeadline(time.monotonic() + 5.0) - client._initial_sync_signal(event, deadline) + client._initial_sync_signal(event, deadline, False, time.monotonic()) client._untrack_sync_cancel(event, deadline) except BaseException as error: errors.append(repr(error)) @@ -5516,7 +5686,7 @@ def test_initial_sync_signal_uses_a_shared_non_reentrant_lock_once() -> None: second._cond = threading.Condition(lock) first.backing = second deadline = client._SignalDeadline(time.monotonic() + 5.0) -client._initial_sync_signal(first, deadline) +client._initial_sync_signal(first, deadline, False, time.monotonic()) client._untrack_sync_cancel(first, deadline) print("OK") """ @@ -5596,6 +5766,28 @@ def is_set(self) -> bool: client_module._untrack_thread_signal(event, deadline) +def test_condition_tracker_rejects_a_call_then_false_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class HiddenEvent(threading.Event): + def is_set(self) -> bool: + super().is_set() + return False + + clock = Clock(monkeypatch) + event = HiddenEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert not event.is_set() + assert deadline.signalled_at is None + finally: + client_module._untrack_thread_signal(event, deadline) + + def test_condition_tracker_rewraps_replaced_hooks_before_reuse( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -5796,6 +5988,35 @@ async def test_clock_async_wait_uses_an_explicit_deadline_gate( assert await clock.async_wait_for_event(event, signal.end, signal) is True assert signal.signalled_at == 100.1 + event.clear() + event.set() + clock.now = 100.2 + signal = client_module._SignalDeadline(clock.now + 10.0) + clock.publish() + clock.now = 120.0 + clock.publish() + assert await clock.async_wait_for_event(event, signal.end, signal) is True + assert signal.signalled_at == 100.2 + + +async def test_manual_timer_is_one_shot( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + event = asyncio.Event() + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + task = asyncio.create_task(real_wait(event, cutoff, client_module._SignalDeadline(cutoff))) + try: + await wait_until(lambda: bool(event._waiters), task) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + timers[0].fire() + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + def test_condition_tracker_rehook_preserves_a_captured_wrapper_delegate( monkeypatch: pytest.MonkeyPatch, @@ -5886,6 +6107,35 @@ def is_set(self) -> bool: client_module._untrack_thread_signal(event, deadline) +def test_deferred_predicate_does_not_backdate_a_late_signal( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.gate = False + + def is_set(self) -> bool: + return self.gate and super().is_set() + + clock = Clock(monkeypatch) + event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.pending + clock.now = 111.0 + event.gate = True + event.set() + client_module._verify_deferred_signals(deadline, deadline.end) + assert deadline.signalled_at is None + finally: + client_module._untrack_thread_signal(event, deadline) + + def test_condition_tracker_verifies_a_backing_notification_from_the_supplied_flag( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -5927,14 +6177,19 @@ def is_set(self) -> bool: 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.5 event.set() event.clear() assert deadline.signalled_at is None + assert not future.done() + assert any(future is pending for pending in event._waiters) event.gate = True event.set() await asyncio.sleep(0) + assert future.done() assert client_module._record_signal_before(event, deadline, deadline.end) is True assert deadline.signalled_at is not None finally: @@ -5979,6 +6234,43 @@ def _get_loop(self) -> None: assert event not in client_module._async_loop_bindings +async def test_async_waiter_rolls_back_other_binder_failures() -> None: + class BindingThenFailingEvent(asyncio.Event): + def _get_loop(self) -> None: + self._loop = asyncio.get_running_loop() + raise ValueError("bind failed") + + event = BindingThenFailingEvent() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + with pytest.raises(ValueError, match="bind failed"): + client_module._watch_async_waiter(event, deadline) + assert event._loop is None + assert event not in client_module._async_loop_bindings + + +async def test_async_binding_survives_a_done_native_future_still_registered() -> None: + loop = asyncio.get_running_loop() + event = asyncio.Event() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + binding = client_module._async_loop_bindings.get(event) + assert binding is not None + native = loop.create_future() + event._waiters.append(native) # type: ignore[arg-type] + try: + client_module._unwatch_async_waiter(sdk_waiter, deadline) + native.set_result(True) + await asyncio.sleep(0) + assert event in client_module._async_loop_bindings + event._waiters.remove(native) # type: ignore[arg-type] + client_module._clear_temporary_async_binding(event, binding) + assert event not in client_module._async_loop_bindings + finally: + if native in event._waiters: # type: ignore[operator] + event._waiters.remove(native) # type: ignore[arg-type] + client_module._clear_temporary_async_binding(event, binding) + + @MODES async def test_cancellable_wait_budget_starts_before_timeout_validation( mode: str, monkeypatch: pytest.MonkeyPatch From c0772d8ed72367a894e15919643166c8260777c2 Mon Sep 17 00:00:00 2001 From: karan nagpal Date: Thu, 3 Dec 2026 17:09:04 +0530 Subject: [PATCH 28/28] Address twenty-eighth Proofline review findings --- README.md | 2 +- proofline/client.py | 182 ++++++++++++-------- tests/test_http.py | 402 +++++++++++++++++++++++++++----------------- 3 files changed, 357 insertions(+), 229 deletions(-) diff --git a/README.md b/README.md index 939dec9f..445f5927 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,7 @@ outcome = await async_client.wait_for_review( # From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) ``` -An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` directly delegates to the standard predicate are supported for both event types: a timely `set()` followed by `clear()` is observed. For a standard or directly delegating synchronous predicate, delivery is verified from the raw flag under the notification; other overridden synchronous predicates are checked after the condition lock is released, so they cannot deadlock that `set()` call. For `asyncio.Event`, native delivery verifies the supplied predicate inline and records cancellation only when it agrees; a rejected pulse leaves the waiter pending for a later verified signal. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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. +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. 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()` while observation is active and before the deadline 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. Subclasses whose `is_set()` directly delegates to the standard predicate are supported for both event types: a timely `set()` followed by `clear()` is observed. For a standard or directly delegating synchronous predicate, delivery is verified from the raw flag under the notification; other overridden synchronous predicates are checked after the condition lock is released, so they cannot deadlock that `set()` call. For `asyncio.Event`, native delivery verifies the supplied predicate inline and records cancellation only when it agrees; a rejected pulse leaves the waiter pending for a later verified signal. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is 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. HTTP 401 and 403 responses are not converted to `STOPPED`: even after a timely cancellation they still propagate to the caller. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 7249643a..d0013fc8 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -14,7 +14,6 @@ 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 @@ -250,13 +249,14 @@ def _verify_deferred_signals(deadline: _SignalDeadline, end: float) -> None: pending = tuple(deadline.pending) deadline.pending.clear() for _sampled, predicate in pending: - # An unverified backing wake is only a hint. If the predicate is true - # now, timestamp the check now rather than backdating the earlier wake. - checked = monotonic() + # An unverified backing wake is only a hint. Timestamp the check after + # the predicate returns, so a predicate that blocks across the deadline + # cannot make a late cancellation look early. try: verified = bool(predicate()) except Exception: verified = False + checked = monotonic() with _notify_lock: if verified and checked < end: deadline.record(checked) @@ -515,9 +515,10 @@ def __init__(self, condition: threading.Condition) -> None: self.saved_notify: Any = attributes.get("notify") self.original_notify_all = _weak_bound_method(condition.notify_all) self.original_notify = _weak_bound_method(condition.notify) - # (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]] = {} + # deadline -> entries of (event whose raw flag proves the signal, whether + # it is a backing event, the event supplied by the caller). One deadline + # can watch several backing events that share the same condition. + self.subscribers: dict[_SignalDeadline, list[tuple[Any, bool, Any]]] = {} self._subscription_lock = threading.Lock() # Condition.notify_all() delegates to notify(); publish only once for # the outer dispatch so a subscriber added while an override delegates @@ -639,7 +640,11 @@ def record(self) -> None: # a subscriber registered during this dispatch cannot receive its time. with self._subscription_lock: now = monotonic() - subscribers = tuple(self.subscribers.items()) + subscribers = tuple( + (deadline, entry) + for deadline, entries in self.subscribers.items() + for entry in entries + ) staged: list[tuple[_SignalDeadline, float, _Verification]] = [] for deadline, (watched, backing, caller) in subscribers: if not bool(getattr(watched, "_flag", False)): @@ -703,26 +708,26 @@ def restore(self) -> None: def _discover_thread_conditions( event: threading.Event, ) -> tuple[tuple[threading.Condition, Any, bool], ...]: - """Snapshot the conditions reachable from an event's own attributes.""" + """Snapshot the conditions reachable from an event's own attributes. + + Backing events are retained even when they share the supplied event's + condition: the condition only needs one hook, but each exposed event's raw + flag can independently prove a notification. + """ with _sync_set_lock: attributes = tuple(_instance_attributes(event).values()) own_condition = getattr(event, "_cond", None) watched: list[tuple[threading.Condition, Any, bool]] = [] - seen: set[int] = set() + seen_events: set[int] = {id(event)} 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 - ) - if ( - value is event - or not isinstance(backing_condition, threading.Condition) - or id(backing_condition) in seen - ): + if not isinstance(value, threading.Event) or id(value) in seen_events: continue - seen.add(id(backing_condition)) + backing_condition = getattr(value, "_cond", None) + if not isinstance(backing_condition, threading.Condition): + continue + seen_events.add(id(value)) watched.append((backing_condition, value, True)) return tuple(watched) @@ -730,8 +735,11 @@ def _discover_thread_conditions( 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) - added: list[_ConditionSignalTracker] = [] + conditions: dict[int, threading.Condition] = {} + for tracked, _watched_event, _backing in watched: + conditions.setdefault(id(tracked), tracked) + deadline.conditions = tuple(conditions.values()) + added: list[tuple[_ConditionSignalTracker, tuple[Any, bool, Any]]] = [] with _notify_lock: try: for tracked, watched_event, backing in watched: @@ -741,13 +749,18 @@ def _track_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> _ _notify_trackers[tracked] = tracker elif not tracker._hooks_installed(): tracker._rehook() + entry = (watched_event, backing, event) with tracker._subscription_lock: - tracker.subscribers[deadline] = (watched_event, backing, event) - added.append(tracker) + tracker.subscribers.setdefault(deadline, []).append(entry) + added.append((tracker, entry)) except BaseException: - for tracker in added: + for tracker, entry in added: with tracker._subscription_lock: - tracker.subscribers.pop(deadline, None) + entries = tracker.subscribers.get(deadline) + if entries is not None: + entries[:] = [item for item in entries if item is not entry] + if not entries: + tracker.subscribers.pop(deadline, None) raise return deadline @@ -762,10 +775,11 @@ def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> with tracker._subscription_lock: tracker.subscribers.pop(deadline, None) empty = not tracker.subscribers - if empty and tracker._hooks_installed(): + if empty: # The tracker stays registered for reuse, but an idle wrapper # must not keep acquiring SDK locks on later caller `set()`s. - # `_restore_method` leaves caller replacements untouched. + # `_restore_method` restores each still-owned hook independently + # and leaves caller replacements untouched. try: tracker.restore() except Exception: @@ -778,17 +792,6 @@ def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> Non _track_thread_signal(event, deadline) -def _ordered_condition_locks( - conditions: tuple[threading.Condition, ...], -) -> tuple[Any, ...]: - """Dedupe shared locks and return one stable acquisition order.""" - locks: dict[int, Any] = {} - for condition in conditions: - lock = getattr(condition, "_lock", condition) - locks.setdefault(id(lock), lock) - return tuple(sorted(locks.values(), key=id)) - - def _initial_sync_signal( event: threading.Event, deadline: _SignalDeadline, entry_flag: bool, entry_time: float ) -> bool: @@ -796,17 +799,14 @@ def _initial_sync_signal( The caller samples the entry flag before validation; this helper only records signals first observed after observer setup, and bounds them by the - deadline derived from that original sample. Every distinct lock is acquired - once in identity order, and an overridden predicate is read after release. + deadline derived from that original sample. Observers are registered without + holding any caller-owned condition lock, so a setter that holds its own lock + while forwarding to a backing event cannot deadlock setup. """ - conditions = tuple(item[0] for item in _discover_thread_conditions(event)) standard_predicate = _event_has_standard_predicate(event) - with ExitStack() as stack: - for lock in _ordered_condition_locks(conditions): - stack.enter_context(lock) - _track_sync_cancel(event, deadline) - sampled = monotonic() - flagged = bool(getattr(event, "_flag", False)) + _track_sync_cancel(event, deadline) + sampled = monotonic() + flagged = bool(getattr(event, "_flag", False)) if entry_flag: with _notify_lock: deadline.record_entry(entry_time) @@ -979,7 +979,22 @@ def __init__(self, event: AsyncEvent) -> None: self.event = event self.deadlines: set[_SignalDeadline] = set() self.counts: dict[_SignalDeadline, int] = {} - self.dispatch_done = False + # One predicate verification per set() dispatch. The first future a + # dispatch visits starts the generation; seeing a future again means a + # back-to-back pulse began, so the predicate must be re-evaluated. + self.verification: bool | None = None + self.dispatch_seen: set[int] = set() + + def begin_dispatch(self, future: AsyncFuture[Any]) -> None: + key = id(future) + if key in self.dispatch_seen: + self.dispatch_seen.clear() + self.verification = None + self.dispatch_seen.add(key) + + def reset_dispatch(self) -> None: + self.dispatch_seen.clear() + self.verification = None def add(self, deadline: _SignalDeadline) -> None: self.counts[deadline] = self.counts.get(deadline, 0) + 1 @@ -996,12 +1011,12 @@ def remove(self, deadline: _SignalDeadline) -> bool: return False def note(self, now: float) -> None: - # The caller has already checked the O(1) dispatch latch. Publishing is - # bounded by the number of deadlines, never by the waiter deque. + # The caller has already checked this dispatch's verification cache. + # Publishing is bounded by the number of deadlines, never by the waiter + # deque or by another pending future in the same dispatch. with _async_future_lock: deadlines = tuple(self.deadlines) _publish_signals(tuple((deadline, now) for deadline in deadlines)) - self.dispatch_done = True def defer(self, now: float) -> None: """Wake watchers without treating an overridden predicate as evidence.""" @@ -1028,19 +1043,21 @@ def __init__( def set_result(result: Any) -> None: # asyncio.Event.set() completes watched futures without yielding. - # The first hook verifies the supplied predicate inline and - # publishes once for all deadlines. A rejected native pulse leaves - # the future pending so a later verified pulse can still complete it. + # The first future in a dispatch verifies the supplied predicate and + # publishes once for all deadlines; later futures reuse that result. + # A rejected native pulse leaves the future pending so a later + # verified pulse can still complete it. if not _async_flag_is_set(event): return - verified = True - if not self.signal.dispatch_done: + self.signal.begin_dispatch(self.future) + if self.signal.verification is None: if _event_is_set(event): self.signal.note(monotonic()) + self.signal.verification = True else: self.signal.defer(monotonic()) - verified = False - if verified: + self.signal.verification = False + if self.signal.verification: self.original(result) self.installed = set_result @@ -1091,7 +1108,7 @@ def _watch_async_future( raise # Registration happens outside a set() dispatch, so it starts a new # publication generation. No overridable predicate is consulted here. - signal.dispatch_done = False + signal.reset_dispatch() if owns_signal: _async_signal_watches[id(event)] = signal @@ -1195,8 +1212,14 @@ def _arm_native_waiter_cleanup( *, recheck: bool, ) -> None: - """Watch each pending native waiter, including ones added after teardown.""" + """Watch each pending native waiter, including ones added after teardown. + + Pending futures wake cleanup through their completion callbacks. Only + already-completed futures that still occupy the waiter deque need an + immediate retry, so an unset event never causes per-turn rescheduling. + """ binding.cleanup_armed = True + completed = False for pending in waiters: key = id(pending) if key in binding.watched: @@ -1211,7 +1234,10 @@ def done(_: Any, key: int = key) -> None: pending.add_done_callback(done) except Exception: binding.watched.discard(key) - if recheck: + continue + if pending.done(): + completed = True + if recheck and completed: _schedule_binding_recheck(event, binding) @@ -1831,22 +1857,28 @@ def wait_for_review( # A cancellable wait's budget and entry state are both sampled before # validation, so a slow conversion cannot extend the deadline or turn a - # flag raised during validation into an entry cancellation. + # flag raised during validation into an entry cancellation. Observers are + # installed before that conversion and arithmetic so a set()/clear() + # during either one is still latched. start = monotonic() if cancel_event is not None else None - entry_flag = _thread_event_is_set(cancel_event) if cancel_event is not None else False - if not math.isfinite(timeout) or timeout < 0: - raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, threading.Event): raise TypeError("cancel_event must be a threading.Event.") + entry_flag = _thread_event_is_set(cancel_event) if cancel_event is not None else False read_signal = _SignalDeadline(float("inf")) initially_set = False deadline_set = False try: + if cancel_event is not None: + assert start is not None + initially_set = _initial_sync_signal(cancel_event, read_signal, entry_flag, start) + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The review timeout must be a finite nonnegative number of seconds." + ) if cancel_event is not None: assert start is not None deadline_at = start + timeout read_signal.cap(deadline_at) - initially_set = _initial_sync_signal(cancel_event, read_signal, entry_flag, start) _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) else: @@ -2289,23 +2321,29 @@ async def wait_for_review( """ # A cancellable wait's budget and entry state are both sampled before # validation, so a slow conversion cannot extend the deadline or turn a - # flag raised during validation into an entry cancellation. + # flag raised during validation into an entry cancellation. Observers are + # installed before that conversion and arithmetic so a set()/clear() + # during either one is still latched. start = monotonic() if cancel_event is not None else None - entry_flag = _event_is_set(cancel_event) if cancel_event is not None else False - if not math.isfinite(timeout) or timeout < 0: - raise ValueError("The review timeout must be a finite nonnegative number of seconds.") if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): raise TypeError("cancel_event must be an asyncio.Event.") + entry_flag = _event_is_set(cancel_event) if cancel_event is not None else False read_signal = _SignalDeadline(float("inf")) read_waiter = _AsyncSignalWaiter() initially_set = False deadline_set = False try: + if cancel_event is not None: + assert start is not None + read_waiter = _watch_async_waiter(cancel_event, read_signal) + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The review timeout must be a finite nonnegative number of seconds." + ) if cancel_event is not None: assert start is not None deadline_at = start + timeout read_signal.cap(deadline_at) - read_waiter = _watch_async_waiter(cancel_event, read_signal) initially_set = _initial_async_signal(cancel_event, read_signal, entry_flag, start) _head_commit(head_commit_sha) url = _review_url(self._base_url, organization_id, review_id) diff --git a/tests/test_http.py b/tests/test_http.py index 81cab06d..909603ed 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -114,13 +114,30 @@ async def wait_for_all(aws: Any, **kwargs: Any) -> Any: 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: - if check: + """Reap a signal task without masking the probe's own failure. + + An expected cancellation is ignored; any other sender error is printed so + its traceback survives, and only raised when the probe itself succeeded. + """ + failure: BaseException | None = None + if check: + try: await asyncio.wait_for(sender, 1.0) - finally: - sender.cancel() - await asyncio.gather(sender, return_exceptions=True) + except BaseException as error: + failure = error + sender.cancel() + results = await asyncio.gather(sender, return_exceptions=True) + for outcome in results: + if isinstance(outcome, BaseException) and not isinstance(outcome, asyncio.CancelledError): + if outcome is not failure: + print("unexpected sender error:", file=sys.stderr) + traceback.print_exception( + type(outcome), outcome, outcome.__traceback__, file=sys.stderr + ) + if failure is None and check: + failure = outcome + if failure is not None: + raise failure class ManualTimer: @@ -1556,26 +1573,46 @@ async def wait_until(predicate: Any, task: Any | None = None) -> None: 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) - timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) +def test_async_wait_for_event_latches_a_set_then_clear() -> None: + # A helper that stops responding to cancellation must not hang pytest. + code = """ +import asyncio +import sys + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +async def main(): + now = [100.0] + client.monotonic = lambda: now[0] event = asyncio.Event() - task = asyncio.create_task(real_wait(event, clock.now + 10.0)) - try: - await wait_until(lambda: bool(event._waiters), task) - 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: - task.cancel() - await asyncio.gather(task, return_exceptions=True) - for timer in timers: - timer.cancel() + task = asyncio.create_task(client._async_wait_for_event(event, 110.0)) + for _ in range(200): + if task.done(): + await task + if event._waiters: + break + await asyncio.sleep(0) + else: + raise AssertionError("the helper never registered a waiter") + now[0] = 100.5 + event.set() + event.clear() + assert await task is True + assert "set" not in vars(event) + print("OK") + +asyncio.run(main()) +""" + 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_event_ignores_a_signal_after_cutoff( @@ -2116,7 +2153,7 @@ def replacement() -> None: finally: client_module._untrack_thread_signal(event, deadline) assert condition.notify_all is replacement - assert condition.notify is tracker.installed_notify + assert condition.notify.__func__ is tracker.original_notify.__func__ assert tracker.subscribers == {} @@ -2224,21 +2261,9 @@ def record(now: float) -> bool: 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 - task = asyncio.create_task(client_module._async_wait_for_event(event, time.monotonic() + 10.0)) - try: - await wait_until(lambda: bool(event._waiters), task) - assert event.set == setter - finally: - task.cancel() - await asyncio.gather(task, return_exceptions=True) - assert not event._waiters - - def test_async_wait_for_event_propagates_external_cancellation() -> None: - # A cleanup lockup must be terminated by the parent test. + # A cleanup lockup must be terminated by the parent test. The setter probe + # lives here too, so its cleanup is bounded by the same parent timeout. code = """ import asyncio import sys @@ -2249,6 +2274,7 @@ def test_async_wait_for_event_propagates_external_cancellation() -> None: async def main(): event = asyncio.Event() + setter = event.set task = asyncio.create_task(client._async_wait_for_event(event, time.monotonic() + 10.0)) for _ in range(200): if task.done(): @@ -2258,6 +2284,7 @@ async def main(): await asyncio.sleep(0) else: raise AssertionError("the helper never registered a waiter") + assert event.set == setter assert len(event._waiters) == 1 task.cancel() try: @@ -2266,6 +2293,7 @@ async def main(): pass else: raise AssertionError("external cancellation was not propagated") + assert event.set == setter assert not event._waiters print("OK") @@ -2807,36 +2835,52 @@ async def test_wait_for_review_cancel_event_stops_before_any_request( def test_async_cancel_event_is_reusable_across_event_loops() -> None: - event = asyncio.Event() - failures: list[BaseException] = [] + # Cleanup deadlocks must be terminated by the parent test. + code = """ +import asyncio +import sys +import time - 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 +sys.path.insert(0, sys.argv[1]) +from proofline import client - try: - asyncio.run(main()) - except BaseException as error: - failures.append(error) +event = asyncio.Event() - run_once() - run_once() - assert failures == [] - assert event._loop is None - assert not event._waiters +async def run_once(): + task = asyncio.create_task( + client._async_wait_for_event(event, time.monotonic() + 10.0) + ) + for _ in range(200): + if task.done(): + await task + 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 + else: + raise AssertionError("cancellation was not propagated") + +asyncio.run(run_once()) +asyncio.run(run_once()) +assert event._loop is None +assert not event._waiters +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_accepts_a_read_only_setter( @@ -2916,8 +2960,9 @@ def set_later(): result = client.wait_for_review( t.ORG, t.REVIEW, timeout=5, cancel_event=event ) + finished = time.monotonic() assert published -assert time.monotonic() - published[0] < 2.0 +assert finished - published[0] < 2.0 assert ready.is_set() assert len(server.requests) == 1 assert result.status == "STOPPED" @@ -2994,8 +3039,9 @@ async def set_later(): result = await t.call( client, "wait_for_review", t.ORG, t.REVIEW, timeout=5, cancel_event=event ) + finished = time.monotonic() assert published - assert time.monotonic() - published[0] < 2.0 + assert finished - published[0] < 2.0 assert ready.is_set() assert len(server.requests) == 1 assert result.status == "STOPPED" @@ -3328,10 +3374,13 @@ async def get_review(*args: Any, **kwargs: Any) -> Any: async def test_wait_for_review_records_cancellation_at_the_backoff_cutoff( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: + real_wait = client_module._wait_for_event + real_async_wait = client_module._async_wait_for_event 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")) + observed: list[bool] = [] if mode == "sync": calls = 0 @@ -3343,10 +3392,14 @@ def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) assert timeout == pytest.approx(5.0) assert deadline is not None assert deadline.end == pytest.approx(clock.now + 100.0) - clock.now = 105.0 + cutoff = min(clock.now + timeout, deadline.end) + clock.now = cutoff wait_event.set() wait_event.clear() - return False + clock.now = cutoff - 0.5 + result = real_wait(wait_event, timeout, deadline) + observed.append(result) + return result monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) else: @@ -3361,10 +3414,13 @@ async def async_wait_for_event( assert cutoff == pytest.approx(clock.now + 5.0) assert signal is not None assert signal.end == pytest.approx(clock.now + 100.0) - clock.now = 105.0 + clock.now = cutoff wait_event.set() wait_event.clear() - return False + clock.now = cutoff - 0.5 + result = await real_async_wait(wait_event, cutoff, signal) + observed.append(result) + return result monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) @@ -3374,6 +3430,7 @@ async def async_wait_for_event( client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event ) + assert observed == [True] assert len(server.requests) == 1 assert result.status == "STOPPED" assert result.reason == "The wait was cancelled by the caller." @@ -4690,6 +4747,36 @@ async def test_async_waiter_keeps_a_temporary_binding_until_native_waiters_drain assert not event._waiters +async def test_async_binding_does_not_poll_a_pending_native_waiter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = asyncio.Event() + loop = asyncio.get_running_loop() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + calls: list[tuple[Any, ...]] = [] + monkeypatch.setattr( + client_module, + "_schedule_binding_recheck", + lambda *args: calls.append(args), + ) + client_module._unwatch_async_waiter(sdk_waiter, deadline) + for _ in range(5): + await asyncio.sleep(0) + assert calls == [] + binding = client_module._async_loop_bindings.get(event) + assert binding is not None + try: + native.cancel() + with pytest.raises(asyncio.CancelledError): + await native + await wait_until(lambda: len(calls) == 1) + finally: + client_module._clear_temporary_async_binding(event, binding) + + async def test_wait_for_review_accepts_an_unhashable_async_event_already_set( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -5577,96 +5664,46 @@ def notify_all(self) -> None: client_module._untrack_thread_signal(event, late) -def test_initial_sync_signal_orders_linked_condition_locks() -> None: - # Two events that reference each other expose the same locks in opposite - # order; each setup must record the same identity order under a watchdog. - code = """ -import sys -import threading -import time - -sys.path.insert(0, sys.argv[1]) -from proofline import client - +def test_initial_sync_signal_does_not_hold_caller_condition_locks() -> None: + acquired: list[object] = [] -class TrackingLock: - def __init__(self, order): - self._lock = threading.Lock() - self._order = order - - def __enter__(self): - self._order.append((threading.get_ident(), id(self))) - self._lock.acquire() - return self - - def __exit__(self, *exc): - self._lock.release() - return False - - def acquire(self, *args, **kwargs): - acquired = self._lock.acquire(*args, **kwargs) - if acquired: - self._order.append((threading.get_ident(), id(self))) - return acquired + class TrackingLock: + def __init__(self) -> None: + self._lock = threading.Lock() - def release(self): - self._lock.release() + def __enter__(self) -> Any: + acquired.append(self) + return self._lock.__enter__() - def locked(self): - return self._lock.locked() + def __exit__(self, *exc: object) -> bool: + self._lock.release() + return False - def _is_owned(self): - return self._lock._is_owned() + def acquire(self, *args: Any, **kwargs: Any) -> bool: + got = self._lock.acquire(*args, **kwargs) + if got: + acquired.append(self) + return got + def release(self) -> None: + self._lock.release() -order_log = [] -first_lock = TrackingLock(order_log) -second_lock = TrackingLock(order_log) -first = threading.Event() -second = threading.Event() -first._cond = threading.Condition(first_lock) -second._cond = threading.Condition(second_lock) -first.other = second -second.other = first -barrier = threading.Barrier(2) -orders = [first, second] -errors = [] + def locked(self) -> bool: + return self._lock.locked() + def _is_owned(self) -> bool: + return self._lock._is_owned() -def run(event): - try: - barrier.wait(5.0) - deadline = client._SignalDeadline(time.monotonic() + 5.0) - client._initial_sync_signal(event, deadline, False, time.monotonic()) - client._untrack_sync_cancel(event, deadline) - except BaseException as error: - errors.append(repr(error)) - - -threads = [threading.Thread(target=run, args=(event,), daemon=True) for event in orders] -for thread in threads: - thread.start() -for thread in threads: - thread.join(5.0) -assert not any(thread.is_alive() for thread in threads), "linked setup deadlocked" -assert errors == [], errors -by_thread = {} -for thread_id, lock_id in order_log: - by_thread.setdefault(thread_id, []).append(lock_id) -assert len(by_thread) == 2 -assert all(len(order) == 2 and tuple(order) == tuple(sorted(order)) for order in by_thread.values()) -assert len({tuple(order) for order in by_thread.values()}) == 1 -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" + first = threading.Event() + second = threading.Event() + first._cond = threading.Condition(TrackingLock()) + second._cond = threading.Condition(TrackingLock()) + first.other = second # type: ignore[attr-defined] + second.other = first # type: ignore[attr-defined] + deadline = client_module._SignalDeadline(time.monotonic() + 5.0) + client_module._initial_sync_signal(first, deadline, False, time.monotonic()) + client_module._untrack_sync_cancel(first, deadline) + assert acquired == [] def test_initial_sync_signal_uses_a_shared_non_reentrant_lock_once() -> None: @@ -6136,6 +6173,28 @@ def is_set(self) -> bool: client_module._untrack_thread_signal(event, deadline) +def test_condition_tracker_wakes_for_a_backing_event_sharing_the_condition( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + backing = threading.Event() + backing._cond = event._cond + event.backing = backing # type: ignore[attr-defined] + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + backing.set() + # The outer flag is untouched, so this is only a wake hint, but the + # shared condition must not discard the backing event that carried it. + assert deadline.signalled_at is None + assert deadline.signal_event.is_set() + assert client_module._record_signal_before(event, deadline, deadline.end) is False + finally: + client_module._untrack_thread_signal(event, deadline) + + def test_condition_tracker_verifies_a_backing_notification_from_the_supplied_flag( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -6162,6 +6221,34 @@ def set(self) -> None: client_module._untrack_thread_signal(event, deadline) +async def test_async_event_verifies_the_predicate_once_per_dispatch() -> None: + class CountingEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.calls = 0 + self.gate = False + + def is_set(self) -> bool: + self.calls += 1 + return self.gate and super().is_set() + + event = CountingEvent() + loop = asyncio.get_running_loop() + deadlines = [client_module._SignalDeadline(loop.time() + 10.0) for _ in range(3)] + waiters = [client_module._watch_async_waiter(event, deadline) for deadline in deadlines] + try: + event.set() + event.clear() + assert event.calls == 1 + assert all(deadline.signalled_at is None for deadline in deadlines) + event.set() + event.clear() + assert event.calls == 2 + finally: + for waiter, deadline in zip(waiters, deadlines): + client_module._unwatch_async_waiter(waiter, deadline) + + async def test_async_future_watch_wakes_without_stopping_when_predicate_is_closed( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -6186,12 +6273,15 @@ def is_set(self) -> bool: assert deadline.signalled_at is None assert not future.done() assert any(future is pending for pending in event._waiters) + clock.now = 101.25 event.gate = True event.set() + assert deadline.signalled_at == 101.25 + event.clear() await asyncio.sleep(0) assert future.done() assert client_module._record_signal_before(event, deadline, deadline.end) is True - assert deadline.signalled_at is not None + assert deadline.signalled_at == 101.25 finally: client_module._unwatch_async_waiter(waiter, deadline)