diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 0e7fc70522..b3f9054c07 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -550,9 +550,14 @@ can be lost: would write for the phases it finished can be lost. The stop that ran out logs an ERROR saying so; a second stop call that joined it and ran out of its own time, cancelled or not, logs a WARNING. A cancel of the engine's stop during this wait is held and raised once the store has - closed, except at least when a stop step that runs before the store's guarded teardown fails - first: the stop then ends on that failure without closing the store, as it does when no cancel - came. + closed, and the message graph's stop still runs first. The engine's other stop steps are + guarded the same way. With a message graph, at least these leave the store open: a cancel, + `KeyboardInterrupt` or `SystemExit` that leaves a step before the graph's stop, except a cancel + during this wait; a cancel requested before the stop, unless this wait is the first step; a + failed or cancelled graph stop, when a listener may still be live. The first two never begin the + graph's stop, but the remaining earlier steps run and can hold the stop. After a swallowed cancel + the graph's stop and the close run, unless a later step also ends cancelled. An inbound that will + not stop holds the graph's stop. - **A CRL reload pass in flight** gets at most about 1.8 s at the 3 s minimum, or about 0.8 s while a config write is still running, and less when an earlier stop step was slow, down to the same 0.1 s. When the budget cuts the pass, it is abandoned with a WARNING; a cancel of the stop diff --git a/messagefoundry/pipeline/engine.py b/messagefoundry/pipeline/engine.py index 64d2cc031b..db6ce48416 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -10,11 +10,12 @@ from __future__ import annotations import asyncio +import contextlib import json import logging import os import time -from collections.abc import Awaitable, Callable, Mapping, Sequence +from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence from dataclasses import dataclass, field, replace from pathlib import Path from typing import Any, Protocol, runtime_checkable @@ -243,6 +244,179 @@ def deadline(self, *, kept: float) -> StopDeadline | None: return None if self._deadline is None else StopDeadline(self._deadline - kept) +class _StopSteps: + """The guard :meth:`Engine.stop` runs each of its steps under (BACKLOG #8190). + + Each step has its own guard. A failed or cancelled step does not by itself skip the rest, + except in at least the cases below. A failed or cancelled barrier skips every later step and + the close. A cancel of the stop is told apart from a CancelledError a step leaked from a task + of its own by the stopping task's cancel count: a CancelledError is a cancel of the stop when + the count is above both its value at the stop's entry and its value when the stop last took a + cancel, whichever step took delivery of it. A cancel requested before the stop and not yet + delivered is delivered and held by :meth:`take_a_pending_cancel`, before the first step, and + counts as taken in the first step that runs, where it would otherwise have been delivered, + or as one in the graph stop when no step runs before it. Delivered early, it does not cut that + first step's own wait, as one delivered in it would. A cancel of the stop is held, and + raised by :meth:`finish` in place of any ordinary error, which is then logged; one that a step + swallowed is raised too, since the count still shows it. A leaked CancelledError + is a step failure like any other, except at least where a cancel of the stop that a step + swallowed came before it: the count then cannot tell them apart, and the leak is read as the + stop's cancel. The first failure is held and raised by :meth:`finish`, and logged when it + happens, with its traceback, when it is an ordinary Exception; a later one is logged when it + happens, unless it replaces the held one, which is then logged again. A SystemExit, + KeyboardInterrupt or other BaseException that is not an Exception replaces a held ordinary + error, is never replaced, and is raised in place of a cancel. + + A cancel of the stop that a step before the graph stop let out marks the stop as leaving, + unless the step was given ``leaves_on_cancel=False``, and so does one requested before the + stop whose first step is such a step, whether that step would have let it out or swallowed + it. A cancel a step swallowed does not: the graph stop and the close run, and a wedged + inbound then holds the stop. :meth:`leave_before_graph_stop`, called where the graph stop + would begin, raises as :meth:`finish` orders it when the stop is leaving or a step before it + held a BaseException that is not an Exception, so that stop is never begun or waited on and + the store is left open. + + A ``barrier`` step is one whose failure or cancel leaves the graph possibly still live: the + registry runner's stop raises before it cancels the drain side's workers (ADR 0157 Amendment + B). The stop then raises at once, as :meth:`finish` orders it, so the coordinator is not + deregistered and the store is not closed under a live graph: a held SystemExit or + KeyboardInterrupt first, then a cancel of the stop, then the barrier's own failure, which + replaces an earlier ordinary one. GeneratorExit is not caught either, so a stop coroutine that + is being closed runs no further step; a held failure or cancel is logged then.""" + + def __init__(self) -> None: + self._task = asyncio.current_task() + # Read at entry: a cancel the caller took before calling stop() is not the stop's, and one + # a step swallowed still counts at the end. + self._baseline = self._cancels() + # The count when the stop last took a cancel: a CancelledError with the count no higher + # was requested by nobody since, so a step leaked it. + self._taken = self._baseline + self._cancel: asyncio.CancelledError | None = None + # Whether a step that leaves on a cancel let one of the stop out, or was the first step + # after a cancel requested before the stop. + self._leaves = False + # A cancel taken before the first step, not yet counted against a step. + self._pending_unplaced = False + self._failure: BaseException | None = None + self._failure_label = "" + + def _cancels(self) -> int: + return 0 if self._task is None else self._task.cancelling() + + async def take_a_pending_cancel(self) -> None: + """Deliver and hold a cancel requested before the stop and not yet delivered, so the step + it would otherwise reach does not take it for a leak, or swallow it. With the count at + zero none can be pending and this does not suspend; above zero it costs one turn of the + event loop.""" + if self._baseline == 0: + return + try: + await asyncio.sleep(0) + except asyncio.CancelledError as exc: + self._cancel, self._taken = exc, self._cancels() + self._pending_unplaced = True + + def leave_before_graph_stop(self) -> None: + """Called where the graph stop would begin: raise, as :meth:`finish` orders it, if a step + held a BaseException that is not an Exception, such as SystemExit or KeyboardInterrupt, + if a step that leaves on a cancel let one out, + or if a cancel taken before the first step is still unplaced, since the graph stop would + then be the step to take it.""" + if self._exiting or self._leaves or self._pending_unplaced: + self.finish() + + @property + def _exiting(self) -> bool: + """Whether the held failure is not an Exception, such as SystemExit or KeyboardInterrupt, + and so is raised before all else.""" + return self._failure is not None and not isinstance(self._failure, Exception) + + @contextlib.contextmanager + def step( + self, label: str, *, barrier: bool = False, leaves_on_cancel: bool = True + ) -> Iterator[None]: + if self._pending_unplaced: + self._pending_unplaced = False + self._leaves = self._leaves or leaves_on_cancel + try: + yield + except GeneratorExit: + if self._failure is not None: + log.error( + "the engine stop was closed during step %r; the failure held from step %r is " + "dropped: %s", + label, + self._failure_label, + safe_exc(self._failure), + ) + if self._cancel is not None or self._cancels() > self._baseline: + log.error( + "the engine stop was closed during step %r; its held cancel is dropped", label + ) + raise + except asyncio.CancelledError as exc: + if self._cancels() > self._taken: + self._cancel, self._taken = self._cancel or exc, self._cancels() + self._leaves = self._leaves or leaves_on_cancel + else: + leaked = RuntimeError( + f"engine stop step {label!r} ended cancelled, though the stop was not cancelled" + ) + leaked.__cause__ = exc + self._hold(label, leaked, replaces=barrier) + if barrier: + self.finish() + except BaseException as exc: # noqa: BLE001 - held, and raised once every step has run + self._hold(label, exc, replaces=barrier or not isinstance(exc, Exception)) + if barrier: + self.finish() + + def _hold(self, label: str, exc: BaseException, *, replaces: bool) -> None: + """Hold ``exc`` as the failure to raise. The first failure is held, and logged when it + happens, with its traceback, when it is an ordinary Exception, so a process killed in a + later step still leaves it in the log; an exit request is not logged as a failure. A + failure already held is kept, and ``exc`` is logged in its place, unless ``replaces`` is + true and the held one is an ordinary Exception; then ``exc`` is held and the one it + replaces is logged. So a held SystemExit or KeyboardInterrupt is never replaced: a later + step's failure is logged, and :meth:`finish` raises the held one.""" + held, held_label = self._failure, self._failure_label + if held is None or (replaces and isinstance(held, Exception)): + self._failure, self._failure_label = exc, label + if held is None: + if isinstance(exc, Exception): + # On the handlers logging_setup configures, exc_info is rendered through + # safe_traceback; a handler without that guard renders it raw. + log.error("engine stop step %r failed: %s", label, safe_exc(exc), exc_info=exc) + return + exc, label = held, held_label + # safe_exc, as the registry runner renders an inbound stop's failure: no traceback. + log.error( + "engine stop step %r failed; another stop failure is raised in its place: %s", + label, + safe_exc(exc), + ) + + def finish(self) -> None: + """Raise what the steps left: SystemExit or KeyboardInterrupt first, then a cancel of the + stop, then the held failure.""" + failure = self._failure + if self._exiting and failure is not None: + raise failure + if self._cancel is not None or self._cancels() > self._baseline: + if failure is not None: + # The cancel replaces this error: said here, the error itself was logged when it + # was held. + log.error( + "engine stop step %r failed; the stop's cancel is raised in its place: %s", + self._failure_label, + safe_exc(failure), + ) + raise self._cancel if self._cancel is not None else asyncio.CancelledError() + if failure is not None: + raise failure + + #: How long a connection flag toggle waits for the lock, then again for the store (BACKLOG #2623). A #: write normally takes milliseconds, so this is a stuck or saturated store. Well under the API's #: 120 s request deadline (``api/request_timeout.py``), so the caller hears the toggle's own refusal @@ -4580,12 +4754,39 @@ async def stop(self, *, budget_seconds: float | None = None) -> None: they wait for (the owner ruled on 2026-11-22 that the budget wins). docs/SERVICE.md, *Start / stop / status*, says what each cut loses. + Each step runs under :class:`_StopSteps`, and so do the alert sink's drain lookup and the + coordinator's demote-hook check, which run that object's own code. So a step that raises + or is cancelled does not skip the next step, and what the steps raised is raised once the + close has run, with at least these exceptions, each of which raises before the close: + + - where there is a registry runner, a cancel of this stop that a step before the graph + stop let out, other than the retention runner's stop; one requested before this stop + was called whose first step is such a step, whether that step would let it out or + swallow it (delivered early, it does not cut that step's own wait), or that reaches the + graph stop with no step before it; and a SystemExit, KeyboardInterrupt or other + BaseException that is not an Exception, from any step before the graph stop. This stop + raises it where the graph stop would begin, without beginning it or waiting on it, and + leaves the store open, as such a cancel or exit that escaped an early step did before + BACKLOG #8190. The steps before that point still run; + - the registry runner's stop failing or being cancelled, which may leave the graph live; + - the stop coroutine being closed mid-step. + + A cancel a step swallowed, a cancel in the retention runner's stop, and one requested + before this stop whose first step is that stop are held: the graph stop and the close + run, so a wedged inbound then holds this stop, and the cancel is raised after the close. + Before BACKLOG #8190 the retention runner's cancel was held the same way, and a cancel + an early step swallowed was lost once the graph stop and the close had run. + + A cancel requested before this stop is called and not yet delivered is a cancel of it, as + one requested during it is, even when a step would swallow it; one the caller already took + is not. + Last, once the store's close has run or raised, this engine's lease on the Transit pools - is released, once (BACKLOG #3929). A stop that raises before it reaches the close keeps the - lease, since the store and the graph may still be using the pools; a later stop that - reaches the close releases it. It waits for the pools' running calls only when the steps - ended or raised an ordinary error; a cancel, KeyboardInterrupt or SystemExit gets no - wait.""" + is released, once (BACKLOG #3929). A stop that ends before it reaches the close, for any + of the reasons above, keeps the lease, since the store and the graph may still be using + the pools; a later stop that reaches the close releases it. It waits for the pools' + running calls only when the steps ended or raised an ordinary error; a cancel, + KeyboardInterrupt or SystemExit gets no wait.""" budget = _StopBudget(budget_seconds) waits = False try: @@ -4632,166 +4833,164 @@ async def _stop_steps(self, budget: _StopBudget) -> None: watch_kept = alert_kept + _STOP_WAIT_SHARE_SECONDS + config_kept crl_kept = watch_kept + _STOP_WAIT_SHARE_SECONDS + STOP_FLOOR_SECONDS retention_kept = crl_kept + _STOP_WAIT_SHARE_SECONDS + # Every step below runs under its own guard (BACKLOG #8190); Engine.stop's docstring says + # what the guard holds and the cases that end the stop before the store's close. + steps = _StopSteps() # Quiesce the active-passive graph supervisor FIRST (Workstream A1) so it can't reconcile (and # re-start the graph) while we tear down. A no-op single-node (never spawned). Cooperative: set # the stop event and let any in-flight reconcile finish under the lock (so we never abandon a # half-started graph), falling back to cancel only if a reconcile hangs past the timeout. The # stop budget does not shorten that timeout (BACKLOG #3191). The graph itself is then stopped # by the registry_runner.stop() below, as before. - if self._graph_supervisor is not None: + supervisor = self._graph_supervisor + if supervisor is not None: self._graph_stop.set() # Paired with _graph_stop: the loop now waits on _graph_wake, so without this the # supervisor would sit out its poll interval and be CANCELLED by the wait_for below # rather than exiting cooperatively. self._graph_wake.set() - supervisor = self._graph_supervisor self._graph_supervisor = None - try: - await asyncio.wait_for(supervisor, timeout=_GRAPH_SUPERVISOR_STOP_SECONDS) - except TimeoutError: - # wait_for already cancelled the task on timeout; absorb its cancellation. - await asyncio.gather(supervisor, return_exceptions=True) - retention_cancelled = False + # After the supervisor is told to stop, so the loop turn this may take cannot let it + # begin a reconcile. + await steps.take_a_pending_cancel() + if supervisor is not None: + with steps.step("graph supervisor"): + try: + await asyncio.wait_for(supervisor, timeout=_GRAPH_SUPERVISOR_STOP_SECONDS) + except TimeoutError: + # wait_for already cancelled the task on timeout; absorb its cancellation. + await asyncio.gather(supervisor, return_exceptions=True) if self._retention_runner is not None: retention = self._retention_runner - try: + # BACKLOG #6526: the retention stop passes a cancel of this stop on once its own + # bounded wait ends; the guard holds it until the store has closed, and the graph + # stop still runs, as before BACKLOG #8190. + with steps.step("retention runner", leaves_on_cancel=False): await retention.stop( timeout=budget.wait(retention.stop_timeout_seconds, kept=retention_kept) ) - except asyncio.CancelledError: - # BACKLOG #6526: the retention stop passes a cancel of this stop on once its own - # bounded wait ends. It is held, as the intake monitor's below is, so this stop - # still closes the store, and raised once the store has closed. A cancel that - # lands in a later step before the guarded teardown still leaves at once. - retention_cancelled = True if self._backup_runner is not None: - await self._backup_runner.stop() + with steps.step("backup runner"): + await self._backup_runner.stop() if self._cert_expiry_runner is not None: - await self._cert_expiry_runner.stop() + with steps.step("certificate expiry runner"): + await self._cert_expiry_runner.stop() if self._crl_reload_runner is not None: crl = self._crl_reload_runner - await crl.stop(timeout=budget.wait(crl.stop_timeout_seconds, kept=crl_kept)) - self._crl_reload_runner = None + with steps.step("CRL reload runner"): + await crl.stop(timeout=budget.wait(crl.stop_timeout_seconds, kept=crl_kept)) + self._crl_reload_runner = None if self._log_forward_watch is not None: - await self._log_forward_watch.stop() - self._log_forward_watch = None + with steps.step("log forwarding watch"): + await self._log_forward_watch.stop() + self._log_forward_watch = None if self._secret_rotation_runner is not None: - await self._secret_rotation_runner.stop() + with steps.step("secret rotation runner"): + await self._secret_rotation_runner.stop() if self._update_check_runner is not None: - await self._update_check_runner.stop() + with steps.step("update check runner"): + await self._update_check_runner.stop() # Stop the leader sweep before deregistering membership (it consults the coordinator's gate, so # it must quiesce while the coordinator is still up). A no-op when single-node (never spawned). if self._leader_maintenance is not None: - await self._leader_maintenance.stop() + with steps.step("leader maintenance"): + await self._leader_maintenance.stop() # Stop the config-convergence loop before the coordinator (it polls the coordinator's cached # version). A no-op when single-node (never spawned). if self._config_convergence is not None: - await self._config_convergence.stop() + with steps.step("config convergence"): + await self._config_convergence.stop() # Stop the transform-state convergence loop before the coordinator/pool tear down (it polls the # store). A no-op when single-node (never spawned). (Track B Step 6b.) if self._state_convergence is not None: - await self._state_convergence.stop() - self._state_convergence = None + with steps.step("state convergence"): + await self._state_convergence.stop() + self._state_convergence = None if self._reference_runner is not None: - await self._reference_runner.stop() + with steps.step("reference sync runner"): + await self._reference_runner.stop() if self._registry_runner is not None: - await self._registry_runner.stop() + # Ends the stop here, before the graph stop, in the cases _StopSteps names, so a + # wedged inbound cannot hold it; the store is left open. + steps.leave_before_graph_stop() + # A barrier: a stop that fails or is cancelled raises before the graph's workers are + # cancelled, so its listener may still be live. Nothing below may run then: not the + # gate's release, the GCM settle or the coordinator's deregistration, and not the + # store's close (ADR 0157 Amendment B). + with steps.step("registry runner", barrier=True): + await self._registry_runner.stop() # After the graph, so the listeners are already closed when the monitor opens the gate on its - # way out; stopping it first would let a paused listener read again during shutdown. - # A count, not a flag, as in IntakeBoundMonitor.stop: a cancel of this stop from any step - # below is held until the store has closed, then raised in place of any error. - me = asyncio.current_task() - baseline = me.cancelling() if me is not None else 0 - monitor_cancelled = False + # way out; stopping it first would let a paused listener read again during shutdown. The + # monitor passes a cancel of this stop on once its gate is open (BACKLOG #3269). if self._intake_monitor is not None: monitor, self._intake_monitor = self._intake_monitor, None - try: + with steps.step("intake monitor"): await monitor.stop() - except asyncio.CancelledError: - # The monitor passes a cancel of this stop on once its gate is open (BACKLOG - # #3269). Finish the teardown below first, so the store still drains and closes. - monitor_cancelled = True - # The rest of the teardown is guarded (BACKLOG #3269): the store closes even if a later step - # raises or is cancelled. A pending cancel is raised last, in place of any error a step or the - # close raised, which is then logged. A SystemExit or KeyboardInterrupt is never replaced. - cancelled = monitor_cancelled or retention_cancelled - failure: BaseException | None = None - try: - # Vault BACKLOG #2613: after the graph, so a clear raised here does not say a graph that is - # still serving has gone, and ahead of the alert-state drain, which gives its write a chance. - if self.on_graph_stopped is not None: + # Vault BACKLOG #2613: after the graph, so a clear raised here does not say a graph that is + # still serving has gone, and ahead of the alert-state drain, which gives its write a chance. + if self.on_graph_stopped is not None: + with steps.step("graph-stopped callback"): try: self.on_graph_stopped() except Exception as exc: # noqa: BLE001 - a stop must go on to close the store log.warning("a graph-stopped callback failed: %s", type(exc).__name__) - # Vault BACKLOG #2742: after the graph, so a script refused during the drain is still - # reported by the watch's last pass. That pass may write an audit row and raise an alert, - # so it runs while the store is open, and ahead of the alert-state drain at the end. - if self._remote_debug_watch is not None: + # Vault BACKLOG #2742: after the graph, so a script refused during the drain is still + # reported by the watch's last pass. That pass may write an audit row and raise an alert, + # so it runs while the store is open, and ahead of the alert-state drain at the end. + if self._remote_debug_watch is not None: + with steps.step("remote-debug refusal watch"): await self._remote_debug_watch.stop(deadline=budget.deadline(kept=watch_kept)) self._remote_debug_watch = None - # Settle the GCM invocation bound only AFTER the message graph has quiesced. stop() spends the - # unused remainder of this process's reserved block and unhooks the refill signal, so anything - # that encrypts after it runs is charged against no reservation with no checkpointer left to - # refill one. The registry runner is what drives those encrypts, so settling ahead of it would - # silently under-count every write performed during the shutdown drain. - if self._gcm_invocation_runner is not None: + # Settle the GCM invocation bound only AFTER the message graph has quiesced. stop() spends the + # unused remainder of this process's reserved block and unhooks the refill signal, so anything + # that encrypts after it runs is charged against no reservation with no checkpointer left to + # refill one. The registry runner is what drives those encrypts, so settling ahead of it would + # silently under-count every write performed during the shutdown drain. + if self._gcm_invocation_runner is not None: + with steps.step("GCM invocation runner"): await self._gcm_invocation_runner.stop() self._gcm_invocation_runner = None + with steps.step("cipher refusal alert"): self._disarm_cipher_refusal_alert() + with steps.step("seal page"): self._disarm_seal_page() - # Deregister cluster membership after the runner has quiesced but before the store closes (the - # coordinator marks its node left over the same pool). stop() is idempotent and safe even if - # start() raised (then there's just nothing to cancel). NullCoordinator is a no-op. - # ADR 0157 Inc 5: drop the edge-trigger BEFORE stopping the coordinator, so a clean - # step-down cannot fire a wake into a supervisor that is already gone. + # Deregister cluster membership after the runner has quiesced but before the store closes (the + # coordinator marks its node left over the same pool). stop() is idempotent and safe even if + # start() raised (then there's just nothing to cancel). NullCoordinator is a no-op. + # ADR 0157 Inc 5: drop the edge-trigger BEFORE stopping the coordinator, so a clean + # step-down cannot fire a wake into a supervisor that is already gone. + with steps.step("coordinator demote hook"): if isinstance(self._coordinator, _SupportsDemoteHook): self._coordinator.set_on_demote(None) + with steps.step("coordinator"): await self._coordinator.stop() - # Cancel the background pool warm-up if still running (best-effort; the store is about to close). - # It releases any connections it holds in its own finally, but at shutdown the pool closes anyway. - if self._warm_pool_task is not None: + # Cancel the background pool warm-up if still running (best-effort; the store is about to close). + # It releases any connections it holds in its own finally, but at shutdown the pool closes anyway. + if self._warm_pool_task is not None: + with steps.step("pool warm-up"): self._warm_pool_task.cancel() await asyncio.gather(self._warm_pool_task, return_exceptions=True) self._warm_pool_task = None - # A config write whose caller was cancelled is still running, and its row needs the store - # (BACKLOG #2623). Under the managed API lifespan a drain has already run, bounded by its - # shutdown budget (BACKLOG #3191), and closed the gate. A write it left running gets only - # the short late wait here, inside this step's reserve; with none running it costs nothing. - # A caller whose shutdown ran no drain gets the fixed bound. + # A config write whose caller was cancelled is still running, and its row needs the store + # (BACKLOG #2623). Under the managed API lifespan a drain has already run, bounded by its + # shutdown budget (BACKLOG #3191), and closed the gate. A write it left running gets only + # the short late wait here, inside this step's reserve; with none running it costs nothing. + # A caller whose shutdown ran no drain gets the fixed bound. + with steps.step("config write drain"): await self.drain_config_writes( _CONFIG_WRITE_LATE_DRAIN_SECONDS if self._config_writes_closed else _CONFIG_WRITE_DRAIN_SECONDS ) - # Clears raised on the way out are background writes: an unpinned cluster node's intake - # alerts (BACKLOG #2272) and the coordinator's leadership release. Give them a bounded chance - # to land before the store closes. Last, so it covers every stop step above. + # Clears raised on the way out are background writes: an unpinned cluster node's intake + # alerts (BACKLOG #2272) and the coordinator's leadership release. Give them a bounded chance + # to land before the store closes. Last, so it covers every stop step above. + # The lookup runs the sink's own code, so it is inside the step. + with steps.step("alert-state drain"): drain = getattr(self._alert_sink, "drain_state", None) if drain is not None: await drain(budget.wait(_ALERT_STATE_DRAIN_SECONDS, kept=alert_kept)) - except asyncio.CancelledError: - cancelled = True - except BaseException as exc: # noqa: BLE001 - held until the store closes, then re-raised - failure = exc self._store_close_reached = True # stop() releases the Transit pool lease from here on - try: + with steps.step("store close"): await self.store.close() - except Exception as exc: - if failure is None: - failure = exc - else: - log.exception("the store close failed after an engine stop step failed") - cancelled = cancelled or (me is not None and me.cancelling() > baseline) - if failure is not None and not isinstance(failure, Exception): - raise failure # SystemExit, KeyboardInterrupt: never swallowed by a cancel - if cancelled: - if failure is not None: - # The cancel replaces this error, so it is logged here or not at all. - log.error( - "an engine stop step or the store close failed after the stop was cancelled", - exc_info=failure, - ) - raise asyncio.CancelledError - if failure is not None: - raise failure + steps.finish() diff --git a/messagefoundry/pipeline/remote_debug_watch.py b/messagefoundry/pipeline/remote_debug_watch.py index c34c051402..be46b0a06c 100644 --- a/messagefoundry/pipeline/remote_debug_watch.py +++ b/messagefoundry/pipeline/remote_debug_watch.py @@ -183,7 +183,7 @@ def _bound(kept: float) -> float: if task is None: return # ``wait``, not ``wait_for``: a loop task that something else cancelled must not make - # this call look cancelled, which would end the engine's stop before it closed the store. + # this call look cancelled, which the engine's stop would hold as a failed step. try: wait = _bound(STOP_FLOOR_SECONDS) done, _pending = await asyncio.wait({task}, timeout=wait) diff --git a/tests/test_3929_transit_bulk_pool.py b/tests/test_3929_transit_bulk_pool.py index 5ee2b3318d..b9888102ca 100644 --- a/tests/test_3929_transit_bulk_pool.py +++ b/tests/test_3929_transit_bulk_pool.py @@ -418,11 +418,20 @@ async def test_a_queued_call_is_cancelled_at_shutdown_and_never_runs() -> None: assert ran == [] +async def _cancel_this_stop() -> None: + """A cancel of the stopping task itself. A bare ``raise CancelledError`` with no cancel of the + task is a leaked cancel, which Engine.stop reads as a step failure (BACKLOG #8190).""" + task = asyncio.current_task() + assert task is not None + task.cancel() + await asyncio.sleep(0) + + class _CancelledDrain: """An alert sink whose state drain is cancelled, so the stop runs on as a cancelled stop.""" async def drain_state(self, timeout: float) -> None: - raise asyncio.CancelledError + await _cancel_this_stop() async def test_a_cancelled_stop_logs_no_still_running_warning( @@ -451,6 +460,8 @@ async def test_the_lease_is_released_when_the_store_close_raises( async def close() -> None: await real_close() + if raised is asyncio.CancelledError: + await _cancel_this_stop() raise raised monkeypatch.setattr(eng.store, "close", close) @@ -524,7 +535,7 @@ def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: assert await asyncio.wait_for(shutdown_transit_pools(None), 3.0) is False -class _FailingBackupRunner: +class _FailingStop: async def stop(self) -> None: raise RuntimeError("synthetic stop step failure") @@ -533,20 +544,36 @@ async def test_a_stop_that_raises_before_the_close_keeps_the_lease( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: """Item 1: a stop that raises before it reaches the store's close keeps the lease, since the - store and the graph may still use the pools; a later stop that reaches the close releases it.""" + store and the graph may still use the pools; a later stop that reaches the close releases it. + Since BACKLOG #8190 the cases that end the stop before the close include at least a failed + graph stop, the one this test builds; Engine.stop's docstring lists the others.""" monkeypatch.setattr(row_seal, "_leases", 0) eng = await _engine(tmp_path / "e.db") pool = row_seal._transit_pool() - eng._backup_runner = _FailingBackupRunner() + eng._registry_runner = _FailingStop() with pytest.raises(RuntimeError, match="synthetic stop step failure"): await eng.stop() assert row_seal._leases == 1 assert row_seal._transit_pool() is pool, "the early raise detached pools still in use" - eng._backup_runner = None + eng._registry_runner = None await eng.stop() assert row_seal._leases == 0 +async def test_a_failed_step_before_the_graph_stop_still_releases_the_lease( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """BACKLOG #8190: a step that fails without leaving the graph live no longer ends the stop, + so the store closes and the lease is released.""" + monkeypatch.setattr(row_seal, "_leases", 0) + eng = await _engine(tmp_path / "b.db") + row_seal._transit_pool() + eng._backup_runner = _FailingStop() + with pytest.raises(RuntimeError, match="synthetic stop step failure"): + await eng.stop() + assert row_seal._leases == 0 + + async def test_an_engine_constructor_that_raises_takes_no_lease( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_engine_stop_budget.py b/tests/test_engine_stop_budget.py index 41120286e2..26e7d860b6 100644 --- a/tests/test_engine_stop_budget.py +++ b/tests/test_engine_stop_budget.py @@ -379,12 +379,14 @@ async def test_a_cancel_during_the_crl_runner_first_wait_propagates_as_on_main( await asyncio.gather(pass_task, return_exceptions=True) -async def test_a_cancel_of_engine_stop_during_the_crl_first_wait_leaves_as_on_main( +async def test_a_cancel_of_engine_stop_during_the_crl_first_wait_still_closes_the_store( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """As on main, the CRL stop comes before engine.stop()'s guarded teardown, so a cancel there - leaves engine.stop() at once and the store is not closed (measured on main 72ac872c9cd). This - pins main's behaviour, which this PR keeps; it is not a property to preserve.""" + """The CRL stop cancels its pass and passes the cancel on, as on main. engine.stop() holds that + cancel, closes the store, then raises it: every stop step is guarded (BACKLOG #8190). Before + that, a cancel here left engine.stop() at once with the store still open. With a registry + runner wired, which this test has not, it still ends the stop before the graph stop and + leaves the store open.""" eng = await _engine(tmp_path) runner = CrlReloadRunner(stop_timeout_seconds=30.0) pass_task = asyncio.ensure_future(_hangs()) @@ -407,7 +409,7 @@ async def _close() -> None: await stopping await asyncio.sleep(0) assert pass_task.cancelled() - assert closed == [] + assert closed == [True] finally: pass_task.cancel() await asyncio.gather(pass_task, return_exceptions=True) diff --git a/tests/test_engine_stop_steps.py b/tests/test_engine_stop_steps.py new file mode 100644 index 0000000000..4f14cf2a87 --- /dev/null +++ b/tests/test_engine_stop_steps.py @@ -0,0 +1,760 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""BACKLOG #8190: every Engine.stop step runs under its own guard. + +An ordinary error from a step other than the graph stop, or a cancel a step swallows, must not by +itself skip the later steps or the store's close. A failed or cancelled graph stop skips both. With +a graph, a cancel an early step lets out, and a SystemExit or KeyboardInterrupt from an early step, +end the stop where the graph stop would begin, leaving the store open. A CancelledError a step +leaked from a task of its own must not read as a cancel of the stop. +""" + +from __future__ import annotations + +import asyncio +import contextlib +import logging +from pathlib import Path +from typing import Any + +import pytest + +from messagefoundry.config.settings import EgressSettings +from messagefoundry.config.wiring import Registry +from messagefoundry.pipeline import engine as engine_module +from messagefoundry.pipeline.engine import Engine +from messagefoundry.pipeline.wiring_runner import RegistryRunner + +#: How long a test waits on a stop that must end promptly, so a hang fails the test, not the run. +_PROMPT_SECONDS = 5.0 + + +class _Step: + """A stand-in runner whose stop records that it ran, then does what it was told to.""" + + def __init__(self, ran: list[str], name: str, outcome: BaseException | None = None) -> None: + self._ran, self._name, self._outcome = ran, name, outcome + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + if self._outcome is not None: + raise self._outcome + + +async def _leak_a_child_cancel() -> None: + """Cancel a child task of our own and let its CancelledError out; nobody cancelled us.""" + child = asyncio.ensure_future(asyncio.Event().wait()) + await asyncio.sleep(0) + child.cancel() + await child + + +class _LeaksAChildCancel(_Step): + """A stop whose own child task was cancelled, and which lets that CancelledError out.""" + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + await _leak_a_child_cancel() + + +class _Hangs(_Step): + """A stop that waits until the stop is cancelled.""" + + def __init__(self, ran: list[str], name: str, entered: asyncio.Event) -> None: + super().__init__(ran, name) + self._entered = entered + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + self._entered.set() + await asyncio.Event().wait() + + +async def _engine(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Engine, list[bool]]: + eng = await Engine.create( + tmp_path / "stop.db", egress_settings=EgressSettings(deny_by_default=False) + ) + closed: list[bool] = [] + real_close = eng.store.close + + async def _close() -> None: + closed.append(True) + await real_close() + + monkeypatch.setattr(eng.store, "close", _close) + return eng, closed + + +async def _close_if_left_open(eng: Engine, closed: list[bool]) -> None: + """A failing test, or a stop that ended before the close, must not leave the store's worker + thread holding the process open, or the engine's Transit pool lease raised.""" + if not closed: + await eng.store.close() + await eng.release_transit_pools(0.0) + + +def _wire(eng: Engine, first: _Step, ran: list[str]) -> None: + """``first`` as the backup runner, the earliest step a test can stand in for without the + graph, then recorders at a middle step and at the intake monitor.""" + eng._backup_runner = first # type: ignore[assignment] + eng._update_check_runner = _Step(ran, "update check") # type: ignore[assignment] + eng._intake_monitor = _Step(ran, "intake monitor") # type: ignore[assignment] + + +async def test_an_early_step_that_raises_does_not_skip_the_later_steps_or_the_close( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", RuntimeError("synthetic backup stop fault")), ran) + try: + with pytest.raises(RuntimeError, match="synthetic backup stop fault"): + await eng.stop() + assert ran == ["backup", "update check", "intake monitor"] + assert closed == [True] + finally: + await _close_if_left_open(eng, closed) + + +async def test_an_intake_monitor_stop_that_raises_still_closes_the_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The monitor's stop was guarded only against a cancel, so any other error skipped the + alert-state drain and the store's close.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + eng._intake_monitor = _Step(ran, "intake monitor", ValueError("synthetic monitor fault")) # type: ignore[assignment] + drained: list[float] = [] + + class _Sink: + async def drain_state(self, timeout: float) -> None: + drained.append(timeout) + + eng._alert_sink = _Sink() # type: ignore[assignment] + try: + with pytest.raises(ValueError, match="synthetic monitor fault"): + await eng.stop() + assert ran == ["intake monitor"] + assert len(drained) == 1, "the alert-state drain still ran" + assert closed == [True] + finally: + await _close_if_left_open(eng, closed) + + +async def test_a_cancel_of_the_stop_in_an_early_step_still_closes_the_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The cancel is held while the later steps and the close run, then raised.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + entered = asyncio.Event() + _wire(eng, _Hangs(ran, "backup", entered), ran) + stopping = asyncio.ensure_future(eng.stop()) + try: + await asyncio.wait_for(entered.wait(), 10) + stopping.cancel("the caller's own cancel") + with pytest.raises(asyncio.CancelledError, match="the caller's own cancel"): + await stopping + assert ran == ["backup", "update check", "intake monitor"] + assert closed == [True] + finally: + await _close_if_left_open(eng, closed) + + +@pytest.mark.parametrize("where", ["early", "monitor", "late"]) +async def test_a_cancel_a_step_leaked_from_its_own_child_is_not_a_cancel_of_the_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, where: str +) -> None: + """Nobody cancelled the stop, so it must not end in CancelledError: its caller would read + that as its own cancel. It is a step failure, raised once the store has closed.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup"), ran) + if where == "early": + eng._backup_runner = _LeaksAChildCancel(ran, "backup") # type: ignore[assignment] + elif where == "monitor": + eng._intake_monitor = _LeaksAChildCancel(ran, "intake monitor") # type: ignore[assignment] + else: + + async def _leaks(_timeout: float) -> None: + ran.append("config write drain") + await _leak_a_child_cancel() + + monkeypatch.setattr(eng, "drain_config_writes", _leaks) + try: + with pytest.raises(RuntimeError, match="ended cancelled") as raised: + await eng.stop() + assert isinstance(raised.value.__cause__, asyncio.CancelledError) + assert closed == [True] + assert "intake monitor" in ran, "the steps after the leak still ran" + task = asyncio.current_task() + assert task is not None and task.cancelling() == 0 + finally: + await _close_if_left_open(eng, closed) + + +async def test_the_first_failure_is_raised_and_a_later_one_is_logged( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", RuntimeError("first fault")), ran) + eng._update_check_runner = _Step(ran, "update check", RuntimeError("second fault")) # type: ignore[assignment] + try: + with ( + caplog.at_level(logging.ERROR, logger=engine_module.__name__), + pytest.raises(RuntimeError, match="first fault"), + ): + await eng.stop() + assert closed == [True] + later = [r for r in caplog.records if "raised in its place" in r.getMessage()] + assert len(later) == 1 + assert "second fault" in later[0].getMessage() + assert "'update check runner'" in later[0].getMessage(), "the step that raised it" + finally: + await _close_if_left_open(eng, closed) + + +async def test_an_exit_after_an_ordinary_failure_is_what_the_stop_raises( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """A SystemExit or KeyboardInterrupt is never dropped for an earlier ordinary error.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", RuntimeError("first fault")), ran) + eng._update_check_runner = _Step(ran, "update check", SystemExit(3)) # type: ignore[assignment] + try: + with ( + caplog.at_level(logging.ERROR, logger=engine_module.__name__), + pytest.raises(SystemExit), + ): + await eng.stop() + assert closed == [True] + [logged] = [r for r in caplog.records if "raised in its place" in r.getMessage()] + assert "first fault" in logged.getMessage() + assert "'backup runner'" in logged.getMessage(), "named by the step that raised it" + finally: + await _close_if_left_open(eng, closed) + + +@pytest.mark.parametrize("how", ["raises", "cancelled"]) +async def test_a_failed_graph_stop_ends_the_stop_before_the_later_steps_and_the_close( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, how: str +) -> None: + """The registry runner's stop raises before it cancels the drain side, so its listener may + still be live (ADR 0157 Amendment B). The gate's release, the coordinator's deregistration and + the store's close must not run under it. A step before it that failed still let it run.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", ValueError("early fault")), ran) + if how == "raises": + eng._registry_runner = _Step(ran, "registry", RuntimeError("graph stop fault")) # type: ignore[assignment] + stopping = asyncio.ensure_future(eng.stop()) + else: + entered = asyncio.Event() + eng._registry_runner = _Hangs(ran, "registry", entered) # type: ignore[assignment] + stopping = asyncio.ensure_future(eng.stop()) + await asyncio.wait_for(entered.wait(), 10) + stopping.cancel() + try: + # The graph stop's own failure is what the stop raises: the earlier one is only logged. + expected: type[BaseException] = RuntimeError if how == "raises" else asyncio.CancelledError + with pytest.raises(expected): + await stopping + assert ran == ["backup", "update check", "registry"] + assert closed == [] + assert not eng._store_close_reached + finally: + await _close_if_left_open(eng, closed) + + +async def test_a_cancel_the_caller_took_before_the_stop_is_not_raised_by_it( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A caller that caught its own cancel and goes on to stop the engine must not have the stop + raise that cancel again: the count is read at the stop's entry.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup"), ran) + + async def _caller() -> None: + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + await eng.stop() + + caller = asyncio.ensure_future(_caller()) + try: + await asyncio.sleep(0) + caller.cancel() + await caller # the stop returned, so the caller ended normally + assert closed == [True] + assert ran == ["backup", "update check", "intake monitor"] + finally: + await _close_if_left_open(eng, closed) + + +async def test_a_stop_coroutine_closed_mid_step_runs_no_further_step( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """A stop coroutine closed while suspended in a step (GeneratorExit) is not kept running by the + guard, and the failure it held is logged rather than lost.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", RuntimeError("held fault")), ran) + eng._update_check_runner = _Hangs(ran, "update check", asyncio.Event()) # type: ignore[assignment] + stop = eng.stop() + try: + stop.send(None) # runs until the update check suspends + with caplog.at_level(logging.ERROR, logger=engine_module.__name__): + stop.close() + assert ran == ["backup", "update check"] + assert closed == [] + assert any( + "held fault" in r.getMessage() and "is dropped" in r.getMessage() + for r in caplog.records + ) + finally: + await _close_if_left_open(eng, closed) + + +class _Source: + """An inbound whose stop records that it ran, then returns, or with ``wedged`` never returns + until it is cancelled.""" + + def __init__(self, ran: list[str], *, wedged: bool) -> None: + self._ran, self._wedged = ran, wedged + + async def stop(self) -> None: + self._ran.append("inbound stop") + if self._wedged: + await asyncio.Event().wait() + + +def _registry_runner(ran: list[str], *, wedged: bool) -> RegistryRunner: + """A real registry runner holding one inbound, so its stop is the graph stop main ran.""" + runner = RegistryRunner(Registry(), store=None, egress=EgressSettings(deny_by_default=False)) # type: ignore[arg-type] + runner._sources["IB_SYNTH"] = _Source(ran, wedged=wedged) # type: ignore[assignment] + return runner + + +async def test_a_cancel_taken_in_an_early_step_does_not_wait_on_a_wedged_graph_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """origin/main left at once on a cancel in an early step. Held, it must not begin the graph + stop, where a wedged inbound would hold it: the stop raises the cancel there, and the store + is left open, as main left it.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + entered = asyncio.Event() + _wire(eng, _Hangs(ran, "backup", entered), ran) + eng._registry_runner = _registry_runner(ran, wedged=True) + stopping = asyncio.ensure_future(eng.stop()) + try: + await asyncio.wait_for(entered.wait(), _PROMPT_SECONDS) + stopping.cancel("the caller's own cancel") + with pytest.raises(asyncio.CancelledError, match="the caller's own cancel"): + await asyncio.wait_for(stopping, _PROMPT_SECONDS) + assert ran == ["backup", "update check"], "the graph stop did not begin" + assert closed == [] + assert not eng._store_close_reached + finally: + if not stopping.done(): + stopping.cancel() + await asyncio.gather(stopping, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +class _SwallowsTheCancel(_Step): + """A stop shaped like the engine's runner stops: it awaits its own work and catches the + CancelledError of that await, so a cancel of the stop delivered there never leaves it.""" + + def __init__(self, ran: list[str], name: str, entered: asyncio.Event) -> None: + super().__init__(ran, name) + self._entered = entered + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + self._entered.set() + with contextlib.suppress(asyncio.CancelledError): + await asyncio.Event().wait() + + +async def test_a_cancel_an_early_step_swallowed_still_runs_the_graph_stop_and_closes_the_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The engine's runner stops swallow the cancel of their own await. origin/main then ran the + graph stop and closed the store, and so must the guard: the cancel, which the count still + shows, is raised once the close has run. With a wedged inbound the graph stop then waits, as + on main.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + entered = asyncio.Event() + _wire(eng, _SwallowsTheCancel(ran, "backup", entered), ran) + eng._registry_runner = _registry_runner(ran, wedged=False) + stopping = asyncio.ensure_future(eng.stop()) + try: + await asyncio.wait_for(entered.wait(), _PROMPT_SECONDS) + stopping.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(stopping, _PROMPT_SECONDS) + assert ran == ["backup", "update check", "inbound stop", "intake monitor"] + assert closed == [True] + finally: + if not stopping.done(): + stopping.cancel() + await asyncio.gather(stopping, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +class _RetentionStep(_Step): + stop_timeout_seconds = 5.0 + + +class _RetentionSwallows(_SwallowsTheCancel): + stop_timeout_seconds = 5.0 + + +async def test_a_cancel_the_retention_stop_swallowed_still_runs_the_graph_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A cancel the retention stop took, even one it swallowed, lets the graph stop and the close + run; the early step after it does not read it again as its own.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + entered = asyncio.Event() + eng._retention_runner = _RetentionSwallows(ran, "retention", entered) # type: ignore[assignment] + _wire(eng, _Step(ran, "backup"), ran) + eng._registry_runner = _registry_runner(ran, wedged=False) + stopping = asyncio.ensure_future(eng.stop()) + try: + await asyncio.wait_for(entered.wait(), _PROMPT_SECONDS) + stopping.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(stopping, _PROMPT_SECONDS) + assert ran == ["retention", "backup", "update check", "inbound stop", "intake monitor"] + assert closed == [True] + finally: + if not stopping.done(): + stopping.cancel() + await asyncio.gather(stopping, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +async def test_a_cancel_requested_before_the_stop_with_only_a_wedged_graph( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """With no step before the graph stop, a cancel requested before stop() would be the graph + stop's to take: the stop raises it where that stop would begin, without beginning it.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + eng._registry_runner = _registry_runner(ran, wedged=True) + + async def _caller() -> None: + task = asyncio.current_task() + assert task is not None + task.cancel("requested before the stop") + await eng.stop() + + caller = asyncio.ensure_future(_caller()) + try: + with pytest.raises(asyncio.CancelledError, match="requested before the stop"): + await asyncio.wait_for(caller, _PROMPT_SECONDS) + assert ran == [] + assert closed == [] + finally: + if not caller.done(): + caller.cancel() + await asyncio.gather(caller, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +@pytest.mark.parametrize("first", ["backup", "retention"]) +async def test_a_cancel_requested_before_the_stop_with_a_graph( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, first: str +) -> None: + """A cancel requested before stop() counts against the first step that runs, where it would + otherwise have been delivered: before the graph stop it ends the stop there, with the store + left open, unless that step is the retention stop, whose cancel lets the graph stop and the + close run.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup"), ran) + if first == "retention": + eng._retention_runner = _RetentionStep(ran, "retention") # type: ignore[assignment] + eng._registry_runner = _registry_runner(ran, wedged=first == "backup") + + async def _caller() -> None: + task = asyncio.current_task() + assert task is not None + task.cancel("requested before the stop") + await eng.stop() + + caller = asyncio.ensure_future(_caller()) + try: + with pytest.raises(asyncio.CancelledError, match="requested before the stop"): + await asyncio.wait_for(caller, _PROMPT_SECONDS) + if first == "backup": + assert ran == ["backup", "update check"] + assert closed == [] + else: + assert ran == ["retention", "backup", "update check", "inbound stop", "intake monitor"] + assert closed == [True] + finally: + if not caller.done(): + caller.cancel() + await asyncio.gather(caller, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +async def test_an_uncancelled_early_failure_still_runs_the_graph_stop_and_closes_the_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The control for the test above: an early step's ordinary failure is held, and the graph + stop and the store's close still run before it is raised.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", RuntimeError("synthetic backup stop fault")), ran) + eng._registry_runner = _registry_runner(ran, wedged=False) + try: + with pytest.raises(RuntimeError, match="synthetic backup stop fault"): + await asyncio.wait_for(eng.stop(), _PROMPT_SECONDS) + assert ran == ["backup", "update check", "inbound stop", "intake monitor"] + assert closed == [True] + finally: + await _close_if_left_open(eng, closed) + + +@pytest.mark.parametrize("first", ["backup", "retention"]) +@pytest.mark.parametrize("exit_exc", [SystemExit, KeyboardInterrupt]) +async def test_an_exit_from_an_early_step_does_not_wait_on_a_wedged_graph_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, first: str, exit_exc: type[BaseException] +) -> None: + """origin/main raised a SystemExit or KeyboardInterrupt from an early step at once. Held, it + must not begin the graph stop, where a wedged inbound would hold the stop without end: the + stop raises it where that stop would begin, and the store is left open, as main left it.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", exit_exc() if first == "backup" else None), ran) + if first == "retention": + eng._retention_runner = _RetentionStep(ran, "retention", exit_exc()) # type: ignore[assignment] + eng._registry_runner = _registry_runner(ran, wedged=True) + try: + with pytest.raises(exit_exc): + await asyncio.wait_for(eng.stop(), _PROMPT_SECONDS) + assert "inbound stop" not in ran, "the graph stop did not begin" + assert ran[-1] == "update check" + assert closed == [] + assert not eng._store_close_reached + finally: + await _close_if_left_open(eng, closed) + + +class _WaitsForRelease(_Step): + """A stop that says it began, then waits until the test releases it.""" + + def __init__(self, ran: list[str], name: str) -> None: + super().__init__(ran, name) + self.entered, self.release = asyncio.Event(), asyncio.Event() + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + self.entered.set() + await self.release.wait() + + +async def test_the_first_failed_step_is_logged_when_it_happens( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + """The first failure is raised only once every step has run, so a service killed in a later + step would lose it unless it is logged when it happens, with its traceback.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _Step(ran, "backup", RuntimeError("first fault")), ran) + later = _WaitsForRelease(ran, "update check") + eng._update_check_runner = later # type: ignore[assignment] + stopping = asyncio.ensure_future(eng.stop()) + try: + with caplog.at_level(logging.ERROR, logger=engine_module.__name__): + await asyncio.wait_for(later.entered.wait(), _PROMPT_SECONDS) + [logged] = [r for r in caplog.records if "first fault" in r.getMessage()] + assert "'backup runner'" in logged.getMessage() + assert logged.exc_info is not None, "logged with its traceback" + assert isinstance(logged.exc_info[1], RuntimeError) + later.release.set() + with pytest.raises(RuntimeError, match="first fault"): + await asyncio.wait_for(stopping, _PROMPT_SECONDS) + assert closed == [True] + finally: + if not stopping.done(): + stopping.cancel() + await asyncio.gather(stopping, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +class _HangingRetention(_Hangs): + """A retention runner stand-in: its stop waits until the stop is cancelled.""" + + stop_timeout_seconds = 5.0 + + +async def test_a_cancel_held_by_the_retention_stop_still_runs_the_graph_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """origin/main held a cancel taken in the retention stop (BACKLOG #6526) and went on to the + graph stop and the store's close, so that case keeps main's behaviour.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + entered = asyncio.Event() + eng._retention_runner = _HangingRetention(ran, "retention", entered) # type: ignore[assignment] + eng._intake_monitor = _Step(ran, "intake monitor") # type: ignore[assignment] + eng._registry_runner = _registry_runner(ran, wedged=False) + stopping = asyncio.ensure_future(eng.stop()) + try: + await asyncio.wait_for(entered.wait(), _PROMPT_SECONDS) + stopping.cancel("the caller's own cancel") + with pytest.raises(asyncio.CancelledError, match="the caller's own cancel"): + await asyncio.wait_for(stopping, _PROMPT_SECONDS) + assert ran == ["retention", "inbound stop", "intake monitor"] + assert closed == [True] + finally: + if not stopping.done(): + stopping.cancel() + await asyncio.gather(stopping, return_exceptions=True) + await _close_if_left_open(eng, closed) + + +class _SuspendsOnce(_Step): + """A stop that suspends once. A CancelledError delivered there is let out, or with + ``swallows`` caught and dropped, as a stop that catches it without uncancel() does.""" + + def __init__(self, ran: list[str], name: str, *, swallows: bool) -> None: + super().__init__(ran, name) + self._swallows = swallows + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + try: + await asyncio.sleep(0) + except asyncio.CancelledError: + if not self._swallows: + raise + + +class _RequestsACancelOfTheStop(_Step): + """A stop that requests a cancel of the stopping task and returns without suspending, so + the cancel is requested in this step and delivered in a later one.""" + + async def stop(self, **_kwargs: Any) -> None: + self._ran.append(self._name) + task = asyncio.current_task() + assert task is not None + task.cancel("requested during the stop") + + +@pytest.mark.parametrize("swallows", [False, True], ids=["let_out", "swallowed"]) +async def test_a_cancel_requested_before_the_stop_is_raised_by_the_stop( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + swallows: bool, +) -> None: + """A cancel requested before stop() and not yet delivered is a cancel of the stop: not a + failed step, and not lost to a step that would swallow it. The store still closes first.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _SuspendsOnce(ran, "backup", swallows=swallows), ran) + + async def _caller() -> None: + task = asyncio.current_task() + assert task is not None + task.cancel("requested before the stop") + await eng.stop() + + caller = asyncio.ensure_future(_caller()) + try: + with ( + caplog.at_level(logging.ERROR, logger=engine_module.__name__), + pytest.raises(asyncio.CancelledError, match="requested before the stop"), + ): + await asyncio.wait_for(caller, _PROMPT_SECONDS) + assert ran == ["backup", "update check", "intake monitor"] + assert closed == [True] + assert not caplog.records, "the cancel was not taken for a failed step" + finally: + await _close_if_left_open(eng, closed) + + +@pytest.mark.parametrize("swallows", [False, True], ids=["let_out", "swallowed"]) +async def test_a_cancel_requested_during_the_stop_is_raised_by_the_stop( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + swallows: bool, +) -> None: + """A cancel requested in one step and delivered in a later one is still the stop's: not a + failed step, and not lost to a step that swallows it. The store still closes first.""" + eng, closed = await _engine(tmp_path, monkeypatch) + ran: list[str] = [] + _wire(eng, _RequestsACancelOfTheStop(ran, "backup"), ran) + eng._update_check_runner = _SuspendsOnce(ran, "update check", swallows=swallows) # type: ignore[assignment] + stopping = asyncio.ensure_future(eng.stop()) + try: + with ( + caplog.at_level(logging.ERROR, logger=engine_module.__name__), + pytest.raises(asyncio.CancelledError) as raised, + ): + await asyncio.wait_for(stopping, _PROMPT_SECONDS) + if not swallows: + assert "requested during the stop" in str(raised.value) + assert ran == ["backup", "update check", "intake monitor"] + assert closed == [True] + assert not caplog.records, "the cancel was not taken for a failed step" + finally: + await _close_if_left_open(eng, closed) + + +async def test_an_alert_sink_whose_drain_lookup_raises_still_closes_the_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Looking up the sink's drain runs the sink's own code, so it is guarded as a step is.""" + eng, closed = await _engine(tmp_path, monkeypatch) + + class _Sink: + @property + def drain_state(self) -> Any: + raise RuntimeError("synthetic drain lookup fault") + + eng._alert_sink = _Sink() # type: ignore[assignment] + try: + with pytest.raises(RuntimeError, match="synthetic drain lookup fault"): + await eng.stop() + assert closed == [True] + finally: + await _close_if_left_open(eng, closed) + + +async def test_a_coordinator_whose_demote_hook_check_raises_still_closes_the_store( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The isinstance check against the demote-hook Protocol reads the coordinator's own class, + so it is guarded as a step is: the coordinator still stops and the store still closes.""" + eng, closed = await _engine(tmp_path, monkeypatch) + stopped: list[bool] = [] + + class _Coordinator: + @property # type: ignore[misc] + def __class__(self) -> type: + raise RuntimeError("synthetic demote hook check fault") + + async def stop(self) -> None: + stopped.append(True) + + eng._coordinator = _Coordinator() # type: ignore[assignment] + try: + with pytest.raises(RuntimeError, match="synthetic demote hook check fault"): + await eng.stop() + assert stopped == [True] + assert closed == [True] + finally: + await _close_if_left_open(eng, closed) diff --git a/tests/test_intake_alert_expiry.py b/tests/test_intake_alert_expiry.py index db8ce3daa9..e4dd80df54 100644 --- a/tests/test_intake_alert_expiry.py +++ b/tests/test_intake_alert_expiry.py @@ -46,6 +46,16 @@ async def _is_open(store: MessageStore, subject: str) -> bool: return bool(rows) +async def _cancel_this_stop() -> None: + """What the monitor passing a cancel of Engine.stop on looks like: the stopping task is itself + cancelled. A bare ``raise CancelledError`` with no cancel of the task is a leak, which + Engine.stop reads as a step failure (BACKLOG #8190).""" + task = asyncio.current_task() + assert task is not None + task.cancel() + await asyncio.sleep(0) + + def _sweeper(store: MessageStore, node: str | None) -> IntakeBoundMonitor: """A live process's monitor: its own depth is fine, and it sweeps the shared store.""" return IntakeBoundMonitor( @@ -421,7 +431,7 @@ async def test_a_cancel_passed_on_by_the_monitor_still_lets_the_engine_close_the class _CancelledStop: async def stop(self) -> None: await real_monitor.stop() - raise asyncio.CancelledError + await _cancel_this_stop() engine._intake_monitor = cast(IntakeBoundMonitor, _CancelledStop()) closed: list[bool] = [] @@ -461,7 +471,7 @@ class _MaybeCancelledStop: async def stop(self) -> None: await real_monitor.stop() if monitor_cancels: - raise asyncio.CancelledError + await _cancel_this_stop() engine._intake_monitor = cast(IntakeBoundMonitor, _MaybeCancelledStop()) real_drain = engine.drain_config_writes @@ -486,8 +496,10 @@ async def close() -> None: ): await engine.stop() assert closed == [True], "the store closed although a later teardown step raised" - logged = any("failed after the stop was cancelled" in r.getMessage() for r in caplog.records) - assert logged is monitor_cancels, "the error the cancel replaces is logged, and only then" + logged = any( + "the stop's cancel is raised in its place" in r.getMessage() for r in caplog.records + ) + assert logged is monitor_cancels, "the error is logged as replaced by the cancel only then" async def test_one_failed_read_costs_a_watch_only_that_gap( @@ -547,7 +559,7 @@ async def test_a_store_close_that_raises_does_not_replace_the_deferred_cancel( class _CancelledStop: async def stop(self) -> None: await real_monitor.stop() - raise asyncio.CancelledError + await _cancel_this_stop() engine._intake_monitor = cast(IntakeBoundMonitor, _CancelledStop()) real_close = engine.store.close @@ -563,7 +575,8 @@ async def failing_close() -> None: ): await engine.stop() assert any( - "store close failed after the stop was cancelled" in r.getMessage() for r in caplog.records + "step 'store close' failed; the stop's cancel is raised in its place" in r.getMessage() + for r in caplog.records ), "the close error the cancel replaces is logged" @@ -681,7 +694,9 @@ async def test_engine_stop_keeps_the_right_exception_when_the_close_also_raises( async def drain(timeout: float) -> None: await real_drain(timeout) - if step_raises is not None: + if step_raises is asyncio.CancelledError: + await _cancel_this_stop() + elif step_raises is not None: raise step_raises monkeypatch.setattr(engine, "drain_config_writes", drain)