diff --git a/README.md b/README.md index 721949da..445f5927 100644 --- a/README.md +++ b/README.md @@ -74,7 +74,35 @@ 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. Argument validation comes first: an already set `cancel_event` returns `STOPPED` only after validation succeeds. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. If `cancel_event` is also set and cancellation is observed before the deadline, cancellation takes precedence over that mismatch: the status is `STOPPED`, the mismatch or unavailable-head gap is still attached, and `reason` is the cancellation reason. The response must still pass normal validation. A signal first delivered at or after the deadline is ignored and does not override the mismatch; because the deadline is checked first, a mismatch observed only after expiry returns `TIMED_OUT` with the `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. + +## Cancelling a wait + +Pass `cancel_event` to stop a wait when your own code no longer needs the result: a `threading.Event` for `wait_for_review` on `ProoflineClient`, or an `asyncio.Event` for `wait_for_review` on `AsyncProoflineClient`. The synchronous method blocks its calling thread, so set a `threading.Event` from a separate setter thread, not from a task on that same thread. For `AsyncProoflineClient`, a task on the same loop may call `cancel.set()`; use `loop.call_soon_threadsafe(lambda: cancel.set())` when the setter is another thread so the event loop resolves the setter at dispatch time. If your application already owns `SIGINT` handling, route cancellation through that handler instead of replacing it with `loop.add_signal_handler`. Do not call `threading.Event.set()` directly from a Python signal handler; have the handler hand off to another thread instead. + +```python +import threading + +cancel = threading.Event() +# The wait blocks this thread; call cancel.set() from a separate setter thread. +outcome = client.wait_for_review(organization_id, review_id, cancel_event=cancel) +``` + +```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 a task on this loop: cancel.set() +# From another thread: loop.call_soon_threadsafe(lambda: cancel.set()) +``` + +An event already set at entry, including with `timeout=0`, returns `STOPPED` before any request once argument validation has succeeded. A cancellable wait samples its deadline before validation, so validation counts toward the polling budget and can exhaust it without a request; without `cancel_event`, validation happens before the timeout clock starts. Cancellation is then checked before each poll, during the backoff, and after each read. A signal delivered while arguments are validated is bounded by that entry deadline, so one delivered at or after expiry is ignored. The backoff waits on a latch fed by the supplied event's own condition and waiter registration, so a `set()` followed by `clear()` while observation is active and before the deadline is still observed, overriding `wait()` implementations are never called by the SDK, and no short-slice polling is needed. An in-flight read is not interrupted: cancellation waits for that read to finish, including transport retries and their delays. Retry delays count toward the overall wait deadline, not a single per-attempt HTTP timeout. A signal first delivered at or after the overall deadline is ignored: it does not change the wait's result or suppress a read error that would otherwise propagate. Cancellation must be observable on the event you pass: call `set()` on that event. A cached bound standard `threading.Event.set()` still notifies that event's condition and works; a setter that bypasses the observed condition, or a direct mutation of a backing object, may not wake an in-progress backoff. For `asyncio.Event`, the setter must notify waiters registered on that same event; changing only a backing object's flag does not notify those waiters, though a flag that is still set can be observed at a check after a read. Subclasses whose `is_set()` directly delegates to the standard predicate are supported for both event types: a timely `set()` followed by `clear()` is observed. For a standard or directly delegating synchronous predicate, delivery is verified from the raw flag under the notification; other overridden synchronous predicates are checked after the condition lock is released, so they cannot deadlock that `set()` call. For `asyncio.Event`, native delivery verifies the supplied predicate inline and records cancellation only when it agrees; a rejected pulse leaves the waiter pending for a later verified signal. An override that hides the event's own flag is not supported. The SDK binds the caller's async event to the wait's loop through native registration before attaching its waiter and never assigns to the caller's `set()` attribute. An SDK-owned temporary binding is released when its last waiter is removed; if native waiters remain, ownership is retained until they drain, so the same event may be reused on another loop only after both SDK and native waiters are gone. An event already bound to a different loop, or carrying waiters from one, is rejected under the waiter-registration lock before the first request. A cancelled wait returns `ReviewOutcome` with `status == "STOPPED"` and `reason == "The wait was cancelled by the caller."`. When a review had already been read, `outcome.review` still holds that last record, including when cancellation lands during a read that raises `ProoflineError` or just before the next poll; other exceptions still propagate. A retained review must still pass the normal response validation, including its review ID and head-commit checks: validation errors from either the current response or the retained review propagate even when cancellation is set. When `head_commit_sha` is supplied, a retained review pinned to another head (or to no head) still carries the matching `HEAD_COMMIT_MISMATCH` or `HEAD_COMMIT_UNAVAILABLE` gap; the status remains `STOPPED` and `reason` remains the cancellation reason. Passing the wrong event type raises `TypeError` before any request. Without `cancel_event`, waits keep their existing polling and timeout behavior. HTTP 401 and 403 responses are not converted to `STOPPED`: even after a timely cancellation they still propagate to the caller. ## Review exports diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..d0013fc8 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,8 +2,17 @@ from __future__ import annotations +import asyncio +import dis 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 string import hexdigits from time import monotonic, sleep @@ -11,6 +20,7 @@ from typing import Any, Self, TypedDict, TypeVar, Unpack, cast from urllib.parse import quote from uuid import UUID +from weakref import ref as weak_ref import httpx2 from pydantic import SecretStr @@ -189,6 +199,1265 @@ 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, verification: True, False, or a deferred predicate) +_Verification = bool | Callable[[], bool] | None +_pending_notifications: list[tuple[_SignalDeadline, float, _Verification]] = [] +# Synchronizes snapshots of an event's attributes with condition-hook installation. +_sync_set_lock = threading.Lock() + + +def _stage_signals(items: tuple[tuple[_SignalDeadline, float, _Verification], ...]) -> 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, verification in items: + if verification is True: + deadline.record(now) + elif verification is False or verification is None: + deadline.defer(now) + else: + deadline.defer_verified(now, verification) + + +def _verify_deferred_signals(deadline: _SignalDeadline, end: float) -> None: + """Resolve deferred predicates only after the condition lock has been released.""" + with _notify_lock: + pending = tuple(deadline.pending) + deadline.pending.clear() + for _sampled, predicate in pending: + # An unverified backing wake is only a hint. Timestamp the check after + # the predicate returns, so a predicate that blocks across the deadline + # cannot make a late cancellation look early. + try: + verified = bool(predicate()) + except Exception: + verified = False + checked = monotonic() + with _notify_lock: + if verified and checked < end: + deadline.record(checked) + elif deadline.signalled_at is None and checked < end: + deadline.signal_event.set() + + +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.entry = False + self.conditions: tuple[threading.Condition, ...] = () + self.signal_event = threading.Event() + self.pending: list[tuple[float, Callable[[], bool]]] = [] + + def record(self, now: float) -> bool: + if self.signalled_at is None and now < self.end: + self.signalled_at = now + self.signal_event.set() + return True + return False + + def record_entry(self, now: float) -> None: + """Latch a signal sampled before the deadline was established.""" + if self.signalled_at is None: + self.signalled_at = now + self.entry = True + self.signal_event.set() + + def cap(self, end: float) -> None: + """Apply the wait deadline to notifications observed during setup.""" + self.end = end + if not self.entry and self.signalled_at is not None and self.signalled_at >= end: + self.signalled_at = None + + def defer(self, now: float) -> None: + """Wake the waiter without treating an unverified notification as evidence.""" + if self.signalled_at is None and now < self.end: + self.signal_event.set() + + def defer_verified(self, now: float, predicate: Callable[[], bool]) -> None: + """Wake now, with an out-of-lock predicate check deferred to a checkpoint.""" + if self.signalled_at is None and now < self.end: + self.pending.append((now, predicate)) + self.signal_event.set() + + +def _event_attributes_snapshot(value: Any) -> tuple[Any, ...]: + """Read an event's instance attributes without racing hook installation.""" + with _sync_set_lock: + return tuple(_instance_attributes(value).values()) + + +def _forwards_is_set(method: Any) -> bool: + """Whether a method directly returns the inherited standard predicate.""" + function = getattr(method, "__func__", method) + code = getattr(function, "__code__", None) + if code is None or code.co_names != ("super", "is_set") or code.co_consts != (None,): + return False + operations = [ + instruction.opname + for instruction in dis.get_instructions(code) + if instruction.opname not in {"COPY_FREE_VARS", "RESUME", "PRECALL", "CACHE", "NOP"} + ] + return operations == [ + "LOAD_GLOBAL", + "LOAD_DEREF", + "LOAD_FAST", + "LOAD_SUPER_ATTR", + "CALL", + "RETURN_VALUE", + ] + + +def _event_has_standard_predicate(value: Any) -> bool: + """Whether the resolved predicate is safe to read from the raw flag.""" + attributes = _instance_attributes(value) + if "is_set" in attributes: + candidate = attributes["is_set"] + if getattr(candidate, "__func__", None) is threading.Event.is_set and ( + getattr(candidate, "__self__", None) is value + ): + return True + return _forwards_is_set(candidate) and getattr(candidate, "__self__", None) is value + for cls in type(value).__mro__: + if "is_set" in cls.__dict__: + raw = cls.__dict__["is_set"] + return raw is threading.Event.is_set or _forwards_is_set(raw) + return False + + +def _thread_predicate_for_notification(value: Any) -> Callable[[], bool] | None: + """Resolve a callable predicate without invoking a property descriptor.""" + attributes = _instance_attributes(value) + if "is_set" in attributes: + candidate = attributes["is_set"] + if callable(candidate) and not isinstance(candidate, property): + return lambda: bool(candidate()) + return None + for cls in type(value).__mro__: + if "is_set" in cls.__dict__: + raw = cls.__dict__["is_set"] + if isinstance(raw, property) or not callable(raw): + return None + return lambda: bool(raw(value)) + return None + + +def _restore_method(target: Any, name: str, had_instance: bool, saved: Any, installed: Any) -> None: + """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 _WeakBoundMethod: + """A callable bound method that does not keep its owner alive.""" + + def __init__(self, owner_ref: Any, func: Any) -> None: + self._owner_ref = owner_ref + self.__func__ = func + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + owner = self._owner_ref() + if owner is None: + raise ReferenceError("the condition owned by this hook was collected") + return self.__func__(owner, *args, **kwargs) + + def __eq__(self, other: Any) -> bool: + owner = self._owner_ref() + return ( + owner is not None + and getattr(other, "__self__", None) is owner + and getattr(other, "__func__", None) is self.__func__ + ) + + def __hash__(self) -> int: + return hash((id(self._owner_ref()), self.__func__)) + + +def _weak_bound_method(value: Any) -> Any: + """Use a weak owner for bound methods, leaving other callables unchanged.""" + owner = getattr(value, "__self__", None) + func = getattr(value, "__func__", None) + if owner is None or func is None: + return value + try: + owner_ref = weak_ref(owner) + except TypeError: + return value + return _WeakBoundMethod(owner_ref, func) + + +def _restore_bound_method(value: Any) -> Any: + """Rebuild a bound method stored through a weak owner.""" + if not isinstance(value, _WeakBoundMethod): + return value + owner = value._owner_ref() + if owner is None: + return value.__func__ + return value.__func__.__get__(owner, type(owner)) + + +class _WeakTrackerRegistry: + """Map conditions to trackers without keeping either side alive.""" + + def __init__(self) -> None: + self._conditions: dict[int, Any] = {} + self._trackers: dict[int, Any] = {} + + def _discard(self, key: int, tracker_ref: Any = None) -> None: + if tracker_ref is None or self._trackers.get(key) is tracker_ref: + self._trackers.pop(key, None) + self._conditions.pop(key, None) + + def __setitem__(self, condition: threading.Condition, tracker: Any) -> None: + key = id(condition) + self._discard(key) + + def tracker_gone(tracker_ref: Any) -> None: + self._discard(key, tracker_ref) + + def condition_gone(_: Any) -> None: + self._discard(key) + + self._conditions[key] = weak_ref(condition, condition_gone) + self._trackers[key] = weak_ref(tracker, tracker_gone) + + def get(self, condition: threading.Condition) -> Any | None: + key = id(condition) + condition_ref = self._conditions.get(key) + tracker_ref = self._trackers.get(key) + if condition_ref is None or tracker_ref is None: + return None + tracker = tracker_ref() + if tracker is None or condition_ref() is not condition: + self._discard(key) + return None + return tracker + + def __getitem__(self, condition: threading.Condition) -> Any: + tracker = self.get(condition) + if tracker is None: + raise KeyError(condition) + return tracker + + def __contains__(self, condition: object) -> bool: + return isinstance(condition, threading.Condition) and self.get(condition) is not None + + def __delitem__(self, condition: threading.Condition) -> None: + self._discard(id(condition)) + + def values(self) -> tuple[Any, ...]: + live: list[Any] = [] + for key, tracker_ref in tuple(self._trackers.items()): + condition_ref = self._conditions.get(key) + tracker = tracker_ref() + if tracker is None or condition_ref is None or condition_ref() is None: + self._discard(key) + continue + live.append(tracker) + return tuple(live) + + +class _ConditionSignalTracker: + """Watch one condition, preserving whether overrides were instance attributes.""" + + def __init__(self, condition: threading.Condition) -> None: + self.condition_ref = weak_ref(condition) + attributes = vars(condition) + self.had_notify_all = "notify_all" in attributes + self.saved_notify_all: Any = attributes.get("notify_all") + self.had_notify = "notify" in attributes + self.saved_notify: Any = attributes.get("notify") + self.original_notify_all = _weak_bound_method(condition.notify_all) + self.original_notify = _weak_bound_method(condition.notify) + # deadline -> entries of (event whose raw flag proves the signal, whether + # it is a backing event, the event supplied by the caller). One deadline + # can watch several backing events that share the same condition. + self.subscribers: dict[_SignalDeadline, list[tuple[Any, bool, Any]]] = {} + self._subscription_lock = threading.Lock() + # Condition.notify_all() delegates to notify(); publish only once for + # the outer dispatch so a subscriber added while an override delegates + # cannot consume a notification that began before it subscribed. + self._dispatching = False + self.installed_notify_all: Any = None + self.installed_notify: Any = None + try: + self._install_initial_hooks(condition) + 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 _new_hook(self, delegate: Any) -> Callable[..., Any]: + """Create a wrapper whose delegate is fixed at installation time.""" + + def installed(*args: Any, **kwargs: Any) -> Any: + return self._dispatch(delegate, *args, **kwargs) + + return installed + + def _install_initial_hooks(self, condition: threading.Condition) -> None: + installed_all = self._new_hook(self.original_notify_all) + installed_notify = self._new_hook(self.original_notify) + changed: list[tuple[str, bool, Any, Any]] = [] + try: + for name, had_name, saved_name, installed_name, installed in ( + ( + "notify_all", + "had_notify_all", + "saved_notify_all", + "installed_notify_all", + installed_all, + ), + ( + "notify", + "had_notify", + "saved_notify", + "installed_notify", + installed_notify, + ), + ): + changed.append( + (name, getattr(self, had_name), getattr(self, saved_name), installed) + ) + setattr(self, installed_name, installed) + setattr(condition, name, installed) + except BaseException: + for name, had_instance, saved, installed in changed: + _rollback_condition_hook(condition, name, had_instance, saved, installed) + raise + + def _hooks_installed(self) -> bool: + condition = self.condition_ref() + return condition is not None and ( + getattr(condition, "notify_all", None) is self.installed_notify_all + and getattr(condition, "notify", None) is self.installed_notify + ) + + def _rehook(self) -> None: + """Wrap current methods with fresh wrappers after a caller replaces hooks.""" + condition = self.condition_ref() + if condition is None: + return + attributes = _instance_attributes(condition) + changed: list[tuple[str, bool, Any, Any]] = [] + try: + for name, original_name, had_name, saved_name, installed_name in ( + ( + "notify_all", + "original_notify_all", + "had_notify_all", + "saved_notify_all", + "installed_notify_all", + ), + ( + "notify", + "original_notify", + "had_notify", + "saved_notify", + "installed_notify", + ), + ): + installed = getattr(self, installed_name) + if getattr(condition, name, None) is installed: + continue + had_instance = name in attributes + saved = attributes.get(name) + method = getattr(condition, name) + fresh = self._new_hook(method) + # Journal the attempted assignment before invoking a setter that + # may store the wrapper and then raise. + changed.append((name, had_instance, saved, fresh)) + setattr(self, had_name, had_instance) + setattr(self, saved_name, saved) + setattr(self, original_name, _weak_bound_method(method)) + setattr(self, installed_name, fresh) + setattr(condition, name, fresh) + except BaseException: + for name, had_instance, saved, installed in changed: + _rollback_condition_hook(condition, name, had_instance, saved, installed) + raise + + def record(self) -> None: + # Sample the clock and snapshot subscribers in one critical section, so + # a subscriber registered during this dispatch cannot receive its time. + with self._subscription_lock: + now = monotonic() + subscribers = tuple( + (deadline, entry) + for deadline, entries in self.subscribers.items() + for entry in entries + ) + staged: list[tuple[_SignalDeadline, float, _Verification]] = [] + for deadline, (watched, backing, caller) in subscribers: + if not bool(getattr(watched, "_flag", False)): + continue + if _event_has_standard_predicate(caller): + # The raw flag is the standard predicate; it is safe to verify + # here even while the condition lock is held. + staged.append((deadline, now, bool(getattr(caller, "_flag", False)))) + continue + predicate = _thread_predicate_for_notification(caller) + if predicate is None: + staged.append((deadline, now, False)) + else: + # An override may re-enter the condition lock, so defer its + # predicate to a checkpoint outside notification. + staged.append((deadline, now, predicate)) + _stage_signals(tuple(staged)) + _drain_signals() + + def _dispatch(self, original: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + if self._dispatching: + return original(*args, **kwargs) + self._dispatching = True + try: + self.record() + return original(*args, **kwargs) + finally: + self._dispatching = False + + def notify_all(self) -> None: + self._dispatch(self.original_notify_all) + + def notify(self, *args: Any, **kwargs: Any) -> None: + self._dispatch(self.original_notify, *args, **kwargs) + + def restore(self) -> None: + # Retained for explicit cleanup; teardown never unwraps caller hooks. + condition = self.condition_ref() + if condition is None: + return + # One failing restoration must not hide the other one. + error: Exception | None = None + for name, had_instance, saved, installed in ( + ("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( + condition, name, had_instance, _restore_bound_method(saved), installed + ) + except Exception as exc: + if error is None: + error = exc + if error is not None: + raise error + + +_notify_trackers = _WeakTrackerRegistry() + + +def _discover_thread_conditions( + event: threading.Event, +) -> tuple[tuple[threading.Condition, Any, bool], ...]: + """Snapshot the conditions reachable from an event's own attributes. + + Backing events are retained even when they share the supplied event's + condition: the condition only needs one hook, but each exposed event's raw + flag can independently prove a notification. + """ + with _sync_set_lock: + attributes = tuple(_instance_attributes(event).values()) + own_condition = getattr(event, "_cond", None) + watched: list[tuple[threading.Condition, Any, bool]] = [] + seen_events: set[int] = {id(event)} + if isinstance(own_condition, threading.Condition): + watched.append((own_condition, event, False)) + for value in attributes: + if not isinstance(value, threading.Event) or id(value) in seen_events: + continue + backing_condition = getattr(value, "_cond", None) + if not isinstance(backing_condition, threading.Condition): + continue + seen_events.add(id(value)) + watched.append((backing_condition, value, True)) + return tuple(watched) + + +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) + conditions: dict[int, threading.Condition] = {} + for tracked, _watched_event, _backing in watched: + conditions.setdefault(id(tracked), tracked) + deadline.conditions = tuple(conditions.values()) + added: list[tuple[_ConditionSignalTracker, tuple[Any, bool, Any]]] = [] + with _notify_lock: + try: + for tracked, watched_event, backing in watched: + tracker = _notify_trackers.get(tracked) + if tracker is None: + tracker = _ConditionSignalTracker(tracked) + _notify_trackers[tracked] = tracker + elif not tracker._hooks_installed(): + tracker._rehook() + entry = (watched_event, backing, event) + with tracker._subscription_lock: + tracker.subscribers.setdefault(deadline, []).append(entry) + added.append((tracker, entry)) + except BaseException: + for tracker, entry in added: + with tracker._subscription_lock: + entries = tracker.subscribers.get(deadline) + if entries is not None: + entries[:] = [item for item in entries if item is not entry] + if not entries: + tracker.subscribers.pop(deadline, None) + raise + return deadline + + +def _untrack_thread_signal(event: threading.Event, deadline: _SignalDeadline) -> None: + """Detach one deadline and restore SDK hooks when the last observer leaves.""" + with _notify_lock: + for condition in deadline.conditions: + tracker = _notify_trackers.get(condition) + if tracker is None: + continue + with tracker._subscription_lock: + tracker.subscribers.pop(deadline, None) + empty = not tracker.subscribers + if empty: + # The tracker stays registered for reuse, but an idle wrapper + # must not keep acquiring SDK locks on later caller `set()`s. + # `_restore_method` restores each still-owned hook independently + # and leaves caller replacements untouched. + try: + tracker.restore() + except Exception: + pass + deadline.conditions = () + + +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, entry_flag: bool, entry_time: float +) -> bool: + """Install observers and verify a flag first seen during setup. + + The caller samples the entry flag before validation; this helper only + records signals first observed after observer setup, and bounds them by the + deadline derived from that original sample. Observers are registered without + holding any caller-owned condition lock, so a setter that holds its own lock + while forwarding to a backing event cannot deadlock setup. + """ + standard_predicate = _event_has_standard_predicate(event) + _track_sync_cancel(event, deadline) + sampled = monotonic() + flagged = bool(getattr(event, "_flag", False)) + if entry_flag: + with _notify_lock: + deadline.record_entry(entry_time) + elif flagged and sampled < deadline.end: + if standard_predicate or _thread_event_is_set(event): + _publish_signals(((deadline, sampled),)) + _drain_signals() + return entry_flag + + +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.""" + if event is None: + return False + _drain_signals() + _verify_deferred_signals(deadline, end) + if deadline.signalled_at is not None: + return True + if 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]: + """Resolve deferred predicates, drain publications, then read the latch.""" + _drain_signals() + _verify_deferred_signals(deadline, deadline.end) + with _notify_lock: + return deadline.signalled_at, monotonic() + + +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 observers installed on the event's + # condition. Waiting on it never calls an overridable wait() and never polls + # in short slices; a set/clear is latched by the notification timestamp. + end = min(monotonic() + timeout, deadline.end) + while True: + if _record_signal_before(event, deadline, deadline.end): + 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 _async_flag_is_set(event: AsyncEvent) -> bool: + """Read asyncio's raw flag without calling an overridable predicate.""" + return bool(getattr(event, "_value", getattr(event, "_flag", False))) + + +def _initial_async_signal( + event: AsyncEvent, deadline: _SignalDeadline, entry_flag: bool, entry_time: float +) -> bool: + """Record a flag first observed after validation against the entry deadline.""" + now = monotonic() + if entry_flag: + with _notify_lock: + deadline.record_entry(entry_time) + elif _async_flag_is_set(event) and now < deadline.end and _event_is_set(event): + _publish_signals(((deadline, now),)) + _drain_signals() + return entry_flag + + +def _check_async_event_loop(event: asyncio.Event) -> None: + """Reject foreign waiters before native registration can bind the event. + + The caller holds ``_async_future_lock``, so a competing native ``wait()`` + cannot register a waiter between the scan and the SDK attaching its own. + """ + loop = async_get_running_loop() + for pending in getattr(event, "_waiters", ()) or (): + pending_loop = getattr(pending, "_loop", None) + if pending_loop is not None and pending_loop is not loop: + raise RuntimeError("cancel_event has waiters on a different event loop.") + event_loop = getattr(event, "_loop", None) + if event_loop is not None and event_loop is not loop: + raise RuntimeError("cancel_event is already bound to a different event loop.") + binder = getattr(event, "_get_loop", None) + if binder is not None: + try: + binder() + except BaseException as error: + # A failing override may have bound the event before raising. Roll + # back only a binding it created here, never a preexisting one, and + # preserve the original exception for non-loop failures. + if event_loop is None and getattr(event, "_loop", None) is loop: + event._loop = None # type: ignore[attr-defined] + if isinstance(error, RuntimeError): + raise RuntimeError( + "cancel_event is already bound to a different event loop." + ) from None + raise + + +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] = {} + # One predicate verification per set() dispatch. The first future a + # dispatch visits starts the generation; seeing a future again means a + # back-to-back pulse began, so the predicate must be re-evaluated. + self.verification: bool | None = None + self.dispatch_seen: set[int] = set() + + def begin_dispatch(self, future: AsyncFuture[Any]) -> None: + key = id(future) + if key in self.dispatch_seen: + self.dispatch_seen.clear() + self.verification = None + self.dispatch_seen.add(key) + + def reset_dispatch(self) -> None: + self.dispatch_seen.clear() + self.verification = None + + def add(self, deadline: _SignalDeadline) -> None: + self.counts[deadline] = self.counts.get(deadline, 0) + 1 + 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: + # The caller has already checked this dispatch's verification cache. + # Publishing is bounded by the number of deadlines, never by the waiter + # deque or by another pending future in the same dispatch. + with _async_future_lock: + deadlines = tuple(self.deadlines) + _publish_signals(tuple((deadline, now) for deadline in deadlines)) + + def defer(self, now: float) -> None: + """Wake watchers without treating an overridden predicate as evidence.""" + with _async_future_lock: + deadlines = tuple(self.deadlines) + _stage_signals(tuple((deadline, now, False) for deadline in deadlines)) + _drain_signals() + + +class _AsyncFutureWatch: + """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: + # asyncio.Event.set() completes watched futures without yielding. + # The first future in a dispatch verifies the supplied predicate and + # publishes once for all deadlines; later futures reuse that result. + # A rejected native pulse leaves the future pending so a later + # verified pulse can still complete it. + if not _async_flag_is_set(event): + return + self.signal.begin_dispatch(self.future) + if self.signal.verification is None: + if _event_is_set(event): + self.signal.note(monotonic()) + self.signal.verification = True + else: + self.signal.defer(monotonic()) + self.signal.verification = False + if self.signal.verification: + self.original(result) + + 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 + # Registration happens outside a set() dispatch, so it starts a new + # publication generation. No overridable predicate is consulted here. + signal.reset_dispatch() + 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 _AsyncLoopBinding: + """SDK ownership of a native event binding, shared by every SDK waiter.""" + + def __init__(self, loop: Any, owned: bool) -> None: + self.loop = loop + self.owned = owned + self.count = 0 + self.cleanup_armed = False + self.watched: set[int] = set() + + +class _AsyncBindingRegistry: + """Identity-keyed weak bindings, including events that are unhashable.""" + + def __init__(self) -> None: + self._events: dict[int, Any] = {} + self._bindings: dict[int, _AsyncLoopBinding] = {} + + def _discard(self, key: int, binding: _AsyncLoopBinding | None = None) -> None: + if binding is None or self._bindings.get(key) is binding: + self._bindings.pop(key, None) + self._events.pop(key, None) + + def __setitem__(self, event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + key = id(event) + self._discard(key) + + def event_gone(_: Any) -> None: + self._discard(key) + + self._events[key] = weak_ref(event, event_gone) + self._bindings[key] = binding + + def get(self, event: AsyncEvent) -> _AsyncLoopBinding | None: + key = id(event) + event_ref = self._events.get(key) + binding = self._bindings.get(key) + if event_ref is None or binding is None: + return None + if event_ref() is not event: + self._discard(key) + return None + return binding + + def discard(self, event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + self._discard(id(event), binding) + + def __contains__(self, event: object) -> bool: + return isinstance(event, asyncio.Event) and self.get(event) is not None + + def __delitem__(self, event: AsyncEvent) -> None: + self._discard(id(event)) + + +_async_loop_bindings = _AsyncBindingRegistry() + + +class _AsyncSignalWaiter: + """A future registered directly on the event, without driving overrides.""" + + def __init__(self) -> None: + self.event: AsyncEvent | None = None + self.future: AsyncFuture[Any] | None = None + self.binding: _AsyncLoopBinding | None = None + + +def _schedule_binding_recheck(event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + """Ask the owning loop to recheck native waiters once they settle.""" + try: + binding.loop.call_soon(_clear_temporary_async_binding, event, binding) + except RuntimeError: + pass + + +def _arm_native_waiter_cleanup( + event: AsyncEvent, + binding: _AsyncLoopBinding, + waiters: tuple[AsyncFuture[Any], ...], + *, + recheck: bool, +) -> None: + """Watch each pending native waiter, including ones added after teardown. + + Pending futures wake cleanup through their completion callbacks. Only + already-completed futures that still occupy the waiter deque need an + immediate retry, so an unset event never causes per-turn rescheduling. + """ + binding.cleanup_armed = True + completed = False + for pending in waiters: + key = id(pending) + if key in binding.watched: + continue + binding.watched.add(key) + + def done(_: Any, key: int = key) -> None: + binding.watched.discard(key) + _schedule_binding_recheck(event, binding) + + try: + pending.add_done_callback(done) + except Exception: + binding.watched.discard(key) + continue + if pending.done(): + completed = True + if recheck and completed: + _schedule_binding_recheck(event, binding) + + +def _clear_temporary_async_binding(event: AsyncEvent, binding: _AsyncLoopBinding) -> None: + """Clear a temporary ownership once every native waiter has drained.""" + with _async_future_lock: + if binding.count or _async_loop_bindings.get(event) is not binding: + return + # A done future can still occupy the native waiter deque until its task + # resumes and removes it; ownership must survive that interval too. + waiters = tuple(getattr(event, "_waiters", None) or ()) + if waiters: + _arm_native_waiter_cleanup(event, binding, waiters, recheck=True) + return + _async_loop_bindings.discard(event, binding) + if binding.owned and getattr(event, "_loop", None) is binding.loop: + event._loop = None # type: ignore[attr-defined] + + +def _release_async_binding(waiter: _AsyncSignalWaiter) -> None: + """Release one SDK waiter, retaining ownership until native waiters drain.""" + binding = waiter.binding + event = waiter.event + waiter.binding = None + if binding is None or event is None: + return + binding.count -= 1 + if binding.count > 0: + return + waiters = tuple(getattr(event, "_waiters", None) or ()) + if waiters: + _arm_native_waiter_cleanup(event, binding, waiters, recheck=True) + return + _clear_temporary_async_binding(event, binding) + + +def _watch_async_waiter(event: AsyncEvent, deadline: _SignalDeadline) -> _AsyncSignalWaiter: + """Observe a signal with native loop ownership shared by all SDK waiters.""" + waiter = _AsyncSignalWaiter() + if not isinstance(event, asyncio.Event): + return waiter + with _async_future_lock: + binding = _async_loop_bindings.get(event) + previous_loop = getattr(event, "_loop", None) + _check_async_event_loop(event) + loop = async_get_running_loop() + if binding is None: + binding = _AsyncLoopBinding( + loop, previous_loop is None and getattr(event, "_loop", None) is loop + ) + _async_loop_bindings[event] = binding + elif binding.loop is not loop: + # A native check may have rebound a temporarily cleared event to + # this loop; undo that before rejecting the foreign registration. + if previous_loop is None and getattr(event, "_loop", None) is loop: + event._loop = None # type: ignore[attr-defined] + raise RuntimeError("cancel_event is already bound to a different event loop.") + binding.count += 1 + waiter.event = event + waiter.binding = binding + try: + waiters = getattr(event, "_waiters", None) + if waiters is None: + waiters = deque() + event._waiters = waiters + created_future: AsyncFuture[Any] = loop.create_future() + waiters.append(created_future) + waiter.future = created_future + _watch_async_future(created_future, event, deadline) + except BaseException: + future = waiter.future + if future is not None: + try: + _unwatch_async_future(future, deadline) + except Exception: + pass + waiters = getattr(event, "_waiters", None) + if waiters is not None: + try: + waiters.remove(future) + except ValueError: + pass + future.cancel() + _release_async_binding(waiter) + waiter.event = None + waiter.future = None + 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() + _release_async_binding(waiter) + waiter.event = None + waiter.future = None + + +def _schedule_cutoff_timer( + loop: Any, when: float, callback: Any, args: tuple[Any, ...], *, deadline: float +) -> Any: + """Schedule one helper cutoff, with its absolute deadline visible to tests.""" + return loop.call_at(when, callback, *args) + + +async def _async_wait_for_event( + 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 = _schedule_cutoff_timer( + loop, + loop.time() + max(0.0, cutoff - monotonic()), + timer.set_result, + (None,), + deadline=cutoff, + ) + waiter = _AsyncSignalWaiter() + try: + waiter = _watch_async_waiter(event, deadline) + 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 +1815,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 +1824,113 @@ 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, once argument validation has succeeded. + cancel_event then stops the wait before another request. It is checked + before each poll, during the backoff, and after each read. An in-flight + read is not interrupted: cancellation waits for that read to finish, + including transport retries and their delays. Those + delays count toward the overall wait deadline rather than a single HTTP + timeout. A cancellable wait samples its deadline before validation, so + validation and URL construction count toward the polling budget and can + exhaust it without a request; notifications observed during setup use + that same deadline. Without a cancellation event, validation and URL + construction happen before the timeout clock starts. A signal first + delivered at or after the deadline is ignored; it does not change the + wait's result, override a head mismatch, or suppress a read error that + would otherwise propagate. + + The signal must notify a condition reachable from the event passed here. + Call ``set()`` on that event. The SDK never assigns to its ``set()`` + 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. A subclass whose ``is_set()`` directly delegates to the + standard predicate is verified from the raw flag under the condition; + other overrides are checked after the lock is released. An override + that hides the event's flag is not supported. """ - if not math.isfinite(timeout) or timeout < 0: - raise ValueError("The review timeout must be a finite nonnegative number of seconds.") - _head_commit(head_commit_sha) - url = _review_url(self._base_url, organization_id, review_id) - last: CustomerReviewDetail | None = None - deadline = _transport.DEADLINE.set(monotonic() + timeout) - interval = 5.0 + # A cancellable wait's budget and entry state are both sampled before + # validation, so a slow conversion cannot extend the deadline or turn a + # flag raised during validation into an entry cancellation. Observers are + # installed before that conversion and arithmetic so a set()/clear() + # during either one is still latched. + start = monotonic() if cancel_event is not None else None + if cancel_event is not None and not isinstance(cancel_event, threading.Event): + raise TypeError("cancel_event must be a threading.Event.") + entry_flag = _thread_event_is_set(cancel_event) if cancel_event is not None else False + read_signal = _SignalDeadline(float("inf")) + initially_set = False + deadline_set = False try: + if cancel_event is not None: + assert start is not None + initially_set = _initial_sync_signal(cancel_event, read_signal, entry_flag, start) + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The review timeout must be a finite nonnegative number of seconds." + ) + if cancel_event is not None: + assert start is not None + deadline_at = start + timeout + read_signal.cap(deadline_at) + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + else: + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + deadline_at = monotonic() + timeout + if initially_set: + return _stopped(url, None, review_id, head_commit_sha) + last: CustomerReviewDetail | None = None + deadline = _transport.DEADLINE.set(deadline_at) + deadline_set = True + interval = 5.0 while (_transport.remaining() or 0) > 0: + if _cancellation_signal(cancel_event, read_signal): + return _stopped(url, last, review_id, head_commit_sha) try: last = self.get_review(organization_id, review_id) except ProoflineError as error: + if error.status in (401, 403): + raise + cancelled = _cancellation_signal(cancel_event, read_signal) + if _invalid_response(error) and cancelled: + raise + 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: + if deadline_set: + _transport.DEADLINE.reset(deadline) class AsyncProoflineClient(AsyncOperations): @@ -941,30 +2290,112 @@ async def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + cancel_event: AsyncEvent | None = None, ) -> ReviewOutcome: - if not math.isfinite(timeout) or timeout < 0: - raise ValueError("The review timeout must be a finite nonnegative number of seconds.") - _head_commit(head_commit_sha) - url = _review_url(self._base_url, organization_id, review_id) - last: CustomerReviewDetail | None = None - deadline = _transport.DEADLINE.set(monotonic() + timeout) - interval = 5.0 + """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, once argument validation has succeeded. + cancel_event then stops the wait before another request. It is checked + before each poll, during the backoff, and after each read. An in-flight + read is not interrupted. A cancellable wait samples its deadline before + validation, so validation and URL + construction count toward the polling budget and can exhaust it without + a request; notifications observed during setup use that same deadline. + Without a cancellation event, validation and URL construction happen + before the timeout clock starts. A signal first delivered at or after + the deadline is ignored; it does not change the wait's result, override + a head mismatch, or suppress a read error that would otherwise propagate. + The signal must notify waiters + registered on the event passed here: call ``set()`` on that event and do + not only mutate a backing object's flag, which can still be observed at + a check after a read but will not wake an in-progress backoff. Native + event registration establishes loop ownership under the waiter lock; + an event or existing waiter already bound to another loop is rejected + before the early check or the first request. An SDK-owned temporary + binding is released when its last waiter is removed; if native waiters + remain, ownership is retained until they drain, so reuse on another loop + is possible only after both SDK and native waiters are gone. Native + delivery verifies the supplied event's predicate inline; a rejected + pulse leaves the waiter pending for a later verified signal. + """ + # A cancellable wait's budget and entry state are both sampled before + # validation, so a slow conversion cannot extend the deadline or turn a + # flag raised during validation into an entry cancellation. Observers are + # installed before that conversion and arithmetic so a set()/clear() + # during either one is still latched. + start = monotonic() if cancel_event is not None else None + if cancel_event is not None and not isinstance(cancel_event, AsyncEvent): + raise TypeError("cancel_event must be an asyncio.Event.") + entry_flag = _event_is_set(cancel_event) if cancel_event is not None else False + read_signal = _SignalDeadline(float("inf")) + read_waiter = _AsyncSignalWaiter() + initially_set = False + deadline_set = False try: + if cancel_event is not None: + assert start is not None + read_waiter = _watch_async_waiter(cancel_event, read_signal) + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The review timeout must be a finite nonnegative number of seconds." + ) + if cancel_event is not None: + assert start is not None + deadline_at = start + timeout + read_signal.cap(deadline_at) + initially_set = _initial_async_signal(cancel_event, read_signal, entry_flag, start) + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + else: + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + deadline_at = monotonic() + timeout + if initially_set: + return _stopped(url, None, review_id, head_commit_sha) + if cancel_event is not None and _cancellation_signal(cancel_event, read_signal): + return _stopped(url, None, review_id, head_commit_sha) + last: CustomerReviewDetail | None = None + deadline = _transport.DEADLINE.set(deadline_at) + deadline_set = True + interval = 5.0 while (_transport.remaining() or 0) > 0: + if _cancellation_signal(cancel_event, read_signal): + return _stopped(url, last, review_id, head_commit_sha) try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: + if error.status in (401, 403): + raise + cancelled = _cancellation_signal(cancel_event, read_signal) + if _invalid_response(error) and cancelled: + raise + 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: + if cancel_event is not None: + _unwatch_async_waiter(read_waiter, read_signal) + finally: + if deadline_set: + _transport.DEADLINE.reset(deadline) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..909603ed 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2,6 +2,7 @@ import asyncio import csv +import gc import gzip import inspect import io @@ -14,6 +15,7 @@ import time import tomllib import traceback +import weakref from collections.abc import AsyncIterator from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta @@ -106,10 +108,93 @@ 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 without masking the probe's own failure. + + An expected cancellation is ignored; any other sender error is printed so + its traceback survives, and only raised when the probe itself succeeded. + """ + failure: BaseException | None = None + if check: + try: + await asyncio.wait_for(sender, 1.0) + except BaseException as error: + failure = error + sender.cancel() + results = await asyncio.gather(sender, return_exceptions=True) + for outcome in results: + if isinstance(outcome, BaseException) and not isinstance(outcome, asyncio.CancelledError): + if outcome is not failure: + print("unexpected sender error:", file=sys.stderr) + traceback.print_exception( + type(outcome), outcome, outcome.__traceback__, file=sys.stderr + ) + if failure is None and check: + failure = outcome + if failure is not None: + raise failure + + +class ManualTimer: + """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, + deadline: float | None = None, + ) -> None: + self.callback = callback + self.args = args + self.kwargs = kwargs or {} + self.owner = getattr(callback, "__self__", None) + self.deadline = deadline + self.cancelled = False + self.fired = False + + def fire(self) -> None: + if not self.cancelled and not self.fired: + self.fired = True + self.callback(*self.args, **self.kwargs) + + def cancel(self) -> None: + self.cancelled = True + + +def patch_helper_timer( + monkeypatch: pytest.MonkeyPatch, loop: Any, deadlines: tuple[float, ...] = () +) -> list[ManualTimer]: + """Control named helper cutoffs through the helper's explicit schedule hook.""" + timers: list[ManualTimer] = [] + real_schedule = client_module._schedule_cutoff_timer + + def schedule( + hooked_loop: Any, _when: float, callback: Any, args: tuple[Any, ...], *, deadline: float + ) -> Any: + assert hooked_loop is loop + if deadline in deadlines: + timer = ManualTimer(callback, args, None, deadline) + timers.append(timer) + return timer + return real_schedule(loop, _when, callback, args, deadline=deadline) + + monkeypatch.setattr(client_module, "_schedule_cutoff_timer", schedule) + return timers + + class Clock: def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: self.now = 100.0 self.delays: list[float] = [] + self.publication = threading.Event() + self.publication_at: float | None = None + self.deadline_reached = threading.Event() monkeypatch.setattr(client_module, "monotonic", lambda: self.now) monkeypatch.setattr(_transport, "monotonic", lambda: self.now) monkeypatch.setattr(_sync_http, "monotonic", lambda: self.now) @@ -117,6 +202,59 @@ 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 publish(self) -> None: + """Mark a cancellation as published, preserving the first pending time.""" + if self.publication_at is None: + self.publication_at = self.now + self.publication.set() + + def reach_deadline(self) -> None: + """Explicitly authorize the fake async wait to advance to its deadline.""" + self.deadline_reached.set() + + def wait_for_event(self, event: Any, timeout: float, deadline: Any | None = None) -> bool: + woke = bool(event.is_set()) + if woke and deadline is not None: + 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 + + def _record_async_arrival( + self, + event: Any, + cutoff: float, + signal: Any | None, + published: bool = False, + arrival: float | None = None, + ) -> bool: + when = self.now if arrival is None else arrival + if not published or not event.is_set() or when >= cutoff: + return False + if signal is not None: + signal.record(min(when, signal.end)) + return True + + async def async_wait_for_event( + self, event: Any, cutoff: float, signal: Any | None = None + ) -> bool: + if self.publication.is_set(): + self.publication.clear() + arrival, self.publication_at = self.publication_at, None + if self._record_async_arrival(event, cutoff, signal, published=True, arrival=arrival): + return True + if not self.deadline_reached.is_set(): + raise AssertionError("advance the fake async deadline explicitly") + self.deadline_reached.clear() + self.sleep(max(0.0, cutoff - self.now)) + return self._record_async_arrival(event, cutoff, signal) def sleep(self, delay: float) -> None: self.delays.append(delay) @@ -1397,6 +1535,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,1175 +1562,4827 @@ 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, task: Any | None = None) -> None: + for _ in range(200): + if task is not None and task.done(): + # Surface the original helper failure instead of a generic timeout. + await task + if predicate(): + return + await asyncio.sleep(0) + raise AssertionError("the wait helper did not reach the expected state") + + +def test_async_wait_for_event_latches_a_set_then_clear() -> None: + # A helper that stops responding to cancellation must not hang pytest. + code = """ +import asyncio +import sys + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +async def main(): + now = [100.0] + client.monotonic = lambda: now[0] + event = asyncio.Event() + task = asyncio.create_task(client._async_wait_for_event(event, 110.0)) + for _ in range(200): + if task.done(): + await task + if event._waiters: + break + await asyncio.sleep(0) + else: + raise AssertionError("the helper never registered a waiter") + now[0] = 100.5 + event.set() + event.clear() + assert await task is True + assert "set" not in vars(event) + print("OK") + +asyncio.run(main()) +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +async def test_async_wait_for_event_ignores_a_signal_after_cutoff( + 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] + event = asyncio.Event() + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + task = asyncio.create_task(real_wait(event, cutoff)) + try: + await wait_until(lambda: bool(event._waiters), task) + 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), task) + 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), task) + 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), task) + 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), task) + 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) + event = asyncio.Event() + setter = event.set + short_cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (short_cutoff,)) + first = asyncio.create_task(real_wait(event, short_cutoff)) + second = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: + await wait_until(lambda: len(event._waiters) >= 2, first) + 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) + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + event = asyncio.Event() + setter = event.set + task = asyncio.create_task(real_wait(event, cutoff)) + try: + await wait_until(lambda: bool(event._waiters), task) + future = next(iter(event._waiters)) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + 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 + +def test_condition_hook_ignores_a_late_flag_after_the_setter_returns( + 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 + clock = Clock(monkeypatch) - original_resolution = socket.getaddrinfo - resolution_started = threading.Event() - resolution_released = threading.Event() - resolution_finished = threading.Event() - resolutions: list[bool] = [] + class LateFlagEvent(threading.Event): + def set(self) -> None: + clock.now = 101.5 + super().set() - 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() + 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) - 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 == [] +async def test_async_wait_for_event_supports_a_read_only_setter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop()) + + class ReadOnlySetEvent(asyncio.Event): + @property + def set(self) -> Any: + return asyncio.Event.set.__get__(self, asyncio.Event) + + event = ReadOnlySetEvent() + task = asyncio.create_task(real_wait(event, clock.now + 10.0)) + try: + await wait_until(lambda: bool(event._waiters), task) + 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( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) -def test_sync_transport_connects_to_each_resolved_address_under_the_original_host( + 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() + cutoff = clock.now + 0.05 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + task = asyncio.create_task(real_wait(event, cutoff)) + try: + await wait_until(lambda: bool(event._waiters), task) + event.set() + assert event.is_set() + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + for timer in timers: + timer.cancel() + + +def test_condition_observation_preserves_a_replacement_setter( 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() + 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": - 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)), - ] - if host == "scoped.proofline.invalid": - return [ - (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", port, 0, 41)), - (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", port, 0, 41)), - (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", port, 0, 42)), - ] - if host in {"fe80::1", "fe80::1%41", "fe80::1%42"}: - # Translate synthetic interface scopes at the OS boundary; TCP stays real. - scoped_connections.append(host) - if host == "fe80::1": - raise socket.gaierror(socket.EAI_NONAME, "The IPv6 scope is missing") - address = "127.0.0.2" if host == "fe80::1%41" else "127.0.0.1" - return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port))] - return original(host, port, *args, **kwargs) + def replacement() -> None: + return None - original = socket.getaddrinfo - monkeypatch.setattr(socket, "getaddrinfo", resolve) - with Server(lambda request, index: Reply(body=finding())) as server: - port = server.url.rsplit(":", 1)[1] - with httpx2.Client(transport=_sync_http.Transport()) as client: - response = client.get(f"http://service.proofline.invalid:{port}/finding") - assert response.json()["id"] == str(FINDING) - assert server.requests[0].headers["Host"] == f"service.proofline.invalid:{port}" - assert ("service.proofline.invalid", "proofline-dns") in lookups - response = client.get(f"http://scoped.proofline.invalid:{port}/finding") - assert response.json()["id"] == str(FINDING) - assert server.requests[1].headers["Host"] == f"scoped.proofline.invalid:{port}" - assert ("scoped.proofline.invalid", "proofline-dns") in lookups - assert scoped_connections == ["fe80::1%41", "fe80::1%42"] - with pytest.raises(httpx2.TransportError) as raised: - client.get(f"http://missing.proofline.invalid:{port}/finding") - assert not isinstance(raised.value, httpx2.TimeoutException) - with pytest.raises(httpx2.TransportError): - client.get(f"http://127.0.0.1:{closed_port}/finding") - assert len(server.requests) == 2 + 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 -@MODES -async def test_cursor_pagination_preserves_filters_and_refuses_cycles_or_bounds(mode: str) -> None: - def respond(request: Request, index: int) -> Reply: - assert urlsplit(request.path).path == f"/api/v1/organizations/{ORG}/reviews" - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - query = parse_qs(urlsplit(request.path).query) - assert query["repository"] == [str(REPOSITORY)] - assert query["status"] == ["COMPLETED"] - assert query["limit"] == ["2"] - assert query["query"] == [STRUCTURED_QUERY] - assert query["search"] == ["text & space"] - if index == 0: - assert "cursor" not in query - else: - assert query["cursor"] == ["opaque+/cursor"] - return Reply( - body=page(cursor="opaque+/cursor" if index == 0 else None, truncated=index == 0) - ) +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) + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + event = asyncio.Event() + + def replacement() -> None: + return None + + event.set = replacement # type: ignore[method-assign] + task = asyncio.create_task(real_wait(event, cutoff)) + try: + await wait_until(lambda: bool(event._waiters), task) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + assert event.set is replacement + 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) - with Server(respond) as server: - async with session(mode, server.url) as client: - items = await collect( - client, - page_size=2, - filters={ - "repository": REPOSITORY, - "status": "COMPLETED", - "query": STRUCTURED_QUERY, - "search": "text & space", - }, - ) - assert [item.id for item in items] == [REVIEW, REVIEW] - assert len(server.requests) == 2 - for cursor in ["repeated", None]: - with Server( - lambda request, index: Reply(body=page(cursor=cursor, truncated=True)) - ) as server: - async with session(mode, server.url) as client: - with pytest.raises(ProoflineError) as raised: - await collect(client) - assert raised.value.type == "urn:proofline:sdk:invalid-pagination" - assert len(server.requests) <= 2 - with Server( - lambda request, index: Reply(body=page(cursor=str(index), truncated=True)) - ) as server: - async with session(mode, server.url) as client: - with pytest.raises(ProoflineError) as raised: - await collect(client, max_pages=2) - assert raised.value.type == "urn:proofline:sdk:pagination-limit" - assert len(server.requests) == 2 - two_items = page() - two_items["items"].append(dict(two_items["items"][0])) - with Server(lambda request, index: Reply(body=two_items)) as server: - async with session(mode, server.url) as client: - with pytest.raises(ProoflineError) as raised: - await collect(client, max_items=1, filters={"cursor": "initial"}) - assert raised.value.type == "urn:proofline:sdk:pagination-limit" + 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 -def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN) - with ProoflineClient() as client: - assert client._api.token.get_secret_value() == TOKEN - assert TOKEN not in repr(client._api) - for origin in [ - "http://api.example", - "http://localhost", - "http://127.0.0.1.example", - "https://user:password@example.com", - "https://example.com?token=secret", - "https://example.com/api/v1", - " https://example.com", - ]: - with pytest.raises(ValueError): - ProoflineClient(TOKEN, base_url=origin) - with ProoflineClient(TOKEN, base_url="http://[::1]:8080"): + +async def test_async_wait_for_event_unregisters_waiter_when_restore_raises( + monkeypatch: pytest.MonkeyPatch, +) -> None: + loop = asyncio.get_running_loop() + cutoff = loop.time() + 100.0 + timers = patch_helper_timer(monkeypatch, loop, (cutoff,)) + event = asyncio.Event() + real_restore = client_module._AsyncFutureWatch.restore + captured: list[Any] = [] + + 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, cutoff)) + try: + await wait_until(lambda: bool(event._waiters), task) + 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(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) + tracker = client_module._notify_trackers[condition] + try: + condition.notify_all = replacement # type: ignore[method-assign] + finally: + client_module._untrack_thread_signal(event, deadline) + assert condition.notify_all is replacement + assert condition.notify.__func__ is tracker.original_notify.__func__ + assert tracker.subscribers == {} + + +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 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) + + +def test_async_wait_for_event_propagates_external_cancellation() -> None: + # A cleanup lockup must be terminated by the parent test. The setter probe + # lives here too, so its cleanup is bounded by the same parent timeout. + code = """ +import asyncio +import sys +import time + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +async def main(): + event = asyncio.Event() + setter = event.set + task = asyncio.create_task(client._async_wait_for_event(event, time.monotonic() + 10.0)) + for _ in range(200): + if task.done(): + await task + if event._waiters: + break + await asyncio.sleep(0) + else: + raise AssertionError("the helper never registered a waiter") + assert event.set == setter + assert len(event._waiters) == 1 + task.cancel() + try: + await task + except asyncio.CancelledError: pass + else: + raise AssertionError("external cancellation was not propagated") + assert event.set == setter + assert not event._waiters + print("OK") + +asyncio.run(main()) +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" -@MODES -@pytest.mark.parametrize("size", [131_072, 131_073, 150_000, 8 * 1024 * 1024 + 1]) -async def test_csv_export_preserves_large_cells(mode: str, size: int) -> None: - claim = 'é, "quoted"\r\n' + "x" * size - row = { - "dataset_version": "1", - "organization_id": str(ORG), - "repository_id": str(REPOSITORY), - "review_id": str(REVIEW), - "assessment_id": str(ASSESSMENT), - "environment_id": str(ORG), - "finding_id": str(FINDING), - "claim": claim, - "impact": "Synthetic consequence", - "risk_domain": "SECURITY", - "severity": "HIGH", - "lifecycle_state": "OPEN", - "created_at": "2026-11-16T00:00:00Z", - "evidence_refs": "[]", - } - stream = io.StringIO(newline="") - writer = csv.DictWriter(stream, fieldnames=list(row)) - writer.writeheader() - writer.writerow(row) - text = stream.getvalue() - with Server( - lambda request, index: Reply( - body=text.encode(), - headers={ - "Content-Type": "text/csv", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-11-16T00:00:00Z", - "X-Proofline-Export-Next-Cursor": "opaque/+cursor", - }, - ) - ) as server: - async with session(mode, server.url) as client: - kwargs = {"from_time": "2026-11-01T00:00:00Z", "to_time": "2026-11-15T00:00:00Z"} - if size > 8 * 1024 * 1024: - with pytest.raises(ProoflineError) as caught: - await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) - assert caught.value.type == "urn:proofline:sdk:invalid-response" - else: - page = await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) - assert page.rows == [row] - assert page.text == text - assert page.version == 1 - assert page.settled_until == "2026-11-16T00:00:00Z" - assert page.next_cursor == "opaque/+cursor" - assert len(server.requests) == 1 +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 == [] -@MODES -async def test_export_pages_preserve_csv_and_refuse_foreign_cursor(mode: str) -> None: - def respond(request: Request, index: int) -> Reply: - query = parse_qs(urlsplit(request.path).query) - assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/findings?") - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - if query.get("cursor") == ["refused"]: - return Reply(status=404, body={"detail": "not found"}) - is_csv = query.get("format") == ["csv"] - return Reply( - body=( - b'dataset_version,claim\r\n2,"comma, quote "" and\nnewline"\r\n' - if is_csv - else b'{"dataset_version":2,"claim":"hello"}\n' - ), - headers={ - "Content-Type": "text/csv" if is_csv else "application/x-ndjson", - "X-Proofline-Export-Version": "2", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - "X-Proofline-Export-Next-Cursor": "opaque/+cursor", - }, - ) +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 == [] - with Server(respond) as server: - async with session(mode, server.url) as client: - kwargs = {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-25T00:00:00Z"} - exported = await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) - assert exported.rows[0]["claim"] == 'comma, quote " and\nnewline' - assert exported.next_cursor == "opaque/+cursor" - exported = await call( - client, "export_reviews", ORG, "findings", cursor=exported.next_cursor, **kwargs - ) - assert exported.rows[0]["dataset_version"] == 2 - assert exported.version == 2 - assert "cursor=opaque%2F%2Bcursor" in server.requests[1].path - with pytest.raises(ProoflineError) as caught: - await call(client, "export_reviews", ORG, "findings", cursor="refused", **kwargs) - assert caught.value.status == 404 +def test_sleep_with_cancel_latches_delivery_before_a_late_resume( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() -async def next_export(iterator: Any) -> Any: - return await anext(iterator) if hasattr(iterator, "__anext__") else next(iterator) + 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 == [] -@MODES -@pytest.mark.parametrize("format", ["csv", "ndjson"]) -async def test_export_iterator_preserves_filters_and_streams_empty_pages( - mode: str, format: str + +def test_sleep_with_cancel_records_a_captured_setter( + monkeypatch: pytest.MonkeyPatch, ) -> None: - def respond(request: Request, index: int) -> Reply: - assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/finding_outcomes?") - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - query = parse_qs(urlsplit(request.path).query) - assert query == { - "from": ["2026-10-01T00:00:00Z"], - "to": ["2026-10-25T00:00:00Z"], - "format": [format], - "group_by": ["repository"], - "cursor": ["resume/+cursor" if index == 0 else "next/+cursor"], - } - headers = { - "Content-Type": "text/csv" if format == "csv" else "application/x-ndjson", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - } - if index == 0: - headers["X-Proofline-Export-Next-Cursor"] = "next/+cursor" - body = ( - ( - b"dataset_version,claim\r\n" - if index == 0 - else b"dataset_version,claim\r\n1,hello\r\n" - ) - if format == "csv" - else (b"" if index == 0 else b'{"dataset_version":1,"claim":"hello"}\n') - ) - return Reply(body=body, headers=headers) + clock = Clock(monkeypatch) + event = threading.Event() + setter = event.set - with Server(respond) as server: + 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 + original_notify_all = condition.notify_all + original_notify = condition.notify + setter = event.set + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + 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 + tracker = client_module._notify_trackers[condition] + assert event.set == setter + # The tracker stays cached for reuse, but its hooks are restored when the + # last observer leaves so later caller `set()` calls never take SDK locks. + assert condition.notify_all == original_notify_all + assert condition.notify == original_notify + assert tracker.original_notify_all == original_notify_all + assert tracker.subscribers == {} + assert clock.delays == [] + + +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 + tracker = client_module._notify_trackers[condition] + assert clock.delays == [] + assert condition.notify_all.__func__ is tracker.original_notify_all.__func__ + assert condition.notify.__func__ is tracker.original_notify.__func__ + assert tracker.subscribers == {} + + +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 + tracker = client_module._notify_trackers[condition] + assert condition.notify_all == notify_all + assert tracker.original_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) + self.primary_notifications = 0 + original_notify_all = self._cond.notify_all + + def notify_all(*args, **kwargs): + self.primary_notifications += 1 + return original_notify_all(*args, **kwargs) + + self._cond.notify_all = notify_all + + def set(self): + # Publish on the backing condition only; never notify the primary one. + self._flag = True + 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] +woke_at = [] +waiting = threading.Event() +revealed = threading.Event() +real_wait = t.client_module._wait_for_event + +def wait_for_event(event_arg, timeout, deadline=None): + waiting.set() + woke = real_wait(event_arg, timeout, deadline) + woke_at.append(now[0]) + revealed.set() + return woke + +t.client_module._wait_for_event = wait_for_event + +def signal(): + if not ready.wait(2.0) or not waiting.wait(2.0): + failures.append("the waiter was never registered") + now[0] = 101.5 + event.set() + return + now[0] = 100.5 + event.set() + assert revealed.wait(2.0), "the waiter did not observe the backing wake" + now[0] = 102.0 + +thread = threading.Thread(target=signal, daemon=True) +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 woke_at and woke_at[0] < 101.0 +assert event.primary_notifications == 0 +backing_condition = event.backing._cond +tracker = t.client_module._notify_trackers[backing_condition] +assert backing_condition.notify_all == tracker.original_notify_all +assert tracker.subscribers == {} +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 + tracker = client_module._notify_trackers[condition] + assert condition.notify_all.__func__ is ClassCondition.notify_all + assert condition.notify.__func__ is ClassCondition.notify + assert tracker.original_notify_all.__func__ is ClassCondition.notify_all + assert tracker.original_notify.__func__ is ClassCondition.notify + assert tracker.subscribers == {} + + +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 + tracker = client_module._notify_trackers[condition] + assert tracker.saved_notify_all is notify_all + 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 + tracker = client_module._notify_trackers[event.marker._cond] + assert tracker.subscribers == {} + + +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 + calls = 0 + + class ReentrantEvent(threading.Event): + def is_set(self) -> bool: + nonlocal calls + calls += 1 + assert not held, "is_set called under the condition" + return bool(self._flag) + + event = ReentrantEvent() + + def wait_for_event(wait_event: Any, timeout: float, deadline: Any | None = None) -> bool: + nonlocal held + # The inherited setter establishes a true raw flag. Then notify again + # while the condition is held, so the tracker must take the true-flag + # branch without calling an overridden predicate under that lock. + threading.Event.set(wait_event) + with wait_event._cond: + held = True + try: + 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 + assert calls > 0 + + +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 + original_tracker = client_module._notify_trackers[original_condition] + assert clock.delays == [] + assert original_condition.notify_all == original_tracker.original_notify_all + 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() -> None: + # A deadlocked inline wait must be terminable by the parent test. + code = """ +import sys +import threading + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +clock = [100.0] +client.monotonic = lambda: clock[0] + + +class NeverWaitEvent(threading.Event): + def wait(self, timeout=None): + raise AssertionError("the SDK must not call the caller's wait() override") + + +event = NeverWaitEvent() +ready = threading.Event() +failures = [] +real_track = client._track_sync_cancel + + +def track(event_arg, deadline): + real_track(event_arg, deadline) + ready.set() + + +client._track_sync_cancel = track + + +def signal(): + if not ready.wait(2.0): + failures.append("the cancellation observers were never installed") + clock[0] = 101.5 + event.set() + return + clock[0] = 100.5 + event.set() + clock[0] = 102.0 + + +thread = threading.Thread(target=signal, daemon=True) +thread.start() +result = client._sleep_with_cancel(5, event, cutoff=101.0) +thread.join(2.0) +assert not thread.is_alive() +assert failures == [] +assert result is False +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +@MODES +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: - iterator = client.iter_export_pages( - ORG, - "finding_outcomes", - from_time="2026-10-01T00:00:00Z", - to_time="2026-10-25T00:00:00Z", - format=format, - cursor="resume/+cursor", - group_by="repository", - max_pages=2, + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event ) - assert not server.requests - first = await next_export(iterator) - assert first.rows == [] - assert first.next_cursor == "next/+cursor" - assert first.version == 1 - assert first.settled_until == "2026-10-25T00:00:00Z" - assert len(server.requests) == 1 - second = await next_export(iterator) - assert second.rows[0]["claim"] == "hello" - assert second.next_cursor is None - assert second.text.endswith("\n") - if mode == "sync": - with pytest.raises(StopIteration): - next(iterator) - else: - with pytest.raises(StopAsyncIteration): - await anext(iterator) - assert len(server.requests) == 2 + 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: + # Cleanup deadlocks must be terminated by the parent test. + code = """ +import asyncio +import sys +import time + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +event = asyncio.Event() + +async def run_once(): + task = asyncio.create_task( + client._async_wait_for_event(event, time.monotonic() + 10.0) + ) + for _ in range(200): + if task.done(): + await task + if event._waiters: + break + await asyncio.sleep(0) + else: + raise AssertionError("the waiter was not registered") + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + else: + raise AssertionError("cancellation was not propagated") + +asyncio.run(run_once()) +asyncio.run(run_once()) +assert event._loop is None +assert not event._waiters +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +async def test_async_wait_for_review_accepts_a_read_only_setter( + 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 + + +published = [] + + +def set_later(): + if not ready.wait(2.0): + event.set() + return + published.append(time.monotonic()) + event.set() + + +threading.Thread(target=set_later, daemon=True).start() +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 + ) + finished = time.monotonic() +assert published +assert finished - published[0] < 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)) + + async def wait_for_waiters(): + for _ in range(200): + if helper.done(): + await helper + if len(event._waiters) >= 2: + return + await asyncio.sleep(0) + raise AssertionError("the backoff waiter was never registered") + + try: + await wait_for_waiters() + ready.set() + return await helper + finally: + helper.cancel() + await asyncio.gather(helper, return_exceptions=True) + + t.client_module._async_wait_for_event = async_wait + + published = [] + + async def set_later(): + await asyncio.wait_for(ready.wait(), 2.0) + published.append(time.monotonic()) + event.set() + + setter = asyncio.create_task(set_later()) + verified = False + try: + with t.Server(lambda request, index: t.Reply(body=body)) as server: + async with t.session("async", server.url) as client: + result = await t.call( + client, "wait_for_review", t.ORG, t.REVIEW, timeout=5, cancel_event=event + ) + finished = time.monotonic() + assert published + assert finished - published[0] < 2.0 + assert ready.is_set() + assert len(server.requests) == 1 + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert result.review is not None + assert result.review.id == t.REVIEW + verified = True + finally: + await t.finish_sender(setter, check=verified) + +asyncio.run(main()) +print("OK") +""" + 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 -@pytest.mark.parametrize("failure", ["empty", "repeat", "resume", "cycle", "bound", "refused"]) -async def test_export_iterator_refuses_invalid_continuations_and_bounds( - mode: str, failure: str +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 failure == "refused": - return Reply(status=404, body={"detail": "not found"}) - cursor = { - "empty": "", - "repeat": "next", - "resume": "initial", - "cycle": "a" if index % 2 == 0 else "b", - "bound": str(index), - }[failure] - return Reply( - body=b'{"dataset_version":1}\n', - headers={ - "Content-Type": "application/x-ndjson", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - "X-Proofline-Export-Next-Cursor": cursor, - }, - ) + 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: - iterator = client.iter_export_pages( + 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, - "reviews", - from_time="2026-10-01T00:00:00Z", - to_time="2026-10-25T00:00:00Z", - max_pages=3, - cursor="initial" if failure == "resume" else None, + 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: - for _ in range(4): - await next_export(iterator) - if failure == "refused": - assert raised.value.status == 404 + 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 +@pytest.mark.parametrize("status", [401, 403]) +async def test_wait_for_review_timely_cancellation_keeps_auth_read_error( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + clock.now += 101.0 + raise ProoflineError(status, "urn:proofline:sdk:test", "denied") + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + monkeypatch.setattr(client, "get_review", get_review) + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) + assert raised.value.status == status + assert len(server.requests) == 0 + assert event.is_set() + + +@MODES +async def test_wait_for_review_invalid_response_after_deadline_keeps_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> 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 + event.set() + assert event.is_set() + 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 event.is_set() + + +@MODES +async def test_wait_for_review_timely_cancellation_keeps_invalid_response_error( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + + def get_review(*args: Any, **kwargs: Any) -> Any: + event.set() + clock.now += 101.0 + raise _transport.invalid_response() + + monkeypatch.setattr(client, "get_review", get_review) + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert len(server.requests) == 0 + assert event.is_set() + + +@MODES +async def test_wait_for_review_late_cancellation_after_read_keeps_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> 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: - suffix = "pagination-limit" if failure == "bound" else "invalid-pagination" - assert raised.value.type == f"urn:proofline:sdk:{suffix}" - expected_requests = { - "empty": 1, - "repeat": 2, - "resume": 1, - "cycle": 3, - "bound": 3, - "refused": 1, - } - assert len(server.requests) == expected_requests[failure] + + 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 = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + body = review("RUNNING") + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + if mode == "async": + + async def skip_backoff(wait_event: Any, cutoff: float, signal: Any | None = None) -> bool: + clock.sleep(max(0.0, cutoff - clock.now)) + return False + + monkeypatch.setattr(client_module, "_async_wait_for_event", skip_backoff) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + real_get_review = client.get_review + 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: + real_wait = client_module._wait_for_event + real_async_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + body = review("RUNNING") + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + observed: list[bool] = [] + + if mode == "sync": + calls = 0 + + 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" + assert timeout == pytest.approx(5.0) + assert deadline is not None + assert deadline.end == pytest.approx(clock.now + 100.0) + cutoff = min(clock.now + timeout, deadline.end) + clock.now = cutoff + wait_event.set() + wait_event.clear() + clock.now = cutoff - 0.5 + result = real_wait(wait_event, timeout, deadline) + observed.append(result) + return result + + monkeypatch.setattr(client_module, "_wait_for_event", wait_for_event) + else: + 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" + assert cutoff == pytest.approx(clock.now + 5.0) + assert signal is not None + assert signal.end == pytest.approx(clock.now + 100.0) + clock.now = cutoff + wait_event.set() + wait_event.clear() + clock.now = cutoff - 0.5 + result = await real_async_wait(wait_event, cutoff, signal) + observed.append(result) + return result + + monkeypatch.setattr(client_module, "_async_wait_for_event", async_wait_for_event) + + 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 observed == [True] + 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)), + ] + if host == "scoped.proofline.invalid": + return [ + (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", port, 0, 41)), + (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", port, 0, 41)), + (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", port, 0, 42)), + ] + if host in {"fe80::1", "fe80::1%41", "fe80::1%42"}: + # Translate synthetic interface scopes at the OS boundary; TCP stays real. + scoped_connections.append(host) + if host == "fe80::1": + raise socket.gaierror(socket.EAI_NONAME, "The IPv6 scope is missing") + address = "127.0.0.2" if host == "fe80::1%41" else "127.0.0.1" + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port))] + return original(host, port, *args, **kwargs) + + original = socket.getaddrinfo + monkeypatch.setattr(socket, "getaddrinfo", resolve) + with Server(lambda request, index: Reply(body=finding())) as server: + port = server.url.rsplit(":", 1)[1] + with httpx2.Client(transport=_sync_http.Transport()) as client: + response = client.get(f"http://service.proofline.invalid:{port}/finding") + assert response.json()["id"] == str(FINDING) + assert server.requests[0].headers["Host"] == f"service.proofline.invalid:{port}" + assert ("service.proofline.invalid", "proofline-dns") in lookups + response = client.get(f"http://scoped.proofline.invalid:{port}/finding") + assert response.json()["id"] == str(FINDING) + assert server.requests[1].headers["Host"] == f"scoped.proofline.invalid:{port}" + assert ("scoped.proofline.invalid", "proofline-dns") in lookups + assert scoped_connections == ["fe80::1%41", "fe80::1%42"] + with pytest.raises(httpx2.TransportError) as raised: + client.get(f"http://missing.proofline.invalid:{port}/finding") + assert not isinstance(raised.value, httpx2.TimeoutException) + with pytest.raises(httpx2.TransportError): + client.get(f"http://127.0.0.1:{closed_port}/finding") + assert len(server.requests) == 2 + + +@MODES +async def test_cursor_pagination_preserves_filters_and_refuses_cycles_or_bounds(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + assert urlsplit(request.path).path == f"/api/v1/organizations/{ORG}/reviews" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + query = parse_qs(urlsplit(request.path).query) + assert query["repository"] == [str(REPOSITORY)] + assert query["status"] == ["COMPLETED"] + assert query["limit"] == ["2"] + assert query["query"] == [STRUCTURED_QUERY] + assert query["search"] == ["text & space"] + if index == 0: + assert "cursor" not in query + else: + assert query["cursor"] == ["opaque+/cursor"] + return Reply( + body=page(cursor="opaque+/cursor" if index == 0 else None, truncated=index == 0) + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + items = await collect( + client, + page_size=2, + filters={ + "repository": REPOSITORY, + "status": "COMPLETED", + "query": STRUCTURED_QUERY, + "search": "text & space", + }, + ) + assert [item.id for item in items] == [REVIEW, REVIEW] + assert len(server.requests) == 2 + for cursor in ["repeated", None]: + with Server( + lambda request, index: Reply(body=page(cursor=cursor, truncated=True)) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await collect(client) + assert raised.value.type == "urn:proofline:sdk:invalid-pagination" + assert len(server.requests) <= 2 + with Server( + lambda request, index: Reply(body=page(cursor=str(index), truncated=True)) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await collect(client, max_pages=2) + assert raised.value.type == "urn:proofline:sdk:pagination-limit" + assert len(server.requests) == 2 + two_items = page() + two_items["items"].append(dict(two_items["items"][0])) + with Server(lambda request, index: Reply(body=two_items)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await collect(client, max_items=1, filters={"cursor": "initial"}) + assert raised.value.type == "urn:proofline:sdk:pagination-limit" + + +def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN) + with ProoflineClient() as client: + assert client._api.token.get_secret_value() == TOKEN + assert TOKEN not in repr(client._api) + for origin in [ + "http://api.example", + "http://localhost", + "http://127.0.0.1.example", + "https://user:password@example.com", + "https://example.com?token=secret", + "https://example.com/api/v1", + " https://example.com", + ]: + with pytest.raises(ValueError): + ProoflineClient(TOKEN, base_url=origin) + with ProoflineClient(TOKEN, base_url="http://[::1]:8080"): + pass + + +@MODES +@pytest.mark.parametrize("size", [131_072, 131_073, 150_000, 8 * 1024 * 1024 + 1]) +async def test_csv_export_preserves_large_cells(mode: str, size: int) -> None: + claim = 'é, "quoted"\r\n' + "x" * size + row = { + "dataset_version": "1", + "organization_id": str(ORG), + "repository_id": str(REPOSITORY), + "review_id": str(REVIEW), + "assessment_id": str(ASSESSMENT), + "environment_id": str(ORG), + "finding_id": str(FINDING), + "claim": claim, + "impact": "Synthetic consequence", + "risk_domain": "SECURITY", + "severity": "HIGH", + "lifecycle_state": "OPEN", + "created_at": "2026-11-16T00:00:00Z", + "evidence_refs": "[]", + } + stream = io.StringIO(newline="") + writer = csv.DictWriter(stream, fieldnames=list(row)) + writer.writeheader() + writer.writerow(row) + text = stream.getvalue() + with Server( + lambda request, index: Reply( + body=text.encode(), + headers={ + "Content-Type": "text/csv", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-11-16T00:00:00Z", + "X-Proofline-Export-Next-Cursor": "opaque/+cursor", + }, + ) + ) as server: + async with session(mode, server.url) as client: + kwargs = {"from_time": "2026-11-01T00:00:00Z", "to_time": "2026-11-15T00:00:00Z"} + if size > 8 * 1024 * 1024: + with pytest.raises(ProoflineError) as caught: + await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) + assert caught.value.type == "urn:proofline:sdk:invalid-response" + else: + page = await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) + assert page.rows == [row] + assert page.text == text + assert page.version == 1 + assert page.settled_until == "2026-11-16T00:00:00Z" + assert page.next_cursor == "opaque/+cursor" + assert len(server.requests) == 1 + + +@MODES +async def test_export_pages_preserve_csv_and_refuse_foreign_cursor(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + query = parse_qs(urlsplit(request.path).query) + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/findings?") + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + if query.get("cursor") == ["refused"]: + return Reply(status=404, body={"detail": "not found"}) + is_csv = query.get("format") == ["csv"] + return Reply( + body=( + b'dataset_version,claim\r\n2,"comma, quote "" and\nnewline"\r\n' + if is_csv + else b'{"dataset_version":2,"claim":"hello"}\n' + ), + headers={ + "Content-Type": "text/csv" if is_csv else "application/x-ndjson", + "X-Proofline-Export-Version": "2", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": "opaque/+cursor", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + kwargs = {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-25T00:00:00Z"} + exported = await call(client, "export_reviews", ORG, "findings", format="csv", **kwargs) + assert exported.rows[0]["claim"] == 'comma, quote " and\nnewline' + assert exported.next_cursor == "opaque/+cursor" + exported = await call( + client, "export_reviews", ORG, "findings", cursor=exported.next_cursor, **kwargs + ) + assert exported.rows[0]["dataset_version"] == 2 + assert exported.version == 2 + assert "cursor=opaque%2F%2Bcursor" in server.requests[1].path + with pytest.raises(ProoflineError) as caught: + await call(client, "export_reviews", ORG, "findings", cursor="refused", **kwargs) + assert caught.value.status == 404 + + +async def next_export(iterator: Any) -> Any: + return await anext(iterator) if hasattr(iterator, "__anext__") else next(iterator) + + +@MODES +@pytest.mark.parametrize("format", ["csv", "ndjson"]) +async def test_export_iterator_preserves_filters_and_streams_empty_pages( + mode: str, format: str +) -> None: + def respond(request: Request, index: int) -> Reply: + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/finding_outcomes?") + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + query = parse_qs(urlsplit(request.path).query) + assert query == { + "from": ["2026-10-01T00:00:00Z"], + "to": ["2026-10-25T00:00:00Z"], + "format": [format], + "group_by": ["repository"], + "cursor": ["resume/+cursor" if index == 0 else "next/+cursor"], + } + headers = { + "Content-Type": "text/csv" if format == "csv" else "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + } + if index == 0: + headers["X-Proofline-Export-Next-Cursor"] = "next/+cursor" + body = ( + ( + b"dataset_version,claim\r\n" + if index == 0 + else b"dataset_version,claim\r\n1,hello\r\n" + ) + if format == "csv" + else (b"" if index == 0 else b'{"dataset_version":1,"claim":"hello"}\n') + ) + return Reply(body=body, headers=headers) + + with Server(respond) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_pages( + ORG, + "finding_outcomes", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + format=format, + cursor="resume/+cursor", + group_by="repository", + max_pages=2, + ) + assert not server.requests + first = await next_export(iterator) + assert first.rows == [] + assert first.next_cursor == "next/+cursor" + assert first.version == 1 + assert first.settled_until == "2026-10-25T00:00:00Z" + assert len(server.requests) == 1 + second = await next_export(iterator) + assert second.rows[0]["claim"] == "hello" + assert second.next_cursor is None + assert second.text.endswith("\n") + if mode == "sync": + with pytest.raises(StopIteration): + next(iterator) + else: + with pytest.raises(StopAsyncIteration): + await anext(iterator) + assert len(server.requests) == 2 + + +@MODES +@pytest.mark.parametrize("failure", ["empty", "repeat", "resume", "cycle", "bound", "refused"]) +async def test_export_iterator_refuses_invalid_continuations_and_bounds( + mode: str, failure: str +) -> None: + def respond(request: Request, index: int) -> Reply: + if failure == "refused": + return Reply(status=404, body={"detail": "not found"}) + cursor = { + "empty": "", + "repeat": "next", + "resume": "initial", + "cycle": "a" if index % 2 == 0 else "b", + "bound": str(index), + }[failure] + return Reply( + body=b'{"dataset_version":1}\n', + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": cursor, + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + max_pages=3, + cursor="initial" if failure == "resume" else None, + ) + with pytest.raises(ProoflineError) as raised: + for _ in range(4): + await next_export(iterator) + if failure == "refused": + assert raised.value.status == 404 + else: + suffix = "pagination-limit" if failure == "bound" else "invalid-pagination" + assert raised.value.type == f"urn:proofline:sdk:{suffix}" + expected_requests = { + "empty": 1, + "repeat": 2, + "resume": 1, + "cycle": 3, + "bound": 3, + "refused": 1, + } + assert len(server.requests) == expected_requests[failure] + + +@MODES +@pytest.mark.parametrize("bound", [0, -1, 1001, True, 1.5]) +async def test_export_iterator_validates_bound_before_requests(mode: str, bound: Any) -> None: + with Server(lambda request, index: Reply(body={})) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + max_pages=bound, + ) + with pytest.raises(ValueError, match="max_pages"): + await next_export(iterator) + assert not server.requests + + +@MODES +@pytest.mark.parametrize( + ("cursors", "resume", "yielded"), + [ + ([""], None, 0), + (["initial"], "initial", 0), + (["a", "a"], None, 1), + (["a", "b", "a"], None, 2), + ], + ids=["empty", "resume", "repeat", "cycle"], +) +async def test_export_iterator_never_yields_the_page_with_an_invalid_cursor( + mode: str, cursors: list[str], resume: str | None, yielded: int +) -> None: + def respond(request: Request, index: int) -> Reply: + return Reply( + body=f'{{"dataset_version":1,"page":{index}}}\n'.encode(), + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": cursors[index], + }, + ) + + pages: list[Any] = [] + with Server(respond) as server: + async with session(mode, server.url) as client: + iterator = client.iter_export_pages( + ORG, + "reviews", + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + cursor=resume, + ) + with pytest.raises(ProoflineError) as raised: + while True: + pages.append(await next_export(iterator)) + assert raised.value.type == "urn:proofline:sdk:invalid-pagination" + assert [page.rows[0]["page"] for page in pages] == list(range(yielded)) + assert len(server.requests) == yielded + 1 + + +@MODES +@pytest.mark.parametrize( + ("format", "content_type"), + [ + ("csv", "Text/CSV; charset=utf-8"), + ("ndjson", "Application/X-NDJSON; charset=utf-8"), + ], +) +async def test_export_accepts_case_insensitive_content_type( + mode: str, format: str, content_type: str +) -> None: + def respond(request: Request, index: int) -> Reply: + body = ( + b"dataset_version,claim\n1,hello\n" + if format == "csv" + else b'{"dataset_version":1,"claim":"hello"}\n' + ) + return Reply( + body=body, + headers={ + "Content-Type": content_type, + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + page = await call( + client, + "export_reviews", + ORG, + "findings", + format=format, + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + ) + assert page.rows[0]["claim"] == "hello" + + +@MODES +async def test_export_versions_follow_the_dataset(mode: str) -> None: + served = { + "findings": [("1", 1), ("2", 2), ("2", 1), ("3", 3)], + "finding_validations": [("2", 2)], + "reviews": [("1", 1), ("2", 2)], + } + + seen: dict[str, int] = {} + + def respond(request: Request, index: int) -> Reply: + dataset = urlsplit(request.path).path.rsplit("/", 1)[1] + seen[dataset] = seen.get(dataset, 0) + 1 + header, row = served[dataset][seen[dataset] - 1] + return Reply( + body=json.dumps({"dataset_version": row}).encode() + b"\n", + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": header, + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + kwargs = {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-25T00:00:00Z"} + outcomes = [] + for dataset, replies in served.items(): + for _ in replies: + try: + page = await call(client, "export_reviews", ORG, dataset, **kwargs) + outcomes.append((dataset, page.version)) + except ProoflineError as error: + outcomes.append((dataset, error.type)) + refused = "urn:proofline:sdk:invalid-response" + assert outcomes == [ + ("findings", 1), + ("findings", 2), + ("findings", refused), + ("findings", refused), + ("finding_validations", 2), + ("reviews", 1), + ("reviews", refused), + ] + + +@MODES +@pytest.mark.parametrize("format", ["csv", "ndjson"]) +async def test_review_export_retains_every_recorded_kind(mode: str, format: str) -> None: + kinds = [ + "PULL_REQUEST", + "DEPLOYMENT", + "PATCH", + "COMMIT", + "FILES", + "MERGE_GROUP", + "REVISION_SCAN", + ] + rows = [ + { + "dataset_version": 1, + "kind": kind, + "created_at": "2026-10-24T00:00:00Z", + "organization_id": str(ORG), + "review_id": "00000000-0000-7000-8000-000000000002", + "status": "COMPLETED", + "trigger_origin": "AUTOMATIC", + } + for kind in kinds + ] + + def respond(request: Request, index: int) -> Reply: + assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/reviews?") + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + return Reply( + body=( + ( + ",".join(rows[0]) + + "\r\n" + + "".join(",".join(map(str, row.values())) + "\r\n" for row in rows) + ).encode() + if format == "csv" + else ("\n".join(json.dumps(row) for row in rows) + "\n").encode() + ), + headers={ + "Content-Type": "text/csv" if format == "csv" else "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + page = await call( + client, + "export_reviews", + ORG, + "reviews", + format=format, + from_time="2026-10-01T00:00:00Z", + to_time="2026-10-25T00:00:00Z", + ) + assert [row["kind"] for row in page.rows] == kinds + # The generated wire enum must accept the same retained spellings. + assert [ExportReviewKind(row["kind"]).value for row in page.rows] == kinds + if format == "ndjson": + assert [ReviewsExportRow.from_dict(row).kind.value for row in page.rows] == kinds + assert page.next_cursor is None + + +@MODES +async def test_knowledge_negotiation_scope_and_no_retry(mode: str) -> None: + refusal = False + wrong_id = False + + def respond(request: Request, index: int) -> Reply: + body = json.loads(request.body) + assert request.path == "/mcp" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + if body["method"] == "initialize": + return Reply( + body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} + ) + assert request.headers["MCP-Protocol-Version"] == "2025-11-25" + if body["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + assert body["params"] == { + "name": "get_wiki_page", + "arguments": {"repository": "owner/name", "page_key": "index", "commit": "a" * 40}, + } + if refusal: + return Reply(status=503, body={"detail": "unavailable"}) + return Reply( + body={ + "jsonrpc": "2.0", + "id": 99 if wrong_id else 2, + "result": { + "isError": True, + "content": [{"type": "text", "text": "RESOURCE_NOT_FOUND"}], + }, + } + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + + async def invoke() -> Any: + result = client.knowledge.get_wiki_page("owner/name", "index", commit="a" * 40) + return await result if inspect.isawaitable(result) else result + + assert (await invoke())["isError"] is True + wrong_id = True + with pytest.raises(ProoflineError): + await invoke() + refusal = True + with pytest.raises(ProoflineError): + await invoke() + assert len(server.requests) == 9 + + +@MODES +async def test_fixes_preserve_unavailable_context_and_never_retry(mode: str) -> None: + observed: list[dict[str, Any]] = [] + refuse = False + result = { + "content": [{"type": "text", "text": "untrusted source"}], + "structuredContent": {"status": "UNAVAILABLE", "items": None}, + } + + def respond(request: Request, index: int) -> Reply: + body = json.loads(request.body) + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + if body["method"] == "initialize": + return Reply( + body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} + ) + if body["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + observed.append(body["params"]) + if refuse: + return Reply(status=503, body={"detail": "unavailable"}, headers={"Retry-After": "0"}) + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + + async def invoke(name: str, *args: Any, **kwargs: Any) -> Any: + answer = getattr(client.fixes, name)(*args, **kwargs) + return await answer if inspect.isawaitable(answer) else answer + + assert await invoke("list_open_findings", "owner/name", 7) == result + assert await invoke("get_fix_context", str(REVIEW)) == result + assert ( + await invoke( + "request_reverification", + str(REVIEW), + [str(REVIEW)], + "a" * 40, + note="fixed code", + ) + == result + ) + assert await invoke("get_reverification", str(REVIEW)) == result + assert observed == [ + { + "name": "list_open_findings", + "arguments": {"repository": "owner/name", "pull_request_number": 7}, + }, + {"name": "get_fix_context", "arguments": {"finding_id": str(REVIEW)}}, + { + "name": "request_reverification", + "arguments": { + "review_id": str(REVIEW), + "finding_ids": [str(REVIEW)], + "commit_sha": "a" * 40, + "note": "fixed code", + }, + }, + {"name": "get_reverification", "arguments": {"request_id": str(REVIEW)}}, + ] + refuse = True + with pytest.raises(ProoflineError): + await invoke("request_reverification", str(REVIEW), [str(REVIEW)], "a" * 40) + assert len(observed) == 5 + + +@MODES +async def test_shared_review_outcome_contract(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: + Clock(monkeypatch) + fixture = json.loads((Path(__file__).parent / "fixtures/review-outcomes.json").read_text()) + for case in fixture["cases"]: + body = case["review"] + pending = case["outcome"] is None + settled = next( + item["review"] for item in fixture["cases"] if item["name"] == "review-completed" + ) + with Server( + lambda request, index: Reply(body=settled if pending and index else body) + ) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, UUID(body["id"])) + assert result.status == ("COMPLETED" if pending else case["outcome"]), case["name"] + assert len(server.requests) == (2 if pending else 1), case["name"] + assert [ + { + "assessment_id": str(gap.assessment_id) if gap.assessment_id else None, + "reason_codes": list(gap.reason_codes), + } + for gap in result.gaps + ] == case["gaps"], case["name"] + + +@MODES +async def test_mcp_per_call_organizations_and_refusals(mode: str) -> None: + first, second, foreign = (str(ORG), str(REVIEW), str(ASSESSMENT)) + admitted = [first, second] + observed: list[dict[str, Any]] = [] + concurrent = False + overlap = threading.Barrier(2) + + def respond(request: Request, index: int) -> Reply: + assert request.path == "/mcp" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + body = json.loads(request.body) + if body["method"] == "initialize": + return Reply( + body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} + ) + assert request.headers["MCP-Protocol-Version"] == "2025-11-25" + if body["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + params = body["params"] + observed.append(params) + if params["name"] == "list_organizations": + assert params["arguments"] == {} + result: dict[str, Any] = { + "content": [], + "structuredContent": { + "ok": True, + "data": {"organizations": [{"organization_id": value} for value in admitted]}, + }, + } + else: + if concurrent: + # Neither response completes until both tool calls have arrived. + overlap.wait(timeout=5) + target = params["arguments"].get("organization_id") + code = ( + "ORGANIZATION_REQUIRED" + if target is None + else "NOT_AUTHORIZED" + if target not in admitted + else None + ) + payload = ( + { + "ok": False, + "error": {"code": code, "message": "Target refused", "retryable": False}, + } + if code + else {"ok": True, "data": {"organization_id": target}} + ) + result = { + "isError": code is not None, + "content": [{"type": "text", "text": json.dumps(payload)}], + "structuredContent": payload, + } + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + + async def invoke(group: str, name: str, *args: Any, **kwargs: Any) -> Any: + result = getattr(getattr(client, group), name)(*args, **kwargs) + return await result if inspect.isawaitable(result) else result + + discovery = await invoke("mcp", "list_organizations") + assert discovery["structuredContent"]["data"]["organizations"] == [ + {"organization_id": first}, + {"organization_id": second}, + ] + cases = [ + ( + "knowledge", + "list_wiki_pages", + ("owner/name",), + {"commit": "a" * 40}, + {"repository": "owner/name", "commit": "a" * 40}, + ), + ( + "knowledge", + "get_wiki_page", + ("owner/name", "index"), + {}, + {"repository": "owner/name", "page_key": "index"}, + ), + ( + "knowledge", + "ask_codebase", + ("owner/name", "How?"), + {}, + {"repository": "owner/name", "question": "How?"}, + ), + ( + "knowledge", + "get_architecture_document", + (str(REVIEW),), + {}, + {"environment_id": str(REVIEW)}, + ), + ("knowledge", "get_plan", (str(REVIEW),), {}, {"plan_id": str(REVIEW)}), + ( + "knowledge", + "start_plan_implementation", + (str(REVIEW),), + {}, + {"plan_id": str(REVIEW)}, + ), + ( + "knowledge", + "get_plan_implementation", + (str(REVIEW),), + {}, + {"implementation_id": str(REVIEW)}, + ), + ( + "fixes", + "list_open_findings", + ("owner/name", 7), + {}, + {"repository": "owner/name", "pull_request_number": 7}, + ), + ("fixes", "get_fix_context", (str(REVIEW),), {}, {"finding_id": str(REVIEW)}), + ( + "fixes", + "request_reverification", + (str(REVIEW), [str(REVIEW)], "a" * 40), + {"note": "fixed"}, + { + "review_id": str(REVIEW), + "finding_ids": [str(REVIEW)], + "commit_sha": "a" * 40, + "note": "fixed", + }, + ), + ("fixes", "get_reverification", (str(REVIEW),), {}, {"request_id": str(REVIEW)}), + ] + for group, name, args, kwargs, expected in cases: + for target in (first, second): + answer = await invoke(group, name, *args, **kwargs, organization_id=target) + assert answer["structuredContent"]["data"]["organization_id"] == target + assert observed[-1] == { + "name": name, + "arguments": {**expected, "organization_id": target}, + } + + if mode == "async": + concurrent = True + answers = await asyncio.gather( + invoke("knowledge", "get_plan", str(REVIEW), organization_id=first), + invoke("fixes", "get_fix_context", str(REVIEW), organization_id=second), + ) + concurrent = False + assert [ + answer["structuredContent"]["data"]["organization_id"] for answer in answers + ] == [first, second] + + async def refused(target: str | None, code: str) -> None: + before = len(observed) + kwargs = {} if target is None else {"organization_id": target} + answer = await invoke( + "fixes", + "request_reverification", + str(REVIEW), + [str(REVIEW)], + "a" * 40, + **kwargs, + ) + assert answer["isError"] is True + assert answer["structuredContent"]["error"]["code"] == code + assert json.loads(answer["content"][0]["text"]) == answer["structuredContent"] + assert len(observed) == before + 1 + assert observed[-1]["arguments"].get("organization_id") == target + assert ("organization_id" in observed[-1]["arguments"]) == (target is not None) + + # An earlier explicit target must never become an implicit default. + await refused(None, "ORGANIZATION_REQUIRED") + await refused(foreign, "NOT_AUTHORIZED") + admitted.remove(first) + await refused(first, "NOT_AUTHORIZED") + remaining = await invoke("mcp", "list_organizations") + assert remaining["structuredContent"]["data"]["organizations"] == [ + {"organization_id": second} + ] + answer = await invoke("fixes", "get_fix_context", str(REVIEW), organization_id=second) + assert answer["structuredContent"]["data"]["organization_id"] == second + assert len(server.requests) == len(observed) * 3 + + +def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> None: + # Compile consumer code through the public entry point; dynamic HTTP tests + # cannot catch a missing keyword in just one sync/async method signature. + lines = ["from proofline import ProoflineClient, AsyncProoflineClient, KnowledgeResult"] + calls = [ + 'knowledge.list_wiki_pages("owner/name", commit="a" * 40)', + 'knowledge.get_wiki_page("owner/name", "index")', + 'knowledge.ask_codebase("owner/name", "How?")', + 'knowledge.get_architecture_document("environment-id")', + 'knowledge.get_plan("plan-id")', + 'knowledge.start_plan_implementation("plan-id")', + 'knowledge.get_plan_implementation("implementation-id")', + 'fixes.list_open_findings("owner/name", 7)', + 'fixes.get_fix_context("finding-id")', + 'fixes.request_reverification("review-id", ["finding-id"], "a" * 40, note="fixed")', + 'fixes.get_reverification("request-id")', + ] + for prefix, kind, wait in [ + ("", "ProoflineClient", ""), + ("async ", "AsyncProoflineClient", "await "), + ]: + lines.append(f"{prefix}def use_{kind}(client: {kind}) -> None:") + lines.append(f" result: KnowledgeResult = {wait}client.mcp.list_organizations()") + for expression in calls: + lines.append(f" result = {wait}client.{expression}") + targeted = expression[:-1] + ', organization_id="00000000-0000-7000-8000-000000000001")' + lines.append(f" result = {wait}client.{targeted}") + fixture = tmp_path / "mcp_types.py" + fixture.write_text("\n".join(lines)) + # Use the same mypy configuration as the SDK qualification gate. + subprocess.run([sys.executable, "-m", "mypy", str(fixture)], check=True) + + +@MODES +async def test_export_ndjson_preserves_unicode_line_separators(mode: str) -> None: + kwargs = { + "from_time": "2026-10-01T00:00:00Z", + "to_time": "2026-10-25T00:00:00Z", + } + + for separator in ("\x85", "\u2028", "\u2029"): + row = { + "dataset_version": 1, + "claim": f"before{separator}after", + } + body = (json.dumps(row, ensure_ascii=False) + "\n").encode("utf-8") + + def respond(request: Request, index: int) -> Reply: + return Reply( + body=body, + headers={ + "Content-Type": "application/x-ndjson", + "X-Proofline-Export-Version": "1", + "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", + "X-Proofline-Export-Next-Cursor": "next-page", + }, + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + exported = await call( + client, + "export_reviews", + ORG, + "findings", + format="ndjson", + **kwargs, + ) + + 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 event._loop is None + assert id(event) not in client_module._async_signal_watches + assert event not in client_module._async_loop_bindings + finally: + event._waiters.remove(foreign) # type: ignore[arg-type] + waiter = client_module._watch_async_waiter(event, deadline) + try: + assert event._loop is asyncio.get_running_loop() + finally: + client_module._unwatch_async_waiter(waiter, deadline) + assert event._loop is None + + +async def test_async_waiter_keeps_a_temporary_binding_until_native_waiters_drain() -> None: + event = asyncio.Event() + loop = asyncio.get_running_loop() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + client_module._unwatch_async_waiter(sdk_waiter, deadline) + assert event in client_module._async_loop_bindings + assert event._loop is loop + assert len(event._waiters) == 1 + + native.cancel() + with pytest.raises(asyncio.CancelledError): + await native + await wait_until( + lambda: event._loop is None and event not in client_module._async_loop_bindings + ) + assert not event._waiters + + +async def test_async_binding_does_not_poll_a_pending_native_waiter( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = asyncio.Event() + loop = asyncio.get_running_loop() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + calls: list[tuple[Any, ...]] = [] + monkeypatch.setattr( + client_module, + "_schedule_binding_recheck", + lambda *args: calls.append(args), + ) + client_module._unwatch_async_waiter(sdk_waiter, deadline) + for _ in range(5): + await asyncio.sleep(0) + assert calls == [] + binding = client_module._async_loop_bindings.get(event) + assert binding is not None + try: + native.cancel() + with pytest.raises(asyncio.CancelledError): + await native + await wait_until(lambda: len(calls) == 1) + finally: + client_module._clear_temporary_async_binding(event, binding) + + +async def test_wait_for_review_accepts_an_unhashable_async_event_already_set( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class UnhashableEvent(asyncio.Event): + __hash__ = None # type: ignore[assignment] + + Clock(monkeypatch) + event = UnhashableEvent() + event.set() + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session("async", server.url) as client: + result = await client.wait_for_review(ORG, REVIEW, timeout=0, cancel_event=event) + assert server.requests == [] + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." + assert event not in client_module._async_loop_bindings + + +def test_condition_tracker_registration_waits_for_a_held_notification_lock() -> None: + # A held tracker lock 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 +first = client._SignalDeadline(101.0) +second = client._SignalDeadline(101.0) +client._track_thread_signal(event, first) +real_lock = client._notify_lock +lock_held = threading.Event() +allow_lock = threading.Event() +register_attempted = threading.Event() + + +class ProbeLock: + def __enter__(self): + name = threading.current_thread().name + if name == "teardown": + real_lock.acquire() + lock_held.set() + assert allow_lock.wait(5.0) + return self + if name == "register": + register_attempted.set() + real_lock.acquire() + return self + + def __exit__(self, *exc): + real_lock.release() + return False + + def _is_owned(self): + return real_lock._is_owned() + + +client._notify_lock = ProbeLock() +registered = threading.Event() + + +def teardown(): + client._untrack_thread_signal(event, first) + + +def register(): + client._track_thread_signal(event, second) + registered.set() + + +leaver = threading.Thread(target=teardown, name="teardown", daemon=True) +joiner = threading.Thread(target=register, name="register", daemon=True) +leaver.start() +assert lock_held.wait(2.0), "teardown never held the tracker lock" +joiner.start() +assert register_attempted.wait(2.0), "registration never reached the lock" +assert not registered.is_set(), "registration skipped the held lock" +allow_lock.set() +assert registered.wait(2.0), "registration did not follow teardown" +leaver.join(2.0) +joiner.join(2.0) +assert not leaver.is_alive() +assert not joiner.is_alive() +tracker = client._notify_trackers[condition] +assert set(tracker.subscribers) == {second} +assert condition.notify_all is tracker.installed_notify_all +client._untrack_thread_signal(event, second) +assert tracker.subscribers == {} +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_held_future_lock() -> None: + code = """ +import asyncio +import sys +import threading + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +state = threading.local() +lock_held = threading.Event() +allow_lock = threading.Event() +register_attempted = threading.Event() +real_lock = client._async_future_lock + + +class ProbeLock: + def __enter__(self): + mode = getattr(state, "mode", None) + if mode == "teardown": + real_lock.acquire() + lock_held.set() + assert allow_lock.wait(5.0) + return self + if mode == "register": + register_attempted.set() + real_lock.acquire() + return self + + def __exit__(self, *exc): + real_lock.release() + return False + + def _is_owned(self): + return real_lock._is_owned() + + +client._async_future_lock = ProbeLock() + + +async def main(): + 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) + registered = threading.Event() + + def teardown(): + state.mode = "teardown" + client._unwatch_async_future(future, first) + + def register(): + state.mode = "register" + client._watch_async_future(future, event, second) + registered.set() + + teardown_task = asyncio.create_task(asyncio.to_thread(teardown)) + joiner = None + try: + assert await asyncio.to_thread(lock_held.wait, 5.0) + joiner = asyncio.create_task(asyncio.to_thread(register)) + assert await asyncio.to_thread(register_attempted.wait, 5.0) + assert not registered.is_set(), "registration skipped the held lock" + allow_lock.set() + await asyncio.wait_for(teardown_task, 2.0) + assert await asyncio.to_thread(registered.wait, 2.0) + await asyncio.wait_for(joiner, 2.0) + assert client._unwatch_async_future(future, second) is True + finally: + allow_lock.set() + for task in (teardown_task, joiner): + if task is not None: + task.cancel() + await asyncio.gather( + *(task for task in (teardown_task, joiner) if task is not None), + return_exceptions=True, + ) + 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" -@MODES -@pytest.mark.parametrize("bound", [0, -1, 1001, True, 1.5]) -async def test_export_iterator_validates_bound_before_requests(mode: str, bound: Any) -> None: - with Server(lambda request, index: Reply(body={})) as server: - async with session(mode, server.url) as client: - iterator = client.iter_export_pages( - ORG, - "reviews", - from_time="2026-10-01T00:00:00Z", - to_time="2026-10-25T00:00:00Z", - max_pages=bound, - ) - with pytest.raises(ValueError, match="max_pages"): - await next_export(iterator) - assert not server.requests +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) -@MODES -@pytest.mark.parametrize( - ("cursors", "resume", "yielded"), - [ - ([""], None, 0), - (["initial"], "initial", 0), - (["a", "a"], None, 1), - (["a", "b", "a"], None, 2), - ], - ids=["empty", "resume", "repeat", "cycle"], -) -async def test_export_iterator_never_yields_the_page_with_an_invalid_cursor( - mode: str, cursors: list[str], resume: str | None, yielded: int + 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 condition not in client_module._notify_trackers + + +async def test_async_future_watch_stamps_one_notification_for_all_observers( + monkeypatch: pytest.MonkeyPatch, ) -> None: - def respond(request: Request, index: int) -> Reply: - return Reply( - body=f'{{"dataset_version":1,"page":{index}}}\n'.encode(), - headers={ - "Content-Type": "application/x-ndjson", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - "X-Proofline-Export-Next-Cursor": cursors[index], - }, - ) + clock = Clock(monkeypatch) + samples = iter((100.02, 100.03, 100.04)) + monkeypatch.setattr(client_module, "monotonic", lambda: next(samples, 100.04)) + event = asyncio.Event() + future = asyncio.get_running_loop().create_future() + first = client_module._SignalDeadline(clock.now + 0.1) + 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: + event.set() + future.set_result(True) + assert first.signalled_at == 100.02 + assert second.signalled_at == 100.02 + finally: + client_module._unwatch_async_future(future, first) + client_module._unwatch_async_future(future, second) + + +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) - pages: list[Any] = [] - with Server(respond) as server: - async with session(mode, server.url) as client: - iterator = client.iter_export_pages( - ORG, - "reviews", - from_time="2026-10-01T00:00:00Z", - to_time="2026-10-25T00:00:00Z", - cursor=resume, - ) - with pytest.raises(ProoflineError) as raised: - while True: - pages.append(await next_export(iterator)) - assert raised.value.type == "urn:proofline:sdk:invalid-pagination" - assert [page.rows[0]["page"] for page in pages] == list(range(yielded)) - assert len(server.requests) == yielded + 1 + class AdvancingLock: + def __enter__(self) -> Any: + clock.now = 111.0 + 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 -@pytest.mark.parametrize( - ("format", "content_type"), - [ - ("csv", "Text/CSV; charset=utf-8"), - ("ndjson", "Application/X-NDJSON; charset=utf-8"), - ], -) -async def test_export_accepts_case_insensitive_content_type( - mode: str, format: str, content_type: str +async def test_wait_for_review_reuses_the_read_latch_for_backoff( + mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: - def respond(request: Request, index: int) -> Reply: - body = ( - b"dataset_version,claim\n1,hello\n" - if format == "csv" - else b'{"dataset_version":1,"claim":"hello"}\n' - ) - return Reply( - body=body, - headers={ - "Content-Type": content_type, - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - }, - ) + 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(respond) as server: + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session(mode, server.url) as client: - page = await call( - client, - "export_reviews", - ORG, - "findings", - format=format, - from_time="2026-10-01T00:00:00Z", - to_time="2026-10-25T00:00:00Z", + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, cancel_event=event ) - assert page.rows[0]["claim"] == "hello" + 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 == [] -@MODES -async def test_export_versions_follow_the_dataset(mode: str) -> None: - served = { - "findings": [("1", 1), ("2", 2), ("2", 1), ("3", 3)], - "finding_validations": [("2", 2)], - "reviews": [("1", 1), ("2", 2)], - } +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() -> None: + # A stalled notifier must not hang pytest; the whole probe is bounded. + code = """ +import sys +import threading - seen: dict[str, int] = {} +sys.path.insert(0, sys.argv[1]) +from proofline import client - def respond(request: Request, index: int) -> Reply: - dataset = urlsplit(request.path).path.rsplit("/", 1)[1] - seen[dataset] = seen.get(dataset, 0) + 1 - header, row = served[dataset][seen[dataset] - 1] - return Reply( - body=json.dumps({"dataset_version": row}).encode() + b"\n", - headers={ - "Content-Type": "application/x-ndjson", - "X-Proofline-Export-Version": header, - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - }, - ) +now = [100.0] +client.monotonic = lambda: now[0] +real_track = client._track_sync_cancel - with Server(respond) as server: - async with session(mode, server.url) as client: - kwargs = {"from_time": "2026-10-01T00:00:00Z", "to_time": "2026-10-25T00:00:00Z"} - outcomes = [] - for dataset, replies in served.items(): - for _ in replies: - try: - page = await call(client, "export_reviews", ORG, dataset, **kwargs) - outcomes.append((dataset, page.version)) - except ProoflineError as error: - outcomes.append((dataset, error.type)) - refused = "urn:proofline:sdk:invalid-response" - assert outcomes == [ - ("findings", 1), - ("findings", 2), - ("findings", refused), - ("findings", refused), - ("finding_validations", 2), - ("reviews", 1), - ("reviews", refused), - ] +class CheckpointCondition(threading.Condition): + def notify_all(self): + if not event.pulsed.is_set(): + event.pulsed.set() + assert event.proceed.wait(5.0), "the late checkpoint never arrived" + super().notify_all() -@MODES -@pytest.mark.parametrize("format", ["csv", "ndjson"]) -async def test_review_export_retains_every_recorded_kind(mode: str, format: str) -> None: - kinds = [ - "PULL_REQUEST", - "DEPLOYMENT", - "PATCH", - "COMMIT", - "FILES", - "MERGE_GROUP", - "REVISION_SCAN", - ] - rows = [ - { - "dataset_version": 1, - "kind": kind, - "created_at": "2026-10-24T00:00:00Z", - "organization_id": str(ORG), - "review_id": "00000000-0000-7000-8000-000000000002", - "status": "COMPLETED", - "trigger_origin": "AUTOMATIC", - } - for kind in kinds - ] - def respond(request: Request, index: int) -> Reply: - assert request.path.startswith(f"/api/v1/organizations/{ORG}/exports/reviews?") - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - return Reply( - body=( - ( - ",".join(rows[0]) - + "\r\n" - + "".join(",".join(map(str, row.values())) + "\r\n" for row in rows) - ).encode() - if format == "csv" - else ("\n".join(json.dumps(row) for row in rows) + "\n").encode() - ), - headers={ - "Content-Type": "text/csv" if format == "csv" else "application/x-ndjson", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - }, - ) +class GatedEvent(threading.Event): + def __init__(self): + super().__init__() + self.revealed = False + self.installed = threading.Event() + self.pulsed = threading.Event() + self.proceed = threading.Event() + self._cond = CheckpointCondition(threading.Lock()) + + def is_set(self): + return self.revealed + + def pulse(self): + with self._cond: + self._flag = True + self._cond.notify_all() + self._flag = False + + def reveal_late(self): + self.revealed = True + self.proceed.set() + with self._cond: + self._flag = True + self._cond.notify_all() + self._flag = False + + +event = GatedEvent() + + +def track(event_arg, deadline): + real_track(event_arg, deadline) + event.installed.set() + + +client._track_sync_cancel = track + + +def signal(): + assert event.installed.wait(5.0), "cancellation was never observed" + now[0] = 100.5 + event.pulse() + + +def late(): + assert event.pulsed.wait(5.0), "the early wake never arrived" + now[0] = 101.5 + event.reveal_late() + + +early_thread = threading.Thread(target=signal, daemon=True) +late_thread = threading.Thread(target=late, daemon=True) +early_thread.start() +late_thread.start() +try: + assert client._sleep_with_cancel(5, event, cutoff=101.0) is True +finally: + event.proceed.set() + early_thread.join(5.0) + late_thread.join(5.0) +assert not early_thread.is_alive() +assert not late_thread.is_alive() +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +def test_async_waiter_registration_is_atomic_across_event_loops() -> None: + # The competing registration must try the lock while the first is paused + # inside its critical section, so native ownership alone cannot satisfy it. + code = """ +import asyncio +import sys +import threading +import time + +sys.path.insert(0, sys.argv[1]) +from proofline import client + +event = asyncio.Event() +results = [] +registered = threading.Event() +release = threading.Event() +second_done = threading.Event() +attempts = [] +paused_ident = [] +real_lock = client._async_future_lock +real_watch_future = client._watch_async_future + + +class InstrumentedLock: + def __enter__(self): + attempts.append(threading.get_ident()) + return real_lock.__enter__() + + def __exit__(self, *args): + return real_lock.__exit__(*args) + + +client._async_future_lock = InstrumentedLock() + + +def paused_registration(*args, **kwargs): + if not paused_ident: + paused_ident.append(threading.get_ident()) + registered.set() + assert release.wait(5.0), "the paused registration was never released" + return real_watch_future(*args, **kwargs) + + +client._watch_async_future = paused_registration + + +def run(): + async def main(): + deadline = client._SignalDeadline(time.monotonic() + 10.0) + try: + waiter = client._watch_async_waiter(event, deadline) + results.append((threading.get_ident(), "registered")) + assert second_done.wait(5.0) + client._unwatch_async_waiter(waiter, deadline) + except RuntimeError: + results.append((threading.get_ident(), "rejected")) + second_done.set() + finally: + registered.set() + release.set() + second_done.set() + + asyncio.run(main()) + + +threads = [threading.Thread(target=run, daemon=True) for _ in range(2)] +for thread in threads: + thread.start() +assert registered.wait(5.0), "the paused registration never started" +assert paused_ident +for _ in range(500): + if any(ident != paused_ident[0] for ident in attempts): + break + time.sleep(0.01) +else: + raise AssertionError("the contending registration did not attempt the lock") +assert not release.is_set(), "the first registration resumed before the lock attempt" +release.set() +for thread in threads: + thread.join(5.0) +assert not any(thread.is_alive() for thread in threads) +by_ident = dict(results) +assert by_ident.get(paused_ident[0]) == "registered" +contenders = [ident for ident in by_ident if ident != paused_ident[0]] +assert len(contenders) == 1 +assert by_ident[contenders[0]] == "rejected" +assert not event._waiters +assert event not in client._async_loop_bindings +assert id(event) not in client._async_signal_watches +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_idle_hooks_and_reuses_the_tracker( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = threading.Event() + condition = event._cond + first = client_module._SignalDeadline(time.monotonic() + 10.0) + second = client_module._SignalDeadline(time.monotonic() + 10.0) + attempts: list[tuple[Any, ...]] = [] + real_restore = client_module._restore_method + + def record_restore(*args: Any) -> None: + attempts.append(args) + real_restore(*args) + + monkeypatch.setattr(client_module, "_restore_method", record_restore) + client_module._track_thread_signal(event, first) + tracker = client_module._notify_trackers[condition] + first_installed = tracker.installed_notify_all + try: + client_module._untrack_thread_signal(event, first) + assert len(attempts) == 2 + assert condition.notify_all.__func__ is tracker.original_notify_all.__func__ + assert condition.notify.__func__ is tracker.original_notify.__func__ + client_module._track_thread_signal(event, second) + assert client_module._notify_trackers[condition] is tracker + assert set(tracker.subscribers) == {second} + assert condition.notify_all is tracker.installed_notify_all + assert tracker.installed_notify_all is not first_installed + assert condition.notify is tracker.installed_notify + finally: + client_module._untrack_thread_signal(event, second) + assert tracker.subscribers == {} + assert len(attempts) == 4 + + +def test_condition_tracker_restore_preserves_a_caller_replacement( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = threading.Event() + condition = event._cond + first = client_module._SignalDeadline(time.monotonic() + 10.0) + client_module._track_thread_signal(event, first) + client_module._untrack_thread_signal(event, first) + + def replacement_all(*args: Any, **kwargs: Any) -> None: + return None + + def replacement_notify(*args: Any, **kwargs: Any) -> None: + return None + + condition.notify_all = replacement_all # type: ignore[method-assign] + condition.notify = replacement_notify # type: ignore[method-assign] + second = client_module._SignalDeadline(time.monotonic() + 10.0) + client_module._track_thread_signal(event, second) + try: + assert condition.notify_all is not replacement_all + assert condition.notify is not replacement_notify + finally: + client_module._untrack_thread_signal(event, second) + assert condition.notify_all is replacement_all + assert condition.notify is replacement_notify + + +async def test_async_event_set_publishes_once_for_all_watched_waiters( + 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 future, deadline in zip(futures, deadlines): + assert client_module._unwatch_async_future(future, deadline) is True + assert all(id(future) not in client_module._async_future_watches for future in futures) + assert all("set_result" not in getattr(future, "__dict__", {}) for future in futures) + client_module._async_signal_watches.pop(id(event), None) + + +async def test_async_future_observer_latches_a_forwarding_is_set_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class ForwardingEvent(asyncio.Event): + def is_set(self) -> bool: + return super().is_set() + + event = ForwardingEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + assert waiter.future is not None + try: + clock.now = 100.1 + event.set() + event.clear() + assert waiter.future.done() + assert not event.is_set() + assert deadline.signalled_at == 100.1 + 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) - with Server(respond) as server: + +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: - page = await call( + result = await call( client, - "export_reviews", + "wait_for_review", ORG, - "reviews", - format=format, - from_time="2026-10-01T00:00:00Z", - to_time="2026-10-25T00:00:00Z", + REVIEW, + timeout=0, + head_commit_sha=HEAD, + cancel_event=event, ) - assert [row["kind"] for row in page.rows] == kinds - # The generated wire enum must accept the same retained spellings. - assert [ExportReviewKind(row["kind"]).value for row in page.rows] == kinds - if format == "ndjson": - assert [ReviewsExportRow.from_dict(row).kind.value for row in page.rows] == kinds - assert page.next_cursor is None + assert len(server.requests) == 0 + assert result.status == "TIMED_OUT" + assert clock.delays == [] @MODES -async def test_knowledge_negotiation_scope_and_no_retry(mode: str) -> None: - refusal = False - wrong_id = False - - def respond(request: Request, index: int) -> Reply: - body = json.loads(request.body) - assert request.path == "/mcp" - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - if body["method"] == "initialize": - return Reply( - body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} +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 request.headers["MCP-Protocol-Version"] == "2025-11-25" - if body["method"] == "notifications/initialized": - return Reply(status=202, body=b"") - assert body["params"] == { - "name": "get_wiki_page", - "arguments": {"repository": "owner/name", "page_key": "index", "commit": "a" * 40}, - } - if refusal: - return Reply(status=503, body={"detail": "unavailable"}) - return Reply( - body={ - "jsonrpc": "2.0", - "id": 99 if wrong_id else 2, - "result": { - "isError": True, - "content": [{"type": "text", "text": "RESOURCE_NOT_FOUND"}], - }, - } - ) + assert server.requests == [] + assert result.status == "STOPPED" + assert result.reason == "The wait was cancelled by the caller." - with Server(respond) as server: - async with session(mode, server.url) as client: - async def invoke() -> Any: - result = client.knowledge.get_wiki_page("owner/name", "index", commit="a" * 40) - return await result if inspect.isawaitable(result) else result +@MODES +async def test_wait_for_review_timeout_validation_signal_does_not_become_entry_state( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() - assert (await invoke())["isError"] is True - wrong_id = True - with pytest.raises(ProoflineError): - await invoke() - refusal = True - with pytest.raises(ProoflineError): - await invoke() - assert len(server.requests) == 9 + class ValidationTimeout: + def __float__(self) -> float: + event.set() + return 0.0 + def __lt__(self, other: float) -> bool: + return float(self) < other -@MODES -async def test_fixes_preserve_unavailable_context_and_never_retry(mode: str) -> None: - observed: list[dict[str, Any]] = [] - refuse = False - result = { - "content": [{"type": "text", "text": "untrusted source"}], - "structuredContent": {"status": "UNAVAILABLE", "items": None}, - } + def __radd__(self, other: float) -> float: + return other + float(self) - def respond(request: Request, index: int) -> Reply: - body = json.loads(request.body) - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - if body["method"] == "initialize": - return Reply( - body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=ValidationTimeout(), # type: ignore[arg-type] + cancel_event=event, ) - if body["method"] == "notifications/initialized": - return Reply(status=202, body=b"") - observed.append(body["params"]) - if refuse: - return Reply(status=503, body={"detail": "unavailable"}, headers={"Retry-After": "0"}) - return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + assert server.requests == [] + assert result.status == "TIMED_OUT" + assert event.is_set() + + +def test_condition_tracker_registry_does_not_retain_discarded_events() -> None: + event = threading.Event() + deadline = client_module._SignalDeadline(101.0) + client_module._track_thread_signal(event, deadline) + condition = event._cond + tracker = client_module._notify_trackers[condition] + condition_ref = weakref.ref(condition) + tracker_ref = weakref.ref(tracker) + client_module._untrack_thread_signal(event, deadline) + del tracker, condition, deadline, event + gc.collect() + assert condition_ref() is None + assert tracker_ref() is None + + +def test_condition_tracker_publishes_once_per_dispatch(monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + early = client_module._SignalDeadline(clock.now + 10.0) + late = client_module._SignalDeadline(clock.now + 10.0) + + class InterleavingCondition(threading.Condition): + def notify_all(self) -> None: + client_module._track_thread_signal(event, late) + super().notify_all() + + event = threading.Event() + event._cond = InterleavingCondition(threading.Lock()) + client_module._track_thread_signal(event, early) + try: + event.set() + assert early.signalled_at == clock.now + assert late.signalled_at is None + finally: + client_module._untrack_thread_signal(event, early) + client_module._untrack_thread_signal(event, late) + + +def test_initial_sync_signal_does_not_hold_caller_condition_locks() -> None: + acquired: list[object] = [] + + class TrackingLock: + def __init__(self) -> None: + self._lock = threading.Lock() + + def __enter__(self) -> Any: + acquired.append(self) + return self._lock.__enter__() + + def __exit__(self, *exc: object) -> bool: + self._lock.release() + return False + + def acquire(self, *args: Any, **kwargs: Any) -> bool: + got = self._lock.acquire(*args, **kwargs) + if got: + acquired.append(self) + return got + + def release(self) -> None: + self._lock.release() + + def locked(self) -> bool: + return self._lock.locked() + + def _is_owned(self) -> bool: + return self._lock._is_owned() + + first = threading.Event() + second = threading.Event() + first._cond = threading.Condition(TrackingLock()) + second._cond = threading.Condition(TrackingLock()) + first.other = second # type: ignore[attr-defined] + second.other = first # type: ignore[attr-defined] + deadline = client_module._SignalDeadline(time.monotonic() + 5.0) + client_module._initial_sync_signal(first, deadline, False, time.monotonic()) + client_module._untrack_sync_cancel(first, deadline) + assert acquired == [] + + +def test_initial_sync_signal_uses_a_shared_non_reentrant_lock_once() -> None: + # Holding one lock twice would hang before any wait deadline is established. + code = """ +import sys +import threading +import time - with Server(respond) as server: - async with session(mode, server.url) as client: +sys.path.insert(0, sys.argv[1]) +from proofline import client + +lock = threading.Lock() +first = threading.Event() +second = threading.Event() +first._cond = threading.Condition(lock) +second._cond = threading.Condition(lock) +first.backing = second +deadline = client._SignalDeadline(time.monotonic() + 5.0) +client._initial_sync_signal(first, deadline, False, time.monotonic()) +client._untrack_sync_cancel(first, deadline) +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" - async def invoke(name: str, *args: Any, **kwargs: Any) -> Any: - answer = getattr(client.fixes, name)(*args, **kwargs) - return await answer if inspect.isawaitable(answer) else answer - assert await invoke("list_open_findings", "owner/name", 7) == result - assert await invoke("get_fix_context", str(REVIEW)) == result - assert ( - await invoke( - "request_reverification", - str(REVIEW), - [str(REVIEW)], - "a" * 40, - note="fixed code", - ) - == result - ) - assert await invoke("get_reverification", str(REVIEW)) == result - assert observed == [ - { - "name": "list_open_findings", - "arguments": {"repository": "owner/name", "pull_request_number": 7}, - }, - {"name": "get_fix_context", "arguments": {"finding_id": str(REVIEW)}}, - { - "name": "request_reverification", - "arguments": { - "review_id": str(REVIEW), - "finding_ids": [str(REVIEW)], - "commit_sha": "a" * 40, - "note": "fixed code", - }, - }, - {"name": "get_reverification", "arguments": {"request_id": str(REVIEW)}}, - ] - refuse = True - with pytest.raises(ProoflineError): - await invoke("request_reverification", str(REVIEW), [str(REVIEW)], "a" * 40) - assert len(observed) == 5 +def test_condition_notification_does_not_invoke_an_is_set_descriptor() -> None: + code = """ +import sys +import threading +sys.path.insert(0, sys.argv[1]) +from proofline import client -@MODES -async def test_shared_review_outcome_contract(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: - Clock(monkeypatch) - fixture = json.loads((Path(__file__).parent / "fixtures/review-outcomes.json").read_text()) - for case in fixture["cases"]: - body = case["review"] - pending = case["outcome"] is None - settled = next( - item["review"] for item in fixture["cases"] if item["name"] == "review-completed" - ) - with Server( - lambda request, index: Reply(body=settled if pending and index else body) - ) as server: - async with session(mode, server.url) as client: - result = await call(client, "wait_for_review", ORG, UUID(body["id"])) - assert result.status == ("COMPLETED" if pending else case["outcome"]), case["name"] - assert len(server.requests) == (2 if pending else 1), case["name"] - assert [ - { - "assessment_id": str(gap.assessment_id) if gap.assessment_id else None, - "reason_codes": list(gap.reason_codes), - } - for gap in result.gaps - ] == case["gaps"], case["name"] + +class DescriptorEvent(threading.Event): + @property + def is_set(self): + assert not self._cond._lock.locked(), "descriptor invoked under the condition" + return bool(self._flag) + + +event = DescriptorEvent() +now = [100.0] +client.monotonic = lambda: now[0] + + +def wait_for_event(wait_event, timeout, deadline=None): + now[0] = 100.5 + wait_event.set() + wait_event.clear() + return False + + +client._wait_for_event = wait_for_event +result = client._sleep_with_cancel(5, event, cutoff=101.0) +assert result is True +print("OK") +""" + root = Path(__file__).resolve().parents[1] + result = subprocess.run( + [sys.executable, "-c", code, str(root)], + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "OK" + + +def test_condition_tracker_latches_a_forwarding_is_set_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class ForwardingEvent(threading.Event): + def is_set(self) -> bool: + return super().is_set() + + clock = Clock(monkeypatch) + event = ForwardingEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert not event.is_set() + assert deadline.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_rejects_a_call_then_false_override( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class HiddenEvent(threading.Event): + def is_set(self) -> bool: + super().is_set() + return False + + clock = Clock(monkeypatch) + event = HiddenEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert not event.is_set() + assert deadline.signalled_at is None + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_rewraps_replaced_hooks_before_reuse( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + standard_all = threading.Condition.notify_all + standard_notify = threading.Condition.notify + first = client_module._SignalDeadline(clock.now + 10.0) + second = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, first) + tracker = client_module._notify_trackers[condition] + + def replacement_all(*args: Any, **kwargs: Any) -> None: + standard_all(condition, *args, **kwargs) + + def replacement_notify(*args: Any, **kwargs: Any) -> None: + standard_notify(condition, *args, **kwargs) + + condition.notify_all = replacement_all # type: ignore[method-assign] + condition.notify = replacement_notify # type: ignore[method-assign] + client_module._track_thread_signal(event, second) + try: + assert condition.notify_all is tracker.installed_notify_all + assert condition.notify is tracker.installed_notify + assert tracker.saved_notify_all is replacement_all + assert tracker.saved_notify is replacement_notify + clock.now = 100.5 + event.set() + event.clear() + assert first.signalled_at == 100.5 + assert second.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, first) + client_module._untrack_thread_signal(event, second) + + +def test_async_waiter_releases_a_shared_loop_binding_with_its_last_waiter() -> None: + event = asyncio.Event() + + def overlapping_waits() -> None: + async def main() -> None: + loop = asyncio.get_running_loop() + end = loop.time() + 10.0 + first = client_module._SignalDeadline(end) + second = client_module._SignalDeadline(end) + first_waiter = client_module._watch_async_waiter(event, first) + second_waiter = client_module._watch_async_waiter(event, second) + assert event._loop is loop + assert len(event._waiters) == 2 + client_module._unwatch_async_waiter(first_waiter, first) + assert event._loop is loop + assert len(event._waiters) == 1 + assert event in client_module._async_loop_bindings + client_module._unwatch_async_waiter(second_waiter, second) + assert event._loop is None + assert not event._waiters + assert event not in client_module._async_loop_bindings + + asyncio.run(main()) + + def reuse_on_another_loop() -> None: + async def main() -> None: + loop = asyncio.get_running_loop() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + try: + assert event._loop is loop + finally: + client_module._unwatch_async_waiter(waiter, deadline) + + asyncio.run(main()) + + overlapping_waits() + reuse_on_another_loop() + assert event._loop is None + + +async def test_async_waiter_setup_failure_releases_the_loop_binding( + monkeypatch: pytest.MonkeyPatch, +) -> None: + event = asyncio.Event() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + + def fail(*args: Any, **kwargs: Any) -> None: + raise RuntimeError("future hook failed") + + monkeypatch.setattr(client_module, "_watch_async_future", fail) + with pytest.raises(RuntimeError, match="future hook failed"): + client_module._watch_async_waiter(event, deadline) + assert event._loop is None + assert not event._waiters + assert event not in client_module._async_loop_bindings + + +def test_record_signal_before_skips_drain_without_an_event( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail() -> None: + raise AssertionError("no pending signal may be drained without an event") + + monkeypatch.setattr(client_module, "_drain_signals", fail) + deadline = client_module._SignalDeadline(101.0) + assert client_module._record_signal_before(None, deadline, deadline.end) is False @MODES -async def test_mcp_per_call_organizations_and_refusals(mode: str) -> None: - first, second, foreign = (str(ORG), str(REVIEW), str(ASSESSMENT)) - admitted = [first, second] - observed: list[dict[str, Any]] = [] - concurrent = False - overlap = threading.Barrier(2) +async def test_wait_for_review_validates_head_before_building_the_url( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) - def respond(request: Request, index: int) -> Reply: - assert request.path == "/mcp" - assert request.headers["Authorization"] == f"Bearer {TOKEN}" - body = json.loads(request.body) - if body["method"] == "initialize": - return Reply( - body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}} - ) - assert request.headers["MCP-Protocol-Version"] == "2025-11-25" - if body["method"] == "notifications/initialized": - return Reply(status=202, body=b"") - params = body["params"] - observed.append(params) - if params["name"] == "list_organizations": - assert params["arguments"] == {} - result: dict[str, Any] = { - "content": [], - "structuredContent": { - "ok": True, - "data": {"organizations": [{"organization_id": value} for value in admitted]}, - }, - } - else: - if concurrent: - # Neither response completes until both tool calls have arrived. - overlap.wait(timeout=5) - target = params["arguments"].get("organization_id") - code = ( - "ORGANIZATION_REQUIRED" - if target is None - else "NOT_AUTHORIZED" - if target not in admitted - else None - ) - payload = ( - { - "ok": False, - "error": {"code": code, "message": "Target refused", "retryable": False}, - } - if code - else {"ok": True, "data": {"organization_id": target}} + def fail_url(*args: Any, **kwargs: Any) -> str: + raise RuntimeError("URL construction failed") + + monkeypatch.setattr(client_module, "_review_url", fail_url) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError, match="head commit"): + await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=100, + head_commit_sha="not-a-sha", + ) + assert server.requests == [] + + +@MODES +async def test_wait_for_review_counts_validation_toward_the_cancellable_budget( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() + real_head = client_module._head_commit + + def slow_head(value: str | None) -> None: + clock.sleep(5.0) + real_head(value) + + monkeypatch.setattr(client_module, "_head_commit", slow_head) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=5, cancel_event=event ) - result = { - "isError": code is not None, - "content": [{"type": "text", "text": json.dumps(payload)}], - "structuredContent": payload, - } - return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + assert server.requests == [] + assert result.status == "TIMED_OUT" + assert clock.delays == [5.0] - with Server(respond) as server: + +@MODES +async def test_wait_for_review_without_an_event_starts_the_budget_after_validation( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + real_head = client_module._head_commit + + def slow_head(value: str | None) -> None: + clock.sleep(5.0) + real_head(value) + + monkeypatch.setattr(client_module, "_head_commit", slow_head) + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=5) + assert len(server.requests) == 1 + assert result.status == "TIMED_OUT" + assert clock.delays == [5.0, 5.0] - async def invoke(group: str, name: str, *args: Any, **kwargs: Any) -> Any: - result = getattr(getattr(client, group), name)(*args, **kwargs) - return await result if inspect.isawaitable(result) else result - discovery = await invoke("mcp", "list_organizations") - assert discovery["structuredContent"]["data"]["organizations"] == [ - {"organization_id": first}, - {"organization_id": second}, - ] - cases = [ - ( - "knowledge", - "list_wiki_pages", - ("owner/name",), - {"commit": "a" * 40}, - {"repository": "owner/name", "commit": "a" * 40}, - ), - ( - "knowledge", - "get_wiki_page", - ("owner/name", "index"), - {}, - {"repository": "owner/name", "page_key": "index"}, - ), - ( - "knowledge", - "ask_codebase", - ("owner/name", "How?"), - {}, - {"repository": "owner/name", "question": "How?"}, - ), - ( - "knowledge", - "get_architecture_document", - (str(REVIEW),), - {}, - {"environment_id": str(REVIEW)}, - ), - ("knowledge", "get_plan", (str(REVIEW),), {}, {"plan_id": str(REVIEW)}), - ( - "knowledge", - "start_plan_implementation", - (str(REVIEW),), - {}, - {"plan_id": str(REVIEW)}, - ), - ( - "knowledge", - "get_plan_implementation", - (str(REVIEW),), - {}, - {"implementation_id": str(REVIEW)}, - ), - ( - "fixes", - "list_open_findings", - ("owner/name", 7), - {}, - {"repository": "owner/name", "pull_request_number": 7}, - ), - ("fixes", "get_fix_context", (str(REVIEW),), {}, {"finding_id": str(REVIEW)}), - ( - "fixes", - "request_reverification", - (str(REVIEW), [str(REVIEW)], "a" * 40), - {"note": "fixed"}, - { - "review_id": str(REVIEW), - "finding_ids": [str(REVIEW)], - "commit_sha": "a" * 40, - "note": "fixed", - }, - ), - ("fixes", "get_reverification", (str(REVIEW),), {}, {"request_id": str(REVIEW)}), - ] - for group, name, args, kwargs, expected in cases: - for target in (first, second): - answer = await invoke(group, name, *args, **kwargs, organization_id=target) - assert answer["structuredContent"]["data"]["organization_id"] == target - assert observed[-1] == { - "name": name, - "arguments": {**expected, "organization_id": target}, - } +async def test_clock_async_wait_uses_an_explicit_deadline_gate( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() + with pytest.raises(AssertionError, match="explicitly"): + await clock.async_wait_for_event(event, clock.now + 10.0) + assert clock.delays == [] + clock.reach_deadline() + assert await clock.async_wait_for_event(event, clock.now + 10.0) is False + assert clock.delays == [10.0] + + clock.now = 100.1 + event.set() + signal = client_module._SignalDeadline(clock.now + 10.0) + clock.reach_deadline() + assert await clock.async_wait_for_event(event, signal.end, signal) is False + assert signal.signalled_at is None + assert clock.delays == [10.0, 10.0] + + clock.now = 100.1 + signal = client_module._SignalDeadline(clock.now + 10.0) + clock.publish() + assert await clock.async_wait_for_event(event, signal.end, signal) is True + assert signal.signalled_at == 100.1 + + event.clear() + event.set() + clock.now = 100.2 + signal = client_module._SignalDeadline(clock.now + 10.0) + clock.publish() + clock.now = 120.0 + clock.publish() + assert await clock.async_wait_for_event(event, signal.end, signal) is True + assert signal.signalled_at == 100.2 + + +async def test_manual_timer_is_one_shot( + monkeypatch: pytest.MonkeyPatch, +) -> None: + real_wait = client_module._async_wait_for_event + clock = Clock(monkeypatch) + event = asyncio.Event() + cutoff = clock.now + 0.01 + timers = patch_helper_timer(monkeypatch, asyncio.get_running_loop(), (cutoff,)) + task = asyncio.create_task(real_wait(event, cutoff, client_module._SignalDeadline(cutoff))) + try: + await wait_until(lambda: bool(event._waiters), task) + timers[0].fire() + assert await asyncio.wait_for(task, 1.0) is False + timers[0].fire() + finally: + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +def test_condition_tracker_rehook_preserves_a_captured_wrapper_delegate( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + condition = threading.Condition(threading.Lock()) + event = threading.Event() + event._cond = condition + first = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, first) + captured = condition.notify_all + + def forwarding(*args: Any, **kwargs: Any) -> Any: + return captured(*args, **kwargs) + + condition.notify_all = forwarding # type: ignore[method-assign] + second = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, second) + try: + clock.now = 100.5 + event.set() + assert first.signalled_at == 100.5 + assert second.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, first) + client_module._untrack_thread_signal(event, second) + + +def test_condition_tracker_rolls_back_a_hook_that_fails_after_storing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) - if mode == "async": - concurrent = True - answers = await asyncio.gather( - invoke("knowledge", "get_plan", str(REVIEW), organization_id=first), - invoke("fixes", "get_fix_context", str(REVIEW), organization_id=second), - ) - concurrent = False - assert [ - answer["structuredContent"]["data"]["organization_id"] for answer in answers - ] == [first, second] + class RaisingCondition(threading.Condition): + def __setattr__(self, name: str, value: Any) -> None: + if name == "notify_all" and getattr(self, "_fail", False): + super().__setattr__(name, value) + raise RuntimeError("hook failed") + super().__setattr__(name, value) + + condition = RaisingCondition(threading.Lock()) + event = threading.Event() + event._cond = condition + first = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, first) + tracker = client_module._notify_trackers[condition] + + def replacement(*args: Any, **kwargs: Any) -> None: + threading.Condition.notify_all(condition, *args, **kwargs) + + condition.notify_all = replacement # type: ignore[method-assign] + condition._fail = True # type: ignore[attr-defined] + second = client_module._SignalDeadline(clock.now + 10.0) + with pytest.raises(RuntimeError, match="hook failed"): + client_module._track_thread_signal(event, second) + condition._fail = False # type: ignore[attr-defined] + assert condition.notify_all is replacement + assert first in tracker.subscribers + assert second not in tracker.subscribers + client_module._untrack_thread_signal(event, first) + + +def test_condition_tracker_defers_an_overridden_predicate_until_a_checkpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.gate = False - async def refused(target: str | None, code: str) -> None: - before = len(observed) - kwargs = {} if target is None else {"organization_id": target} - answer = await invoke( - "fixes", - "request_reverification", - str(REVIEW), - [str(REVIEW)], - "a" * 40, - **kwargs, - ) - assert answer["isError"] is True - assert answer["structuredContent"]["error"]["code"] == code - assert json.loads(answer["content"][0]["text"]) == answer["structuredContent"] - assert len(observed) == before + 1 - assert observed[-1]["arguments"].get("organization_id") == target - assert ("organization_id" in observed[-1]["arguments"]) == (target is not None) + def is_set(self) -> bool: + return self.gate and super().is_set() - # An earlier explicit target must never become an implicit default. - await refused(None, "ORGANIZATION_REQUIRED") - await refused(foreign, "NOT_AUTHORIZED") - admitted.remove(first) - await refused(first, "NOT_AUTHORIZED") - remaining = await invoke("mcp", "list_organizations") - assert remaining["structuredContent"]["data"]["organizations"] == [ - {"organization_id": second} - ] - answer = await invoke("fixes", "get_fix_context", str(REVIEW), organization_id=second) - assert answer["structuredContent"]["data"]["organization_id"] == second - assert len(server.requests) == len(observed) * 3 + clock = Clock(monkeypatch) + event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.signalled_at is None + event.gate = True + event.set() + assert client_module._record_signal_before(event, deadline, deadline.end) is True + assert deadline.signalled_at is not None + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_deferred_predicate_does_not_backdate_a_late_signal( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.gate = False + def is_set(self) -> bool: + return self.gate and super().is_set() -def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> None: - # Compile consumer code through the public entry point; dynamic HTTP tests - # cannot catch a missing keyword in just one sync/async method signature. - lines = ["from proofline import ProoflineClient, AsyncProoflineClient, KnowledgeResult"] - calls = [ - 'knowledge.list_wiki_pages("owner/name", commit="a" * 40)', - 'knowledge.get_wiki_page("owner/name", "index")', - 'knowledge.ask_codebase("owner/name", "How?")', - 'knowledge.get_architecture_document("environment-id")', - 'knowledge.get_plan("plan-id")', - 'knowledge.start_plan_implementation("plan-id")', - 'knowledge.get_plan_implementation("implementation-id")', - 'fixes.list_open_findings("owner/name", 7)', - 'fixes.get_fix_context("finding-id")', - 'fixes.request_reverification("review-id", ["finding-id"], "a" * 40, note="fixed")', - 'fixes.get_reverification("request-id")', - ] - for prefix, kind, wait in [ - ("", "ProoflineClient", ""), - ("async ", "AsyncProoflineClient", "await "), - ]: - lines.append(f"{prefix}def use_{kind}(client: {kind}) -> None:") - lines.append(f" result: KnowledgeResult = {wait}client.mcp.list_organizations()") - for expression in calls: - lines.append(f" result = {wait}client.{expression}") - targeted = expression[:-1] + ', organization_id="00000000-0000-7000-8000-000000000001")' - lines.append(f" result = {wait}client.{targeted}") - fixture = tmp_path / "mcp_types.py" - fixture.write_text("\n".join(lines)) - # Use the same mypy configuration as the SDK qualification gate. - subprocess.run([sys.executable, "-m", "mypy", str(fixture)], check=True) + clock = Clock(monkeypatch) + event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.pending + clock.now = 111.0 + event.gate = True + event.set() + client_module._verify_deferred_signals(deadline, deadline.end) + assert deadline.signalled_at is None + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_wakes_for_a_backing_event_sharing_the_condition( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + event = threading.Event() + backing = threading.Event() + backing._cond = event._cond + event.backing = backing # type: ignore[attr-defined] + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + backing.set() + # The outer flag is untouched, so this is only a wake hint, but the + # shared condition must not discard the backing event that carried it. + assert deadline.signalled_at is None + assert deadline.signal_event.is_set() + assert client_module._record_signal_before(event, deadline, deadline.end) is False + finally: + client_module._untrack_thread_signal(event, deadline) + + +def test_condition_tracker_verifies_a_backing_notification_from_the_supplied_flag( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class BackingEvent(threading.Event): + def __init__(self) -> None: + super().__init__() + self.backing = threading.Event() + self.is_set = threading.Event.is_set.__get__(self, threading.Event) + + def set(self) -> None: + self._flag = True + self.backing.set() + + clock = Clock(monkeypatch) + event = BackingEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + client_module._track_thread_signal(event, deadline) + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.signalled_at == 100.5 + finally: + client_module._untrack_thread_signal(event, deadline) + + +async def test_async_event_verifies_the_predicate_once_per_dispatch() -> None: + class CountingEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.calls = 0 + self.gate = False + + def is_set(self) -> bool: + self.calls += 1 + return self.gate and super().is_set() + + event = CountingEvent() + loop = asyncio.get_running_loop() + deadlines = [client_module._SignalDeadline(loop.time() + 10.0) for _ in range(3)] + waiters = [client_module._watch_async_waiter(event, deadline) for deadline in deadlines] + try: + event.set() + event.clear() + assert event.calls == 1 + assert all(deadline.signalled_at is None for deadline in deadlines) + event.set() + event.clear() + assert event.calls == 2 + finally: + for waiter, deadline in zip(waiters, deadlines): + client_module._unwatch_async_waiter(waiter, deadline) + + +async def test_async_future_watch_wakes_without_stopping_when_predicate_is_closed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + class GatedEvent(asyncio.Event): + def __init__(self) -> None: + super().__init__() + self.gate = False + + def is_set(self) -> bool: + return self.gate and super().is_set() + + clock = Clock(monkeypatch) + event = GatedEvent() + deadline = client_module._SignalDeadline(clock.now + 10.0) + waiter = client_module._watch_async_waiter(event, deadline) + future = waiter.future + assert future is not None + try: + clock.now = 100.5 + event.set() + event.clear() + assert deadline.signalled_at is None + assert not future.done() + assert any(future is pending for pending in event._waiters) + clock.now = 101.25 + event.gate = True + event.set() + assert deadline.signalled_at == 101.25 + event.clear() + await asyncio.sleep(0) + assert future.done() + assert client_module._record_signal_before(event, deadline, deadline.end) is True + assert deadline.signalled_at == 101.25 + finally: + client_module._unwatch_async_waiter(waiter, deadline) + + +async def test_async_binding_clears_for_a_native_waiter_registered_after_teardown() -> None: + event = asyncio.Event() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + first_native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + client_module._unwatch_async_waiter(sdk_waiter, deadline) + + second_native = asyncio.create_task(event.wait()) + await wait_until(lambda: len(event._waiters) == 2) + first_native.cancel() + with pytest.raises(asyncio.CancelledError): + await first_native + await wait_until(lambda: len(event._waiters) == 1) + + second_native.cancel() + with pytest.raises(asyncio.CancelledError): + await second_native + await wait_until( + lambda: event._loop is None and event not in client_module._async_loop_bindings + ) + assert not event._waiters + + +async def test_async_waiter_rolls_back_a_binding_created_by_a_failing_binder() -> None: + class BindingThenFailingEvent(asyncio.Event): + def _get_loop(self) -> None: + self._loop = asyncio.get_running_loop() + raise RuntimeError("bind failed") + + event = BindingThenFailingEvent() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + with pytest.raises(RuntimeError, match="different event loop"): + client_module._watch_async_waiter(event, deadline) + assert event._loop is None + assert event not in client_module._async_loop_bindings + + +async def test_async_waiter_rolls_back_other_binder_failures() -> None: + class BindingThenFailingEvent(asyncio.Event): + def _get_loop(self) -> None: + self._loop = asyncio.get_running_loop() + raise ValueError("bind failed") + + event = BindingThenFailingEvent() + deadline = client_module._SignalDeadline(asyncio.get_running_loop().time() + 10.0) + with pytest.raises(ValueError, match="bind failed"): + client_module._watch_async_waiter(event, deadline) + assert event._loop is None + assert event not in client_module._async_loop_bindings + + +async def test_async_binding_survives_a_done_native_future_still_registered() -> None: + loop = asyncio.get_running_loop() + event = asyncio.Event() + deadline = client_module._SignalDeadline(loop.time() + 10.0) + sdk_waiter = client_module._watch_async_waiter(event, deadline) + binding = client_module._async_loop_bindings.get(event) + assert binding is not None + native = loop.create_future() + event._waiters.append(native) # type: ignore[arg-type] + try: + client_module._unwatch_async_waiter(sdk_waiter, deadline) + native.set_result(True) + await asyncio.sleep(0) + assert event in client_module._async_loop_bindings + event._waiters.remove(native) # type: ignore[arg-type] + client_module._clear_temporary_async_binding(event, binding) + assert event not in client_module._async_loop_bindings + finally: + if native in event._waiters: # type: ignore[operator] + event._waiters.remove(native) # type: ignore[arg-type] + client_module._clear_temporary_async_binding(event, binding) @MODES -async def test_export_ndjson_preserves_unicode_line_separators(mode: str) -> None: - kwargs = { - "from_time": "2026-10-01T00:00:00Z", - "to_time": "2026-10-25T00:00:00Z", - } +async def test_cancellable_wait_budget_starts_before_timeout_validation( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + event = asyncio.Event() if mode == "async" else threading.Event() - for separator in ("\x85", "\u2028", "\u2029"): - row = { - "dataset_version": 1, - "claim": f"before{separator}after", - } - body = (json.dumps(row, ensure_ascii=False) + "\n").encode("utf-8") + class SlowTimeout: + def __float__(self) -> float: + clock.now += 2.0 + return 1.0 - def respond(request: Request, index: int) -> Reply: - return Reply( - body=body, - headers={ - "Content-Type": "application/x-ndjson", - "X-Proofline-Export-Version": "1", - "X-Proofline-Export-Settled-Until": "2026-10-25T00:00:00Z", - "X-Proofline-Export-Next-Cursor": "next-page", - }, - ) + def __lt__(self, other: object) -> bool: + return float(self) < float(other) # type: ignore[arg-type] - with Server(respond) as server: - async with session(mode, server.url) as client: - exported = await call( - client, - "export_reviews", - ORG, - "findings", - format="ndjson", - **kwargs, - ) + def __radd__(self, other: float) -> float: + return other + float(self) - assert len(exported.rows) == 1 - assert exported.rows[0]["claim"] == row["claim"] - assert exported.next_cursor == "next-page" + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=SlowTimeout(), cancel_event=event + ) + assert server.requests == [] + assert result.status == "TIMED_OUT"