diff --git a/README.md b/README.md index 721949da..f7ceb104 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,34 @@ 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 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 + +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 + +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(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. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..71760685 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,9 +2,18 @@ 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 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 @@ -189,6 +198,701 @@ 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__", {}) + + +def _thread_event_is_set(event: threading.Event | AsyncEvent) -> bool: + try: + return bool(event.is_set()) + except Exception: + return bool(getattr(event, "_flag", False)) + + +_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]] = [] +# 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: + """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 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) + 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: + """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.conditions: tuple[threading.Condition, ...] = () + self.signal_event = threading.Event() + + def record(self, now: float) -> bool: + if self.signalled_at is None and now < self.end: + self.signalled_at = now + self.signal_event.set() + return True + return False + + 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: + 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: + """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: + 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.""" + + 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 + # (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: + 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( + 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: + # 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 self._subscription_lock: + subscribers = tuple(self.subscribers.items()) + 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() + self.original_notify_all() + + def notify(self, *args: Any, **kwargs: Any) -> None: + self.record() + self.original_notify(*args, **kwargs) + + def restore(self) -> None: + # 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] = {} + + +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]] = [] + 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 + ) + 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)) + 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: + key = id(tracked) + tracker = _notify_trackers.get(key) + if tracker is None: + tracker = _ConditionSignalTracker(tracked) + _notify_trackers[key] = 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 + + +def _track_sync_cancel(event: threading.Event, deadline: _SignalDeadline) -> None: + # Observation uses only the event's condition(s), never the caller's set(). + _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.""" + 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: + _untrack_thread_signal(event, deadline) + + +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 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): + return False + with _notify_lock: + if deadline.signalled_at is not None: + return True + # 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) + 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.""" + return _record_signal_before(event, deadline, deadline.end) + + +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]: + """Drain pending publications, then read the latch and clock under one lock.""" + _drain_signals() + 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) + # 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: + if _record_signal_before(event, deadline, deadline.end): + return True + signalled_at, now = _sync_deadline_state(deadline) + if signalled_at is not None: + return True + if now >= end: + return False + deadline.signal_event.wait(end - now) + deadline.signal_event.clear() + + +_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 + + +def _check_async_event_loop(event: asyncio.Event) -> None: + """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: + 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.counts: dict[_SignalDeadline, int] = {} + self.dispatch_done = False + + 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: + # 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: + """One shared hook on a waiter future, with independent observers.""" + + 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") + self.original = future.set_result + self.deadlines: set[_SignalDeadline] = set() + + def set_result(result: Any) -> None: + if _event_is_set(event): + 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: + 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 _watch_async_future( + future: AsyncFuture[Any], + event: AsyncEvent, + deadline: _SignalDeadline, + signal: _AsyncSignalWatch | None = None, +) -> None: + with _async_future_lock: + owns_signal = signal is None + if signal is None: + signal = _async_signal_watches.get(id(event)) + if signal is None: + signal = _AsyncSignalWatch(event) + watch = _async_future_watches.get(id(future)) + 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 not _event_is_set(event): + signal.dispatch_done = False + if owns_signal: + _async_signal_watches[id(event)] = signal + + +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) + final_signal_registration = watch.signal.remove(deadline) + last = not watch.deadlines + if last: + del _async_future_watches[id(future)] + 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 + + +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 + + +def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: + """Observe a signal without binding the caller's event to this loop.""" + waiter = _AsyncSignalWaiter() + if not isinstance(event, asyncio.Event): + return waiter + with _async_future_lock: + _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: + _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: + 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 + 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() + try: + waiter = _watch_async_waiter(event, deadline) + if _event_is_set(event): + _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() + _unwatch_async_waiter(waiter, deadline) + + +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, + 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) + owns_signal = signal is None + deadline: _SignalDeadline = _SignalDeadline(end) if signal is None else signal + try: + 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 + 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 _record_signal_before(event, deadline, deadline.end): + return False + return True + finally: + if owns_signal: + _untrack_sync_cancel(event, deadline) + + +async def _async_sleep_with_cancel( + delay: float, + event: AsyncEvent | None, + cutoff: float | None = None, + signal: _SignalDeadline | 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, signal): + 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 +1250,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,34 +1259,84 @@ 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. + + 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 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.") + 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 - deadline = _transport.DEADLINE.set(monotonic() + timeout) + read_signal = _SignalDeadline(deadline_at) + deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 try: + 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) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: + cancelled = _cancellation_signal(cancel_event, read_signal) + if _invalid_response(error) and cancelled: + raise + if cancelled: + 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, read_signal + ): + return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) + 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: - _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): @@ -941,30 +1696,83 @@ async def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + cancel_event: AsyncEvent | None = None, ) -> ReviewOutcome: + """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 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.") + 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 - deadline = _transport.DEADLINE.set(monotonic() + timeout) + read_signal = _SignalDeadline(deadline_at) + deadline = _transport.DEADLINE.set(deadline_at) interval = 5.0 + read_waiter = _AsyncSignalWaiter() 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) 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: + cancelled = _cancellation_signal(cancel_event, read_signal) + if _invalid_response(error) and cancelled: + raise + if cancelled: + 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, read_signal + ): + return _stopped(url, last, review_id, head_commit_sha) interval = min(60, interval * 2) + 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: - _transport.DEADLINE.reset(deadline) + try: + _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 0af9d60f..ccc7f61c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -106,6 +106,61 @@ 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], *, check: bool = True) -> None: + """Reap a signal task; only propagate its timeout when the probe succeeded.""" + try: + if check: + 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.owner = getattr(callback, "__self__", None) + 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 isinstance(getattr(callback, "__self__", None), asyncio.Future) + 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 +172,40 @@ 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) + 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) + woke = True + return woke + + 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 + 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) @@ -1397,6 +1486,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,231 +1513,1928 @@ async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( assert len(server.requests) == 8 -@MODES -async def test_retry_after_is_bounded_by_wait_deadline( - mode: str, monkeypatch: pytest.MonkeyPatch +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) - with Server( - lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": "20"}) - ) as server: - async with session(mode, server.url) as client: - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=10) - assert result.status == "TIMED_OUT" - assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" - assert len(server.requests) == 1 - assert clock.delays == [10] + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() + 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() + 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() + + +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) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() + cutoff = clock.now + 0.01 + 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() + assert await asyncio.wait_for(task, 1.0) is False + assert event.is_set() + 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) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() + setter = event.set + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: + await wait_until(lambda: bool(event._waiters)) + clock.now = 100.5 + setter() + 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_uses_a_base_waiter_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 -@MODES -@pytest.mark.parametrize("status", [429, 503, 403]) -async def test_deadline_expiring_with_a_received_problem_chunk_keeps_retry_policy( - mode: str, status: int, monkeypatch: pytest.MonkeyPatch + event = InheritedEvent() + 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_does_not_call_a_subclass_wait_override( + monkeypatch: pytest.MonkeyPatch, ) -> None: + real_wait = client_module._async_wait_for_event clock = Clock(monkeypatch) - checked = _transport.check_stream + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + + class CountingEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.wait_calls = 0 + + async def wait(self) -> bool: + self.wait_calls += 1 + raise AssertionError("the helper must not call an overriding wait()") + + event = CountingEvent() + 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 + assert event.wait_calls == 0 + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + + +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: + 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 + 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 + assert calls == [] + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + + +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: + await wait_until(lambda: len(event._waiters) >= 2) + timers[0].fire() + assert await asyncio.wait_for(first, 1.0) is False + 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 not event._waiters + finally: + first.cancel() + second.cancel() + await asyncio.gather(first, second, return_exceptions=True) + for timer in timers: + timer.cancel() + + +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 + clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + event = asyncio.Event() + setter = event.set + task = asyncio.create_task(real_wait(event, clock.now + 0.01)) + try: + await wait_until(lambda: bool(event._waiters)) + future = next(iter(event._waiters)) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + 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) + for timer in timers: + timer.cancel() + + +async def test_async_wait_for_event_cancels_timer_when_waiter_registration_fails( + 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 late(size: int, response_status: int, deadline: float) -> None: - # The wait deadline passes while a received body chunk is still being checked. - clock.now += 10 - checked(size, response_status, deadline) + 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(_transport, "check_stream", late) - with Server( - lambda request, index: Reply(status, {"detail": PRIVATE}, {"Retry-After": "2"}) - ) as server: - async with session(mode, server.url) as client: - if status == 403: - with pytest.raises(ProoflineError) as raised: - await call(client, "wait_for_review", ORG, REVIEW, timeout=1) - assert raised.value.status == 403 - else: - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=1) - assert result.status == "TIMED_OUT" - assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" - assert len(server.requests) == 1 - assert clock.delays == [] + monkeypatch.setattr(loop, "call_at", record_call_at) + def fail(*args: Any) -> Any: + raise RuntimeError("registration failed") -@MODES -@pytest.mark.parametrize("status", [200, 403]) -async def test_body_stream_deadline_does_not_turn_authority_into_timeout( - mode: str, status: int, monkeypatch: pytest.MonkeyPatch + 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) + + +async def test_async_wait_for_event_cancels_timer_when_future_hook_fails( + monkeypatch: pytest.MonkeyPatch, ) -> None: - body = review() if status == 200 else {"detail": PRIVATE} - # Expire only after the real transport receives the status. A short wall-clock - # timeout can expire before headers on a busy worker, when TIMED_OUT is correct. - with monkeypatch.context() as patch: - clock = Clock(patch) - sync_request = _sync_http.Transport.handle_request - async_request = httpx2.AsyncHTTPTransport.handle_async_request + real_wait = client_module._async_wait_for_event + loop = asyncio.get_running_loop() + handles: list[asyncio.TimerHandle] = [] + real_call_at = loop.call_at - def expire_sync( - transport: _sync_http.Transport, request: httpx2.Request - ) -> httpx2.Response: - response = sync_request(transport, request) - clock.now += 10 - return response + def record_call_at(when: float, callback: Any, *args: Any) -> asyncio.TimerHandle: + handle = real_call_at(when, callback, *args) + handles.append(handle) + return handle - async def expire_async( - transport: httpx2.AsyncHTTPTransport, request: httpx2.Request - ) -> httpx2.Response: - response = await async_request(transport, request) - clock.now += 10 - return response + monkeypatch.setattr(loop, "call_at", record_call_at) - patch.setattr(_sync_http.Transport, "handle_request", expire_sync) - patch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", expire_async) - with Server(lambda request, index: Reply(status, body, split=8, pause=0.2)) as server: - async with session(mode, server.url) as client: - if status == 200: - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=10) - assert result.status == "TIMED_OUT" - assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" - else: - with pytest.raises(ProoflineError) as raised: - await call(client, "wait_for_review", ORG, REVIEW, timeout=10) - assert raised.value.status == 403 - assert len(server.requests) == 1 - slow_reply = Reply(status, body, split=8, header_pause=0.06, first_pause=0.26, pause=0.24) - with Server( - lambda request, index: slow_reply if index == 0 else Reply(body=finding()) - ) as server: - async with session(mode, server.url) as client: - started = time.monotonic() - if status == 200: - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.4) - assert result.status == "TIMED_OUT" - assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" - else: - with pytest.raises(ProoflineError) as raised: - await call(client, "wait_for_review", ORG, REVIEW, timeout=0.4) - assert raised.value.status == 403 - assert time.monotonic() - started < 0.49 - # The next call inherits neither an expired context nor abandoned response bytes. - assert (await call(client, "get_finding", ORG, FINDING)).id == FINDING - assert len(server.requests) == 2 - assert server.requests[0].peer_port != server.requests[1].peer_port - with Server(lambda request, index: Reply(status, b"")) 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=0.1) - assert raised.value.status == (0 if status == 200 else 403) - if status == 200: - assert raised.value.type == "urn:proofline:sdk:invalid-response" + def fail(*args: Any) -> None: + raise RuntimeError("future hook failed") - # The headers wait far past a deadline that leaves time to connect and send. The - # client counts its own attempts, so the no-retry proof needs no scheduler timing. - attempts = 0 - with monkeypatch.context() as patch: - sync_request = _sync_http.Transport.handle_request - async_request = httpx2.AsyncHTTPTransport.handle_async_request + 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 + assert id(event) not in client_module._async_signal_watches - def count_sync(transport: _sync_http.Transport, request: httpx2.Request) -> httpx2.Response: - nonlocal attempts - attempts += 1 - return sync_request(transport, request) - async def count_async( - transport: httpx2.AsyncHTTPTransport, request: httpx2.Request - ) -> httpx2.Response: - nonlocal attempts - attempts += 1 - return await async_request(transport, request) +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) + + +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) - patch.setattr(_sync_http.Transport, "handle_request", count_sync) - patch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", count_async) - with Server(lambda request, index: Reply(status, body, header_pause=2.0)) as server: - async with session(mode, server.url) as client: - started = time.monotonic() - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.3) - assert result.status == "TIMED_OUT" - assert result.review is None - assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" - assert time.monotonic() - started < 1.5 - assert attempts == 1 - # The request was sent before the header wait, so the server reads it - # even after the client gives up. - recorded = time.monotonic() + 5 - while not server.requests and time.monotonic() < recorded: - time.sleep(0.01) - assert len(server.requests) == 1 + 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 -@MODES -async def test_streaming_and_resolution_keep_deadline_outcomes_explicit( - mode: str, monkeypatch: pytest.MonkeyPatch -) -> None: - with Server(lambda request, index: Reply(body=review(), chunk_size=4, pause=0.01)) as server: - async with session(mode, server.url) as client: - started = time.monotonic() - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.06) - assert result.status == "TIMED_OUT" - assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" - assert time.monotonic() - started < 0.5 - with Server(lambda request, index: Reply(body=finding(), chunk_size=4, pause=0.01)) as server: - async with session(mode, server.url, timeout=0.06) as client: - started = time.monotonic() - with pytest.raises(ProoflineError) as raised: - await call(client, "get_finding", ORG, FINDING) - assert raised.value.type == "urn:proofline:sdk:timeout" - assert time.monotonic() - started < 0.5 - original_resolution = socket.getaddrinfo - resolution_started = threading.Event() - resolution_released = threading.Event() - resolution_finished = threading.Event() - resolutions: list[bool] = [] +def test_condition_hook_ignores_a_late_flag_after_the_setter_returns( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) - def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: - resolutions.append(True) - if len(resolutions) > 1: - return original_resolution(host, port, *args, **kwargs) - resolution_started.set() - try: - # Hang until the test releases it, so the deadline expires during the lookup - # whenever the worker starts. The bound only ends a call that waits for it. - resolution_released.wait(5) - return original_resolution("127.0.0.1", port, *args, **kwargs) - finally: - resolution_finished.set() + class LateFlagEvent(threading.Event): + def set(self) -> None: + clock.now = 101.5 + super().set() - monkeypatch.setattr(socket, "getaddrinfo", resolve) - with Server(lambda request, index: Reply(body=finding())) as server: - origin = server.url.replace("http://127.0.0.1", "https://controlled.proofline.invalid") - async with session(mode, origin) as client: - # The resolver worker starts within a millisecond on an idle host; the deadline - # leaves a loaded check worker half a second to start it (#19783). - result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.5) - assert result.status == "TIMED_OUT" - assert result.review is None - assert result.review_url == f"{origin}/orgs/by-id/{ORG}/reviews/{REVIEW}" - assert resolution_started.is_set() - assert not resolution_finished.is_set() - # Drain the abandoned resolver worker before the loopback peer closes. - resolution_released.set() - deadline = time.monotonic() + 5 - while not resolution_finished.is_set() and time.monotonic() < deadline: - await asyncio.sleep(0.01) - assert resolution_finished.is_set() - assert server.requests == [] + event = LateFlagEvent() + deadline = client_module._SignalDeadline(101.0) + client_module._track_thread_signal(event, deadline) + try: + event.set() + assert event.is_set() + assert deadline.signalled_at is None + finally: + client_module._untrack_thread_signal(event, deadline) + assert "set" not in vars(event) -def test_sync_transport_connects_to_each_resolved_address_under_the_original_host( +async def test_async_wait_for_event_supports_a_read_only_setter( monkeypatch: pytest.MonkeyPatch, ) -> None: - lookups: list[tuple[Any, Any]] = [] - scoped_connections: list[str] = [] - refused = socket.socket() - refused.bind(("127.0.0.1", 0)) - closed_port = refused.getsockname()[1] - refused.close() + 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() + + def set(self) -> None: + self.backing.set() + + 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() + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +def test_condition_observation_preserves_a_replacement_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + deadline = client_module._SignalDeadline(clock.now + 10.0) - def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: - lookups.append((host, threading.current_thread().name)) - if host == "missing.proofline.invalid": - raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") - if host == "service.proofline.invalid": + def replacement() -> None: + return None + + client_module._track_thread_signal(event, deadline) + try: + event.set = replacement # type: ignore[method-assign] + finally: + client_module._untrack_thread_signal(event, deadline) + assert event.set is replacement + + +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() + + def replacement() -> None: + return None + + event.set = replacement # type: ignore[method-assign] + task = asyncio.create_task(real_wait(event, clock.now + 0.01)) + try: + 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: + 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( + 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_restore = client_module._AsyncFutureWatch.restore + captured: list[Any] = [] + + def raise_on_restore(watch: Any) -> None: + captured.append(watch) + 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)) + try: + await wait_until(lambda: bool(event._waiters)) + future = next(iter(event._waiters)) + timers[0].fire() + with pytest.raises(RuntimeError, match="restore failed"): + await asyncio.wait_for(task, 1.0) + assert not event._waiters + 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._AsyncFutureWatch, "restore", real_restore) + for watch in captured: + real_restore(watch) + + +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(*args: Any) -> None: + captured.append(args[0]) + 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 + 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( + 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) + + +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: + # 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 + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +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: + 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 + + 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 + + +def test_sleep_with_cancel_returns_true_at_deadline_without_a_signal( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + assert client_module._sleep_with_cancel(5, event, cutoff=clock.now) is True + assert clock.delays == [] + + +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_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, 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) + 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 clock.delays == [] + + +def test_sleep_with_cancel_records_a_set_clear_before_wait_registration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + 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: + 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 + assert clock.delays == [] + + +def test_sleep_with_cancel_latches_an_inherited_wait_set_clear_before_registration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class InheritedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + event = self + + class RaceCondition(threading.Condition): + def notify_all(self, *args: Any, **kwargs: Any) -> None: + event._flag = True + 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 + 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: + clock = Clock(monkeypatch) + event = threading.Event() + event.other = threading.Condition() # type: ignore[attr-defined] + + 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 + + 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) # type: ignore[attr-defined] + + +def test_sleep_with_cancel_ignores_an_unrelated_own_condition_notification( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + + 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 + + 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_accepts_a_read_only_setter_through_its_condition( + 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 + 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() -> None: + # A deadlocked notification must be terminable by the parent test. + code = """ +import sys +import threading + +root = sys.argv[1] +sys.path.insert(0, root) +from tests import test_http as t + +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): + super().set() + self.backing.set() + +event = BackingEvent() +ready = threading.Event() +failures = [] +real_track = t.client_module._track_sync_cancel + +def track(event_arg, deadline): + real_track(event_arg, deadline) + ready.set() + +t.client_module._track_sync_cancel = track +t.client_module.monotonic = lambda: now[0] +now = [100.0] + +def signal(): + if not ready.wait(2.0): + failures.append("the cancellation observers were never installed") + now[0] = 101.5 + event.set() + return + now[0] = 100.5 + event.set() + now[0] = 102.0 + +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( + 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()) + + 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: + clock = Clock(monkeypatch) + event = threading.Event() + event.marker = threading.Event() # type: ignore[attr-defined] + + 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 + + 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] + + +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) + + held = False + + class ReentrantEvent(threading.Event): + def is_set(self) -> bool: + 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 + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + 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: + clock = Clock(monkeypatch) + + class SwappingEvent(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 = SwappingEvent() + 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 set(self) -> None: + super().set() + 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: + real_wait = client_module._wait_for_event + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "_wait_for_event", real_wait) + + 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 = NeverWaitEvent() + ready = threading.Event() + failures: list[str] = [] + 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: + 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, 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 == [] + + +@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 == [] + + +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) + + +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 + +root = sys.argv[1] +sys.path.insert(0, root) +from tests import test_http as t + +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 + + +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) + + +class ReadySignalEvent(threading.Event): + def __init__(self): + super().__init__() + self._cond = ReadyCondition(self._cond._lock) + + +def track(event_arg, deadline): + real_track(event_arg, deadline) + deadline.signal_event = ReadySignalEvent() + + +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" + + +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_wait = t.client_module._async_wait_for_event + + async def async_wait(*args, **kwargs): + helper = asyncio.create_task(real_wait(*args, **kwargs)) + try: + await t.wait_until(lambda: len(event._waiters) >= 2) + ready.set() + return await helper + finally: + helper.cancel() + await asyncio.gather(helper, return_exceptions=True) + + t.client_module._async_wait_for_event = async_wait + + async def set_later(): + await asyncio.wait_for(ready.wait(), 2.0) + event.set() + + 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 + ) + 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 + +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 +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, signal: Any | None = None + ) -> 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_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": + 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() + return False + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + else: + calls = 0 + + 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" + 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() + 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) + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + raise ProoflineError(503, "urn:proofline:sdk:test", "boom") + + else: + + def raise_restore(watch: Any) -> None: + async_watches.append(watch) + raise RuntimeError("cleanup failed") + + monkeypatch.setattr(client_module._AsyncFutureWatch, "restore", raise_restore) + + async def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + raise ProoflineError(503, "urn:proofline:sdk:test", "boom") + + 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 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: + 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 +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 +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": "20"}) + ) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=10) + assert result.status == "TIMED_OUT" + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert len(server.requests) == 1 + assert clock.delays == [10] + + +@MODES +@pytest.mark.parametrize("status", [429, 503, 403]) +async def test_deadline_expiring_with_a_received_problem_chunk_keeps_retry_policy( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + checked = _transport.check_stream + + def late(size: int, response_status: int, deadline: float) -> None: + # The wait deadline passes while a received body chunk is still being checked. + clock.now += 10 + checked(size, response_status, deadline) + + monkeypatch.setattr(_transport, "check_stream", late) + with Server( + lambda request, index: Reply(status, {"detail": PRIVATE}, {"Retry-After": "2"}) + ) as server: + async with session(mode, server.url) as client: + if status == 403: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=1) + assert raised.value.status == 403 + else: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=1) + assert result.status == "TIMED_OUT" + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert len(server.requests) == 1 + assert clock.delays == [] + + +@MODES +@pytest.mark.parametrize("status", [200, 403]) +async def test_body_stream_deadline_does_not_turn_authority_into_timeout( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + body = review() if status == 200 else {"detail": PRIVATE} + # Expire only after the real transport receives the status. A short wall-clock + # timeout can expire before headers on a busy worker, when TIMED_OUT is correct. + with monkeypatch.context() as patch: + clock = Clock(patch) + sync_request = _sync_http.Transport.handle_request + async_request = httpx2.AsyncHTTPTransport.handle_async_request + + def expire_sync( + transport: _sync_http.Transport, request: httpx2.Request + ) -> httpx2.Response: + response = sync_request(transport, request) + clock.now += 10 + return response + + async def expire_async( + transport: httpx2.AsyncHTTPTransport, request: httpx2.Request + ) -> httpx2.Response: + response = await async_request(transport, request) + clock.now += 10 + return response + + patch.setattr(_sync_http.Transport, "handle_request", expire_sync) + patch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", expire_async) + with Server(lambda request, index: Reply(status, body, split=8, pause=0.2)) as server: + async with session(mode, server.url) as client: + if status == 200: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=10) + assert result.status == "TIMED_OUT" + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + else: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=10) + assert raised.value.status == 403 + assert len(server.requests) == 1 + slow_reply = Reply(status, body, split=8, header_pause=0.06, first_pause=0.26, pause=0.24) + with Server( + lambda request, index: slow_reply if index == 0 else Reply(body=finding()) + ) as server: + async with session(mode, server.url) as client: + started = time.monotonic() + if status == 200: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.4) + assert result.status == "TIMED_OUT" + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + else: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=0.4) + assert raised.value.status == 403 + assert time.monotonic() - started < 0.49 + # The next call inherits neither an expired context nor abandoned response bytes. + assert (await call(client, "get_finding", ORG, FINDING)).id == FINDING + assert len(server.requests) == 2 + assert server.requests[0].peer_port != server.requests[1].peer_port + with Server(lambda request, index: Reply(status, b"")) 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=0.1) + assert raised.value.status == (0 if status == 200 else 403) + if status == 200: + assert raised.value.type == "urn:proofline:sdk:invalid-response" + + # The headers wait far past a deadline that leaves time to connect and send. The + # client counts its own attempts, so the no-retry proof needs no scheduler timing. + attempts = 0 + with monkeypatch.context() as patch: + sync_request = _sync_http.Transport.handle_request + async_request = httpx2.AsyncHTTPTransport.handle_async_request + + def count_sync(transport: _sync_http.Transport, request: httpx2.Request) -> httpx2.Response: + nonlocal attempts + attempts += 1 + return sync_request(transport, request) + + async def count_async( + transport: httpx2.AsyncHTTPTransport, request: httpx2.Request + ) -> httpx2.Response: + nonlocal attempts + attempts += 1 + return await async_request(transport, request) + + patch.setattr(_sync_http.Transport, "handle_request", count_sync) + patch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", count_async) + with Server(lambda request, index: Reply(status, body, header_pause=2.0)) as server: + async with session(mode, server.url) as client: + started = time.monotonic() + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.3) + assert result.status == "TIMED_OUT" + assert result.review is None + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert time.monotonic() - started < 1.5 + assert attempts == 1 + # The request was sent before the header wait, so the server reads it + # even after the client gives up. + recorded = time.monotonic() + 5 + while not server.requests and time.monotonic() < recorded: + time.sleep(0.01) + assert len(server.requests) == 1 + + +@MODES +async def test_streaming_and_resolution_keep_deadline_outcomes_explicit( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + with Server(lambda request, index: Reply(body=review(), chunk_size=4, pause=0.01)) as server: + async with session(mode, server.url) as client: + started = time.monotonic() + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.06) + assert result.status == "TIMED_OUT" + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert time.monotonic() - started < 0.5 + with Server(lambda request, index: Reply(body=finding(), chunk_size=4, pause=0.01)) as server: + async with session(mode, server.url, timeout=0.06) as client: + started = time.monotonic() + with pytest.raises(ProoflineError) as raised: + await call(client, "get_finding", ORG, FINDING) + assert raised.value.type == "urn:proofline:sdk:timeout" + assert time.monotonic() - started < 0.5 + + original_resolution = socket.getaddrinfo + resolution_started = threading.Event() + resolution_released = threading.Event() + resolution_finished = threading.Event() + resolutions: list[bool] = [] + + def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: + resolutions.append(True) + if len(resolutions) > 1: + return original_resolution(host, port, *args, **kwargs) + resolution_started.set() + try: + # Hang until the test releases it, so the deadline expires during the lookup + # whenever the worker starts. The bound only ends a call that waits for it. + resolution_released.wait(5) + return original_resolution("127.0.0.1", port, *args, **kwargs) + finally: + resolution_finished.set() + + monkeypatch.setattr(socket, "getaddrinfo", resolve) + with Server(lambda request, index: Reply(body=finding())) as server: + origin = server.url.replace("http://127.0.0.1", "https://controlled.proofline.invalid") + async with session(mode, origin) as client: + # The resolver worker starts within a millisecond on an idle host; the deadline + # leaves a loaded check worker half a second to start it (#19783). + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=0.5) + assert result.status == "TIMED_OUT" + assert result.review is None + assert result.review_url == f"{origin}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert resolution_started.is_set() + assert not resolution_finished.is_set() + # Drain the abandoned resolver worker before the loopback peer closes. + resolution_released.set() + deadline = time.monotonic() + 5 + while not resolution_finished.is_set() and time.monotonic() < deadline: + await asyncio.sleep(0.01) + assert resolution_finished.is_set() + assert server.requests == [] + + +def test_sync_transport_connects_to_each_resolved_address_under_the_original_host( + monkeypatch: pytest.MonkeyPatch, +) -> None: + lookups: list[tuple[Any, Any]] = [] + scoped_connections: list[str] = [] + refused = socket.socket() + refused.bind(("127.0.0.1", 0)) + closed_port = refused.getsockname()[1] + refused.close() + + def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: + lookups.append((host, threading.current_thread().name)) + if host == "missing.proofline.invalid": + raise socket.gaierror(socket.EAI_NONAME, "Name or service not known") + if host == "service.proofline.invalid": return [ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.2", port)), (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port)), @@ -2586,3 +4382,674 @@ 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_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 + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +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() + +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: + 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._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 + + def slow_restore(): + ready_to_restore.set() + if allow_restore.wait(5.0): + real_restore() + + watch.restore = slow_restore + teardown = asyncio.create_task( + asyncio.to_thread(client._unwatch_async_future, future, first) + ) + 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() + + 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(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): + 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: + 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_condition_tracker_includes_a_subscriber_registered_during_notification( + 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._track_thread_signal(self, late) + super().set() + self.clear() + + event = InterleavingEvent() + client_module._track_thread_signal(event, early) + try: + event.set() + assert early.signalled_at == clock.now + assert late.signalled_at == clock.now + finally: + 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( + 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() + pulses = 0 + held: list[Any] = [] + real_signal = client_module._cancellation_signal + + def signal(event_arg: Any, deadline: Any) -> bool: + nonlocal pulses + result = real_signal(event_arg, deadline) + 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 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_does_not_backdate_a_late_flag_from_an_unverified_wake( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + 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() + 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: + 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) + + def signal() -> None: + assert ready.wait(2.0) + while not event.hinted.wait(0.001): + pass + clock.now = 101.5 + event.revealed.set() + + thread = threading.Thread(target=signal, daemon=True) + 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() + + +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 = threading.Event() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + + 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() + assert True in ownership + assert deadline.signalled_at == clock.now + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_restores_both_hooks_after_a_failure( + 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 + + 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 len(calls) == 1 + assert all(deadline.signalled_at == 100.5 for deadline in deadlines) + assert all(future.done() for future in futures) + finally: + 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) + + +async def test_async_future_observer_stays_armed_after_an_unverified_wake( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + 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() + + 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: + 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 "set" not in vars(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 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 == [] + + +@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(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."