diff --git a/README.md b/README.md index 721949da..ff96d9c5 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,33 @@ 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 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 + +cancel = threading.Event() +outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel) +# From another thread: cancel.set() +``` + +```python +import asyncio + +cancel = asyncio.Event() +loop = asyncio.get_running_loop() +outcome = await async_client.wait_for_review( + organization_id, + 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. 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 `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..1ef0f82e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,8 +2,15 @@ from __future__ import annotations +import asyncio import math +import threading +from asyncio import FIRST_COMPLETED +from asyncio import Event as AsyncEvent +from asyncio import Future as AsyncFuture +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 from string import hexdigits from time import monotonic, sleep @@ -189,6 +196,637 @@ 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: + 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, 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") + 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() + condition.notify_all = self.notify_all # type: ignore[method-assign] + 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. + with _notify_lock: + for deadline in tuple(self.deadlines): + deadline.record(now) + + 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) + + 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] = {} +_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: + 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 + + 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: + """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 tracked in deadline.conditions: + key = id(tracked) + tracker = _notify_trackers.get(key) + if tracker is None: + tracker = _ConditionSignalTracker(tracked, event) + _notify_trackers[key] = tracker + tracker.deadlines.add(deadline) + return deadline + + +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.deadlines.discard(deadline) + 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: + 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" + + +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 _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) + 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. + 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 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 deadline.signalled_at is not None + + +_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: + 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 + + 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 _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 + + +_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() + 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) + coro: Any = None + child: asyncio.Task[Any] | None = None + future: AsyncFuture[Any] | None = None + resumed = False + 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) + 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()) + 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 + ) + + +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 + end = _cancel_end(delay, cutoff) + deadline = _SignalDeadline(end) + try: + _track_sync_cancel(event, deadline) + while True: + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + 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 + 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) + return False + return True + finally: + _untrack_sync_cancel(event, deadline) + + +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 + end = _cancel_end(delay, cutoff) + while True: + if monotonic() >= end: + return True + if await _async_wait_for_event(event, end): + return False + if monotonic() >= end: + return True + + 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 +1184,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,33 +1193,63 @@ 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. """ 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 _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None - deadline = _transport.DEADLINE.set(monotonic() + timeout) + 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 _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 _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 _cancellation_signal(cancel_event, read_signal): + 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) if result is not None: return result - sleep(min(interval, _transport.remaining() or 0)) + remaining = _transport.remaining() or 0 + 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 + ): + 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) @@ -941,30 +1610,57 @@ 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 _stopped(url, None, review_id, head_commit_sha) last: CustomerReviewDetail | None = None - deadline = _transport.DEADLINE.set(monotonic() + timeout) + 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 _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): + 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 _cancellation_signal(cancel_event, read_signal): + 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) if result is not None: return result - await async_sleep(min(interval, _transport.remaining() or 0)) + remaining = _transport.remaining() or 0 + if not await _async_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 + ): + 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 0af9d60f..31981710 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -106,6 +106,55 @@ 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) + + +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 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 + ) -> 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.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 @@ -117,6 +166,23 @@ 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, deadline: Any | None = None) -> bool: + woke = bool(event.is_set()) + if woke and deadline is not None: + deadline.record(self.now) + self.sleep(timeout) + 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)) + await asyncio.sleep(0) + return bool(event.is_set()) def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -1397,6 +1463,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") + + 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) @@ -1414,6 +1490,1508 @@ 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_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() + 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()) + 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( + monkeypatch: pytest.MonkeyPatch, +) -> 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) + + event = asyncio.Event() + cutoff = clock.now + 0.01 + signal_sent = False + + async def send_late_signal() -> None: + nonlocal signal_sent + await registered.wait() + 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) + 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() + + +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() + + 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() + 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) + + +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( + 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 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 + return await asyncio.create_task(self.backing.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()) + 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 + + +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: + 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 == [] + + +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) + + 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 == [] + + +def test_sleep_with_cancel_records_a_captured_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + class CapturedSetterEvent(threading.Event): + setter: Any = None + + 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 == [] + + +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 + + 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_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 + + +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 + + +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( + 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) + + +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 = 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() + clock.sleep(timeout or 0) + 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_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: + 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.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 + + +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() + + +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 = patch_helper_timer(monkeypatch, loop) + + class WatchedEvent(asyncio.Event): + 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() + 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() + + +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) + 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 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 + + 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: + 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 + + +@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_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 + 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 + + 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) + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + + 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() + 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) + + 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) + + 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() + thread_started = True + 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, + ) + ) + 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 + + 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 result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review.id == REVIEW + + +@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() + loop = asyncio.get_running_loop() if mode == "async" else None + + def respond(request: Request, index: int) -> Reply: + if loop is None: + event.set() + else: + loop.call_soon_threadsafe(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_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 +) -> 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 event.is_set() + 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_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 +) -> 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() + + 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, deadline: Any | None = None) -> bool: + clock.sleep(timeout) + wait_event.set() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + + 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 +) -> 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