From 39f0eb995bd2eb720d7d0c641012e00d02d2ad04 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 13:59:22 -0600 Subject: [PATCH 1/7] Engine.stop runs every step under its own guard A stop step that raised or was cancelled skipped every step after it, the store's close included: the steps before the intake monitor were unguarded, and the monitor's stop was guarded only against a cancel. A CancelledError a step leaked from a task of its own was read as a cancel of stop() itself. Each step now runs under _StopSteps, a per-step guard. A failure is held and the steps after it still run; the store closes; the first failure is raised after the close, later ones are logged through safe_exc, and a SystemExit or KeyboardInterrupt is never dropped for an ordinary error or replaced by a cancel. Only a cancel count that rose during the step reads as a cancel of the stop; a leaked CancelledError becomes a RuntimeError step failure. The registry runner's stop is a barrier: one that fails or is cancelled may leave a listener live (ADR 0157 Amendment B), so the stop raises there and skips the later steps and the close, as before. The coordinator's demote-hook removal is its own step. A stop coroutine closed mid-step logs what it held. Tests that faked a cancel of the stop with a bare raise now cancel the stopping task, and the CRL and Transit-lease tests that pinned the old early exit now pin the new behaviour. docs/SERVICE.md says so. BACKLOG #8190 (items 7, 32, 74, 75). Proposed PR title: Engine.stop guards each teardown step so a failure or cancel still reaches the store close Proposed ledger banner for #8190: Items 7, 32, 74 and 75 are built on branch rebuild-8190-793f. Engine.stop runs each step under a per-step guard (_StopSteps), so a step that raises or is cancelled, the intake monitor's included, no longer skips the later steps or the store close; a CancelledError a step leaked from its own child is a step failure, not a cancel of the stop. The registry runner's stop stays a barrier, because a failed graph stop may leave a listener live (ADR 0157 Amendment B). The guard also reads the cancel baseline at entry and guards the store close, which touches items 67 and 69, not re-read here as their closing. The other items stay open. Verified-by: tests --- docs/SERVICE.md | 6 +- messagefoundry/pipeline/engine.py | 296 +++++++++++++++++--------- tests/test_3929_transit_bulk_pool.py | 36 +++- tests/test_engine_stop_budget.py | 10 +- tests/test_engine_stop_steps.py | 300 +++++++++++++++++++++++++++ tests/test_intake_alert_expiry.py | 20 +- 6 files changed, 548 insertions(+), 120 deletions(-) create mode 100644 tests/test_engine_stop_steps.py diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 0e7fc70522..b2a4caf070 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -550,9 +550,9 @@ 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. The engine's other stop steps are guarded the same way, with at least one exception: + when the message graph's own stop fails or is cancelled, a listener may still be live, so the + stop ends there without closing the store, as it did before. - **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..12322accd2 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,99 @@ 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). + + A step that raises or is cancelled does not skip the steps after it, the store's close above + all, so the guard is per step, as the managed lifespan's teardown is. 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: only a count that rose during the step is a cancel of the stop. That cancel is + held, and raised by :meth:`finish` in place of any error, which is then logged. A leaked + CancelledError is a step failure like any other. The first failure is held and raised by + :meth:`finish`; each later one is logged when it happens, except that a SystemExit or + KeyboardInterrupt replaces a held ordinary error, and is never replaced by a cancel. + + 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 what is held at once, so the coordinator is not deregistered and the + store is not closed under a live graph. GeneratorExit is not caught either, so a stop coroutine + that is being closed runs no further step; what was held 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() + self._cancelled = False + self._failure: BaseException | None = None + + def _cancels(self) -> int: + return 0 if self._task is None else self._task.cancelling() + + @contextlib.contextmanager + def step(self, label: str, *, barrier: bool = False) -> Iterator[None]: + before = self._cancels() + try: + yield + except GeneratorExit: + if self._failure is not None: + log.error( + "the engine stop was closed during step %r; a held stop failure is dropped: %s", + label, + safe_exc(self._failure), + ) + raise + except asyncio.CancelledError as exc: + if self._cancels() > before: + self._cancelled = True + else: + leaked = RuntimeError( + f"engine stop step {label!r} ended cancelled, though the stop was not cancelled" + ) + leaked.__cause__ = exc + self._hold(label, leaked) + if barrier: + self.finish() + except BaseException as exc: # noqa: BLE001 - held, and raised once every step has run + self._hold(label, exc) + if barrier: + self.finish() + + def _hold(self, label: str, exc: BaseException) -> None: + held = self._failure + if held is None: + self._failure = exc + return + dropped = exc + if isinstance(held, Exception) and not isinstance(exc, Exception): + self._failure, dropped = exc, held # an interrupt or exit is never dropped + # Rendered, not traced: an inbound stop's OSError can carry a partner file name. + log.error( + "engine stop step %r failed while another stop failure was held; this one is logged " + "and not raised: %s", + label, + safe_exc(dropped), + ) + + def finish(self) -> None: + """Raise what the steps left: SystemExit or KeyboardInterrupt first, then a cancel of the + stop, then the first failure.""" + failure = self._failure + if failure is not None and not isinstance(failure, Exception): + raise failure + if self._cancelled or self._cancels() > self._baseline: + 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: " + "%s", + safe_exc(failure), + ) + raise 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,10 +4674,15 @@ 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`, so a step that raises or is cancelled does not + skip the steps after it or the store's close; what the steps raised is raised once the + close has run. The exception is the registry runner's stop: one that fails or is cancelled + may leave the graph live, so the stop raises at once, before any later step or the close. + 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 + is released, once (BACKLOG #3929). A stop that ends before it reaches the close, at that + barrier or because its coroutine is closed, 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) @@ -4632,6 +4731,11 @@ 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): one that raises or is cancelled + # is held, the steps after it still run, and the store still closes. What the steps raised + # is raised once the store has closed (_StopSteps.finish). The one exception is the + # registry runner's barrier, below. + 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 @@ -4646,152 +4750,138 @@ async def _stop_steps(self, budget: _StopBudget) -> None: 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 + 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. + with steps.step("retention runner"): 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() + # 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. - if isinstance(self._coordinator, _SupportsDemoteHook): + # 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. + if isinstance(self._coordinator, _SupportsDemoteHook): + with steps.step("coordinator demote hook"): 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. - drain = getattr(self._alert_sink, "drain_state", None) - if drain is not None: + # 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. + drain = getattr(self._alert_sink, "drain_state", None) + if drain is not None: + with steps.step("alert-state drain"): 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/tests/test_3929_transit_bulk_pool.py b/tests/test_3929_transit_bulk_pool.py index 5ee2b3318d..cf0326aeb4 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,35 @@ 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 only a failed graph stop ends the stop before the close.""" 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..958eb30615 100644 --- a/tests/test_engine_stop_budget.py +++ b/tests/test_engine_stop_budget.py @@ -379,12 +379,12 @@ 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.""" eng = await _engine(tmp_path) runner = CrlReloadRunner(stop_timeout_seconds=30.0) pass_task = asyncio.ensure_future(_hangs()) @@ -407,7 +407,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..f0e70bd550 --- /dev/null +++ b/tests/test_engine_stop_steps.py @@ -0,0 +1,300 @@ +# 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. + +A step that raises or is cancelled must not skip the steps after it, the store's close above all, +and 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 logging +from pathlib import Path +from typing import Any + +import pytest + +from messagefoundry.config.settings import EgressSettings +from messagefoundry.pipeline import engine as engine_module +from messagefoundry.pipeline.engine import Engine + + +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 must not leave the store's worker thread holding the process open.""" + if not closed: + await eng.store.close() + + +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() + with pytest.raises(asyncio.CancelledError): + 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 "is logged and not raised" in r.getMessage()] + assert len(later) == 1 + assert "second fault" in later[0].getMessage() + 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] + assert any("first fault" in r.getMessage() for r in caplog.records), "the error is logged" + 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: + expected: type[BaseException] = ValueError 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() for r in caplog.records) + 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..9f75b6dbfa 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 @@ -547,7 +557,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 @@ -681,7 +691,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) From 78ff2d55e90c0c35d9e6ee77b37d3edc241d126b Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 14:36:00 -0600 Subject: [PATCH 2/7] Engine.stop guard: name the right step, keep the caller's cancel Second review round on the per-step stop guard: - The failure logged in place of another now carries the label of the step that raised it, and a SystemExit or KeyboardInterrupt that replaces a held error no longer logs that error under its own label. - At the registry runner's barrier, the graph stop's own failure is the one raised; an earlier step's failure is logged. - A held cancel of the stop is re-raised as the CancelledError that was delivered, so its message survives, rather than a fresh bare one. - The failure a cancel replaces is logged with its step's label. - Comments no longer claim safe_exc hides a file name, and say "at least" where they list what ends the stop before the close. - The remote-debug watch comment no longer says a cancelled-looking call would end the engine's stop before the close. - The tests release the engine's Transit pool lease when a stop ended before the close. BACKLOG #8190 (items 7, 32, 74, 75). Proposed PR title: Engine.stop guards each teardown step so a failure or cancel still reaches the store close Proposed ledger banner for #8190: Items 7, 32, 74 and 75 are built on branch rebuild-8190-793f. Engine.stop runs each step under a per-step guard (_StopSteps), so a step that raises or is cancelled, the intake monitor's included, no longer skips the later steps or the store close; a CancelledError a step leaked from its own child is a step failure, not a cancel of the stop. The registry runner's stop stays a barrier, because a failed graph stop may leave a listener live (ADR 0157 Amendment B). The guard also reads the cancel baseline at entry and guards the store close, which touches items 67 and 69, not re-read here as their closing. The other items stay open. Verified-by: tests --- messagefoundry/pipeline/engine.py | 70 +++++++++++-------- messagefoundry/pipeline/remote_debug_watch.py | 2 +- tests/test_engine_stop_steps.py | 17 +++-- tests/test_intake_alert_expiry.py | 7 +- 4 files changed, 56 insertions(+), 40 deletions(-) diff --git a/messagefoundry/pipeline/engine.py b/messagefoundry/pipeline/engine.py index 12322accd2..554c583934 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -253,22 +253,24 @@ class _StopSteps: cancel count: only a count that rose during the step is a cancel of the stop. That cancel is held, and raised by :meth:`finish` in place of any error, which is then logged. A leaked CancelledError is a step failure like any other. The first failure is held and raised by - :meth:`finish`; each later one is logged when it happens, except that a SystemExit or - KeyboardInterrupt replaces a held ordinary error, and is never replaced by a cancel. + :meth:`finish`; each later one is logged when it happens. A SystemExit or KeyboardInterrupt + replaces a held ordinary error, and is never replaced by a cancel. 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 what is held at once, so the coordinator is not deregistered and the - store is not closed under a live graph. GeneratorExit is not caught either, so a stop coroutine - that is being closed runs no further step; what was held is logged then.""" + B). The stop then raises at once, the barrier's own failure in place of an earlier one, so the + coordinator is not deregistered and the store is not closed under a live graph. GeneratorExit + is not caught either, so a stop coroutine that is being closed runs no further step; what was + held 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() - self._cancelled = False + self._cancel: asyncio.CancelledError | None = None self._failure: BaseException | None = None + self._failure_label = "" def _cancels(self) -> int: return 0 if self._task is None else self._task.cancelling() @@ -281,58 +283,61 @@ def step(self, label: str, *, barrier: bool = False) -> Iterator[None]: except GeneratorExit: if self._failure is not None: log.error( - "the engine stop was closed during step %r; a held stop failure is dropped: %s", + "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), ) raise except asyncio.CancelledError as exc: if self._cancels() > before: - self._cancelled = True + self._cancel = self._cancel or exc else: leaked = RuntimeError( f"engine stop step {label!r} ended cancelled, though the stop was not cancelled" ) leaked.__cause__ = exc - self._hold(label, leaked) + 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) + self._hold(label, exc, replaces=barrier or not isinstance(exc, Exception)) if barrier: self.finish() - def _hold(self, label: str, exc: BaseException) -> None: - held = self._failure - if held is None: - self._failure = exc - return - dropped = exc - if isinstance(held, Exception) and not isinstance(exc, Exception): - self._failure, dropped = exc, held # an interrupt or exit is never dropped - # Rendered, not traced: an inbound stop's OSError can carry a partner file name. + def _hold(self, label: str, exc: BaseException, *, replaces: bool) -> None: + """Hold ``exc`` as the failure to raise, unless one is already held and ``replaces`` is + false; the failure not raised is logged. A held SystemExit or KeyboardInterrupt is never + replaced: the only step after one that can raise again is the barrier, which then raises.""" + 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: + 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 while another stop failure was held; this one is logged " - "and not raised: %s", + "engine stop step %r failed; another stop failure is raised in its place: %s", label, - safe_exc(dropped), + safe_exc(exc), ) def finish(self) -> None: """Raise what the steps left: SystemExit or KeyboardInterrupt first, then a cancel of the - stop, then the first failure.""" + stop, then the held failure.""" failure = self._failure if failure is not None and not isinstance(failure, Exception): raise failure - if self._cancelled or self._cancels() > self._baseline: + if self._cancel is not None or self._cancels() > self._baseline: 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: " - "%s", + "engine stop step %r failed; the stop's cancel is raised in its place: %s", + self._failure_label, safe_exc(failure), ) - raise asyncio.CancelledError + raise self._cancel if self._cancel is not None else asyncio.CancelledError() if failure is not None: raise failure @@ -4676,8 +4681,9 @@ async def stop(self, *, budget_seconds: float | None = None) -> None: Each step runs under :class:`_StopSteps`, so a step that raises or is cancelled does not skip the steps after it or the store's close; what the steps raised is raised once the - close has run. The exception is the registry runner's stop: one that fails or is cancelled - may leave the graph live, so the stop raises at once, before any later step or the close. + close has run. The exceptions include at least the registry runner's stop: one that fails + or is cancelled may leave the graph live, so the stop raises at once, before any later step + or the close. 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 ends before it reaches the close, at that @@ -4733,8 +4739,10 @@ async def _stop_steps(self, budget: _StopBudget) -> None: retention_kept = crl_kept + _STOP_WAIT_SHARE_SECONDS # Every step below runs under its own guard (BACKLOG #8190): one that raises or is cancelled # is held, the steps after it still run, and the store still closes. What the steps raised - # is raised once the store has closed (_StopSteps.finish). The one exception is the - # registry runner's barrier, below. + # is raised once the store has closed (_StopSteps.finish). The exceptions include at least + # the registry runner's barrier, below, and a stop coroutine closed mid-step. A cancel held + # from an early step is not passed on to the registry runner's stop, so that stop runs as + # an uncancelled one does and the store can still close after it. 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 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_engine_stop_steps.py b/tests/test_engine_stop_steps.py index f0e70bd550..1eeb35943f 100644 --- a/tests/test_engine_stop_steps.py +++ b/tests/test_engine_stop_steps.py @@ -77,9 +77,11 @@ async def _close() -> None: async def _close_if_left_open(eng: Engine, closed: list[bool]) -> None: - """A failing test must not leave the store's worker thread holding the process open.""" + """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: @@ -141,8 +143,8 @@ async def test_a_cancel_of_the_stop_in_an_early_step_still_closes_the_store( stopping = asyncio.ensure_future(eng.stop()) try: await asyncio.wait_for(entered.wait(), 10) - stopping.cancel() - with pytest.raises(asyncio.CancelledError): + 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] @@ -196,9 +198,10 @@ async def test_the_first_failure_is_raised_and_a_later_one_is_logged( ): await eng.stop() assert closed == [True] - later = [r for r in caplog.records if "is logged and not raised" in r.getMessage()] + 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) @@ -218,7 +221,8 @@ async def test_an_exit_after_an_ordinary_failure_is_what_the_stop_raises( ): await eng.stop() assert closed == [True] - assert any("first fault" in r.getMessage() for r in caplog.records), "the error is logged" + [logged] = [r for r in caplog.records if "first fault" in r.getMessage()] + assert "'backup runner'" in logged.getMessage(), "named by the step that raised it" finally: await _close_if_left_open(eng, closed) @@ -243,7 +247,8 @@ async def test_a_failed_graph_stop_ends_the_stop_before_the_later_steps_and_the_ await asyncio.wait_for(entered.wait(), 10) stopping.cancel() try: - expected: type[BaseException] = ValueError if how == "raises" else asyncio.CancelledError + # 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"] diff --git a/tests/test_intake_alert_expiry.py b/tests/test_intake_alert_expiry.py index 9f75b6dbfa..cf48bceda5 100644 --- a/tests/test_intake_alert_expiry.py +++ b/tests/test_intake_alert_expiry.py @@ -496,7 +496,9 @@ 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) + 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 the cancel replaces is logged, and only then" @@ -573,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" From a4c3a15fbbd1d3c5b823f99af440adff891e9676 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 15:59:59 -0600 Subject: [PATCH 3/7] Engine.stop: an early cancel ends the stop before the graph stop, and no cancel is lost A cancel of the stop delivered in a step before the graph stop, other than the retention runner's stop, or requested before stop() was called, is now raised where the registry runner's stop would begin, without beginning or waiting on it, and the store is left open, as before this row. A wedged inbound stop can no longer hold a cancelled stop. A cancel taken in the retention stop is still held while the graph stop and the close run, as before. A cancel that arrives during the graph stop keeps the barrier's behaviour; RegistryRunner is unchanged. A cancel requested before the stop and not yet delivered is delivered and held before the first step, and a cancel requested in one step and delivered in a later one is read as the stop's, by a watermark of the last cancel taken rather than a per-step count. Neither reads as a failed step nor is lost when a step swallows it. The alert sink's drain lookup and the coordinator's demote-hook check now run inside their steps, so neither can end the stop before the close. The Engine.stop, _StopSteps and _hold docstrings, and docs/SERVICE.md, now say what the code does, including that a cancel taken early leaves the store open. BACKLOG #8190, items 7, 32, 74 and 75 (PR 3590 holds 7358532721 and 7359712472). Verified-by: tests --- docs/SERVICE.md | 10 +- messagefoundry/pipeline/engine.py | 134 ++++++++++++----- tests/test_engine_stop_steps.py | 238 ++++++++++++++++++++++++++++++ 3 files changed, 343 insertions(+), 39 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index b2a4caf070..3ff9444159 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -550,9 +550,13 @@ 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. The engine's other stop steps are guarded the same way, with at least one exception: - when the message graph's own stop fails or is cancelled, a listener may still be live, so the - stop ends there without closing the store, as it did before. + closed, and the message graph's stop still runs first. The engine's other stop steps are + guarded the same way, with at least two exceptions, each of which ends the stop without closing + the store, as before. A cancel taken in a stop step before the message graph's stop, other than + this wait, or requested before the stop began, ends the stop where the graph's stop would begin, + when the engine has a graph, without starting or waiting on it: a cancel taken early leaves the + store open. And when the message graph's own stop fails + or is cancelled, a listener may still be live, so the stop ends there. - **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 554c583934..3b6c6291cd 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -250,34 +250,73 @@ class _StopSteps: A step that raises or is cancelled does not skip the steps after it, the store's close above all, so the guard is per step, as the managed lifespan's teardown is. 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: only a count that rose during the step is a cancel of the stop. That cancel is - held, and raised by :meth:`finish` in place of any error, which is then logged. A leaked - CancelledError is a step failure like any other. The first failure is held and raised by - :meth:`finish`; each later one is logged when it happens. A SystemExit or KeyboardInterrupt - replaces a held ordinary error, and is never replaced by a cancel. + 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. 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. The first failure is held and raised by :meth:`finish`; each + later one is logged when it happens. A SystemExit or KeyboardInterrupt replaces a held + ordinary error, is never replaced, and is raised in place of a cancel. + + A cancel of the stop delivered before the graph stop, in a step other than one marked + ``cancel_runs_graph_stop``, ended the stop at once before BACKLOG #8190, and still ends it + before the graph stop: :meth:`leave_if_cancelled` raises it, as :meth:`finish` orders it, + where the graph stop would begin, so that stop is never begun or waited on and the store is + left open, as before. 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, the barrier's own failure in place of an earlier one, so the - coordinator is not deregistered and the store is not closed under a live graph. GeneratorExit - is not caught either, so a stop coroutine that is being closed runs no further step; what was - held is logged then.""" + 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; what was held 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 cancel was delivered that ends the stop before the graph stop. + self._leaves = False self._failure: BaseException | None = None self._failure_label = "" def _cancels(self) -> int: return 0 if self._task is None else self._task.cancelling() + def _take_cancel(self, exc: asyncio.CancelledError, *, leaves: bool) -> None: + self._cancel, self._taken = self._cancel or exc, self._cancels() + self._leaves = self._leaves or leaves + + 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._take_cancel(exc, leaves=True) + + def leave_if_cancelled(self) -> None: + """Raise, as :meth:`finish` orders it, if a cancel of the stop was delivered where + the stop left at once before BACKLOG #8190; called where the graph stop would begin.""" + if self._leaves: + self.finish() + @contextlib.contextmanager - def step(self, label: str, *, barrier: bool = False) -> Iterator[None]: - before = self._cancels() + def step( + self, label: str, *, barrier: bool = False, cancel_runs_graph_stop: bool = False + ) -> Iterator[None]: try: yield except GeneratorExit: @@ -291,8 +330,8 @@ def step(self, label: str, *, barrier: bool = False) -> Iterator[None]: ) raise except asyncio.CancelledError as exc: - if self._cancels() > before: - self._cancel = self._cancel or exc + if self._cancels() > self._taken: + self._take_cancel(exc, leaves=not cancel_runs_graph_stop) else: leaked = RuntimeError( f"engine stop step {label!r} ended cancelled, though the stop was not cancelled" @@ -307,9 +346,11 @@ def step(self, label: str, *, barrier: bool = False) -> Iterator[None]: self.finish() def _hold(self, label: str, exc: BaseException, *, replaces: bool) -> None: - """Hold ``exc`` as the failure to raise, unless one is already held and ``replaces`` is - false; the failure not raised is logged. A held SystemExit or KeyboardInterrupt is never - replaced: the only step after one that can raise again is the barrier, which then raises.""" + """Hold ``exc`` as the failure to raise. 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, the barrier's included, 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 @@ -4679,18 +4720,31 @@ 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`, so a step that raises or is cancelled does not - skip the steps after it or the store's close; what the steps raised is raised once the - close has run. The exceptions include at least the registry runner's stop: one that fails - or is cancelled may leave the graph live, so the stop raises at once, before any later step - or the close. + 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 steps after it or the store's close, and what the steps + raised is raised once the close has run, with at least these exceptions, each of which + raises before any later step or the close: + + - a cancel of this stop delivered before the graph stop, in a step other than the + retention runner's stop, or requested before this stop was called: where there is a + registry runner, this stop raises the cancel where its stop would begin, without + beginning it or waiting on it, and leaves the store open, as before BACKLOG #8190. A + cancel delivered in the retention runner's stop is held, and the graph stop and the + close run, as before; + - the registry runner's stop failing or being cancelled, which may leave the graph live; + - the stop coroutine being closed mid-step. + + 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 ends before it reaches the close, at that - barrier or because its coroutine is closed, 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: @@ -4740,10 +4794,11 @@ async def _stop_steps(self, budget: _StopBudget) -> None: # Every step below runs under its own guard (BACKLOG #8190): one that raises or is cancelled # is held, the steps after it still run, and the store still closes. What the steps raised # is raised once the store has closed (_StopSteps.finish). The exceptions include at least - # the registry runner's barrier, below, and a stop coroutine closed mid-step. A cancel held - # from an early step is not passed on to the registry runner's stop, so that stop runs as - # an uncancelled one does and the store can still close after it. + # a cancel delivered before the graph stop that ended the stop at once before (raised where the + # graph stop would begin, leave_if_cancelled below), the registry runner's barrier, and a + # stop coroutine closed mid-step. steps = _StopSteps() + await steps.take_a_pending_cancel() # 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 @@ -4767,8 +4822,9 @@ async def _stop_steps(self, budget: _StopBudget) -> None: if self._retention_runner is not None: retention = self._retention_runner # 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. - with steps.step("retention runner"): + # 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", cancel_runs_graph_stop=True): await retention.stop( timeout=budget.wait(retention.stop_timeout_seconds, kept=retention_kept) ) @@ -4813,6 +4869,11 @@ async def _stop_steps(self, budget: _StopBudget) -> None: with steps.step("reference sync runner"): await self._reference_runner.stop() if self._registry_runner is not None: + # A cancel delivered above that ended the stop at once before BACKLOG #8190 is raised + # here, before the graph stop begins: a wedged inbound stop would otherwise hold a + # cancelled stop, and the store is left open, as before. One that arrives during the graph stop is + # the barrier's, below. + steps.leave_if_cancelled() # 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 @@ -4859,8 +4920,8 @@ async def _stop_steps(self, budget: _StopBudget) -> None: # 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. - if isinstance(self._coordinator, _SupportsDemoteHook): - with steps.step("coordinator demote hook"): + 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() @@ -4885,9 +4946,10 @@ async def _stop_steps(self, budget: _StopBudget) -> None: # 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. - drain = getattr(self._alert_sink, "drain_state", None) - if drain is not None: - with steps.step("alert-state drain"): + # 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)) self._store_close_reached = True # stop() releases the Transit pool lease from here on with steps.step("store close"): diff --git a/tests/test_engine_stop_steps.py b/tests/test_engine_stop_steps.py index 1eeb35943f..31cd4beb72 100644 --- a/tests/test_engine_stop_steps.py +++ b/tests/test_engine_stop_steps.py @@ -16,8 +16,13 @@ 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: @@ -303,3 +308,236 @@ async def test_a_stop_coroutine_closed_mid_step_runs_no_further_step( assert any("held fault" 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) + + +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) + + +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) From ed175be3753fe83e49828353d1ec0883207a60a0 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 16:20:15 -0600 Subject: [PATCH 4/7] Engine.stop: a swallowed or pre-stop cancel also ends the stop before the graph stop Review round round-b24c20ad31 on a4c3a15fbbd found that the engine's own runner stops swallow the CancelledError of their await, so a cancel taken there never reached the early-leave check, and that a cancel requested before stop() was marked as leaving even where the retention stop would have taken it. - A step now marks the stop as leaving whenever the cancel count rose during it, let out, swallowed or left to a later step, unless the step is the retention stop (leaves_on_cancel=False). - A cancel taken before the first step counts against the first step that runs, so one that first reaches the retention stop still lets the graph stop and the close run. - The pending-cancel probe runs after the graph supervisor is told to stop, so its loop turn cannot let a reconcile begin. - A stop coroutine closed mid-step logs a held cancel as well as a held failure. - Docstrings, comments and docs/SERVICE.md match; two test docstrings in other files that the change made false are corrected. BACKLOG #8190, items 7, 32, 74 and 75 (PR 3590 hold 7359712472). Verified-by: tests --- docs/SERVICE.md | 9 ++- messagefoundry/pipeline/engine.py | 100 +++++++++++++++------------ tests/test_3929_transit_bulk_pool.py | 3 +- tests/test_engine_stop_budget.py | 4 +- tests/test_engine_stop_steps.py | 83 ++++++++++++++++++++++ 5 files changed, 147 insertions(+), 52 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 3ff9444159..c191f6e83b 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -552,11 +552,10 @@ can be lost: WARNING. A cancel of the engine's stop during this wait is held and raised once the store has closed, and the message graph's stop still runs first. The engine's other stop steps are guarded the same way, with at least two exceptions, each of which ends the stop without closing - the store, as before. A cancel taken in a stop step before the message graph's stop, other than - this wait, or requested before the stop began, ends the stop where the graph's stop would begin, - when the engine has a graph, without starting or waiting on it: a cancel taken early leaves the - store open. And when the message graph's own stop fails - or is cancelled, a listener may still be live, so the stop ends there. + the store. A cancel taken in a stop step before the message graph's stop, other than this wait, + ends the stop where the graph's stop would begin, when the engine has a graph, without starting + or waiting on it: a cancel taken early leaves the store open, as before. And when the message + graph's own stop fails or is cancelled, a listener may still be live, so the stop ends there. - **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 3b6c6291cd..5bd5a34141 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -253,18 +253,19 @@ class _StopSteps: 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. 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. The first failure is held and raised by :meth:`finish`; each - later one is logged when it happens. A SystemExit or KeyboardInterrupt replaces a held + 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. 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. The first failure is held and raised by :meth:`finish`; + each later one is logged when it happens. A SystemExit or KeyboardInterrupt replaces a held ordinary error, is never replaced, and is raised in place of a cancel. - A cancel of the stop delivered before the graph stop, in a step other than one marked - ``cancel_runs_graph_stop``, ended the stop at once before BACKLOG #8190, and still ends it - before the graph stop: :meth:`leave_if_cancelled` raises it, as :meth:`finish` orders it, - where the graph stop would begin, so that stop is never begun or waited on and the store is - left open, as before. + A cancel of the stop requested in a step before the graph stop marks the stop as leaving, + whether the step let it out, swallowed it, or left it to a later step, unless the step was + given ``leaves_on_cancel=False``. :meth:`leave_if_cancelled`, called where the graph stop + would begin, then raises as :meth:`finish` orders it, 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 @@ -272,7 +273,7 @@ class _StopSteps: 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; what was held is logged then.""" + is being closed runs no further step; a held failure or cancel is logged then.""" def __init__(self) -> None: self._task = asyncio.current_task() @@ -283,18 +284,16 @@ def __init__(self) -> None: # was requested by nobody since, so a step leaked it. self._taken = self._baseline self._cancel: asyncio.CancelledError | None = None - # Whether a cancel was delivered that ends the stop before the graph stop. + # Whether a cancel of the stop was requested in a step that leaves on one. 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() - def _take_cancel(self, exc: asyncio.CancelledError, *, leaves: bool) -> None: - self._cancel, self._taken = self._cancel or exc, self._cancels() - self._leaves = self._leaves or leaves - 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 @@ -305,33 +304,39 @@ async def take_a_pending_cancel(self) -> None: try: await asyncio.sleep(0) except asyncio.CancelledError as exc: - self._take_cancel(exc, leaves=True) + self._cancel, self._taken = exc, self._cancels() + self._pending_unplaced = True def leave_if_cancelled(self) -> None: - """Raise, as :meth:`finish` orders it, if a cancel of the stop was delivered where - the stop left at once before BACKLOG #8190; called where the graph stop would begin.""" + """Called where the graph stop would begin: raise, as :meth:`finish` orders it, if a + step that leaves on a cancel saw one.""" if self._leaves: self.finish() @contextlib.contextmanager def step( - self, label: str, *, barrier: bool = False, cancel_runs_graph_stop: bool = False + 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: + if self._failure is not None or self._cancel is not None: log.error( - "the engine stop was closed during step %r; the failure held from step %r is " - "dropped: %s", + "the engine stop was closed during step %r; what it held is dropped: " + "a cancel of the stop: %s; a failure from step %r: %s", label, + self._cancel is not None, self._failure_label, - safe_exc(self._failure), + "none" if self._failure is None else safe_exc(self._failure), ) raise except asyncio.CancelledError as exc: if self._cancels() > self._taken: - self._take_cancel(exc, leaves=not cancel_runs_graph_stop) + 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" @@ -344,6 +349,11 @@ def step( self._hold(label, exc, replaces=barrier or not isinstance(exc, Exception)) if barrier: self.finish() + finally: + # A cancel of the stop requested in this step that it swallowed, or left to a later + # step: the engine's runner stops catch the CancelledError of their own await. + if leaves_on_cancel and self._cancels() > self._taken: + self._leaves = True def _hold(self, label: str, exc: BaseException, *, replaces: bool) -> None: """Hold ``exc`` as the failure to raise. A failure already held is kept, and ``exc`` is @@ -4726,12 +4736,14 @@ async def stop(self, *, budget_seconds: float | None = None) -> None: raised is raised once the close has run, with at least these exceptions, each of which raises before any later step or the close: - - a cancel of this stop delivered before the graph stop, in a step other than the - retention runner's stop, or requested before this stop was called: where there is a - registry runner, this stop raises the cancel where its stop would begin, without - beginning it or waiting on it, and leaves the store open, as before BACKLOG #8190. A - cancel delivered in the retention runner's stop is held, and the graph stop and the - close run, as before; + - a cancel of this stop requested in a step before the graph stop, other than the + retention runner's stop, whether the step let it out or swallowed it, or requested + before this stop was called and first reaching such a step: where there is a registry + runner, this stop raises the cancel where its stop would begin, without beginning it or + waiting on it, and leaves the store open, as a cancel that escaped an early step did + before BACKLOG #8190. The steps before that point still run. A cancel in the retention runner's stop, + or requested before this stop and first reaching that stop, is held, and the graph + stop and the close run, as before; - the registry runner's stop failing or being cancelled, which may leave the graph live; - the stop coroutine being closed mid-step. @@ -4791,28 +4803,27 @@ 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): one that raises or is cancelled - # is held, the steps after it still run, and the store still closes. What the steps raised - # is raised once the store has closed (_StopSteps.finish). The exceptions include at least - # a cancel delivered before the graph stop that ended the stop at once before (raised where the - # graph stop would begin, leave_if_cancelled below), the registry runner's barrier, and a - # stop coroutine closed mid-step. + # 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() - await steps.take_a_pending_cancel() # 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 + # 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) @@ -4824,7 +4835,7 @@ async def _stop_steps(self, budget: _StopBudget) -> None: # 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", cancel_runs_graph_stop=True): + with steps.step("retention runner", leaves_on_cancel=False): await retention.stop( timeout=budget.wait(retention.stop_timeout_seconds, kept=retention_kept) ) @@ -4869,10 +4880,9 @@ async def _stop_steps(self, budget: _StopBudget) -> None: with steps.step("reference sync runner"): await self._reference_runner.stop() if self._registry_runner is not None: - # A cancel delivered above that ended the stop at once before BACKLOG #8190 is raised - # here, before the graph stop begins: a wedged inbound stop would otherwise hold a - # cancelled stop, and the store is left open, as before. One that arrives during the graph stop is - # the barrier's, below. + # A cancel of this stop taken above, other than in the retention stop, ends it here, + # before the graph stop begins, so a wedged inbound stop cannot hold it; the store is + # left open. One that arrives during the graph stop is the barrier's, below. steps.leave_if_cancelled() # 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 diff --git a/tests/test_3929_transit_bulk_pool.py b/tests/test_3929_transit_bulk_pool.py index cf0326aeb4..b9888102ca 100644 --- a/tests/test_3929_transit_bulk_pool.py +++ b/tests/test_3929_transit_bulk_pool.py @@ -545,7 +545,8 @@ async def test_a_stop_that_raises_before_the_close_keeps_the_lease( ) -> 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. - Since BACKLOG #8190 only a failed graph stop ends the stop before the close.""" + 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() diff --git a/tests/test_engine_stop_budget.py b/tests/test_engine_stop_budget.py index 958eb30615..26e7d860b6 100644 --- a/tests/test_engine_stop_budget.py +++ b/tests/test_engine_stop_budget.py @@ -384,7 +384,9 @@ async def test_a_cancel_of_engine_stop_during_the_crl_first_wait_still_closes_th ) -> None: """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.""" + 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()) diff --git a/tests/test_engine_stop_steps.py b/tests/test_engine_stop_steps.py index 31cd4beb72..7e46ffe924 100644 --- a/tests/test_engine_stop_steps.py +++ b/tests/test_engine_stop_steps.py @@ -9,6 +9,7 @@ from __future__ import annotations import asyncio +import contextlib import logging from pathlib import Path from typing import Any @@ -357,6 +358,88 @@ async def test_a_cancel_taken_in_an_early_step_does_not_wait_on_a_wedged_graph_s 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_does_not_wait_on_a_wedged_graph_stop( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The engine's runner stops swallow the cancel of their own await, so the cancel is seen + by the count: the stop still raises it where the graph stop would begin.""" + 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=True) + 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"], "the graph stop did not begin" + assert closed == [] + 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 + + +@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: From e00d369e17fd5d99e40e15a75b916a42bb457890 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 16:39:53 -0600 Subject: [PATCH 5/7] Engine.stop: a pre-stop cancel with only the graph ends the stop, and a retention swallow stays held Review round round-8a8f6c7e45 on ed175be3753: - A cancel taken before the first step and still unplaced when the graph stop would begin, because no step ran before it, now ends the stop there instead of handing the registry runner an uncancelled stop. - A cancel a step swallowed is seen once: a watermark of the count each step ended with keeps a cancel the retention stop swallowed from being read again by the next early step as a leaving cancel. - A stop coroutine closed mid-step logs a held cancel on its own line, including one only the count shows, and no longer prints an empty failure. - docs/SERVICE.md no longer says "as before" where a swallowed cancel used to run the graph stop; the docstrings say a pre-stop cancel delivered early does not cut the first step's own wait. BACKLOG #8190, items 7, 32, 74 and 75 (PR 3590 hold 7359712472). Verified-by: tests --- docs/SERVICE.md | 9 +++-- messagefoundry/pipeline/engine.py | 34 ++++++++++++------ tests/test_engine_stop_steps.py | 58 +++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 14 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index c191f6e83b..e476aeb98b 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -553,9 +553,12 @@ can be lost: closed, and the message graph's stop still runs first. The engine's other stop steps are guarded the same way, with at least two exceptions, each of which ends the stop without closing the store. A cancel taken in a stop step before the message graph's stop, other than this wait, - ends the stop where the graph's stop would begin, when the engine has a graph, without starting - or waiting on it: a cancel taken early leaves the store open, as before. And when the message - graph's own stop fails or is cancelled, a listener may still be live, so the stop ends there. + or requested before the stop began, ends the stop where the graph's stop would begin, when the + engine has a graph, without starting or waiting on it: a cancel taken early leaves the store + open. Before this change such a cancel either did the same or, where the step swallowed it, ran + the graph's stop, which could wait without end on an inbound that would not stop. And when the + message graph's own stop fails or is cancelled, a listener may still be live, so the stop ends + there. - **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 5bd5a34141..d89d3b6167 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -254,7 +254,9 @@ class _StopSteps: 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. A cancel of the stop is + 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. The first failure is held and raised by :meth:`finish`; @@ -288,6 +290,9 @@ def __init__(self) -> None: self._leaves = False # A cancel taken before the first step, not yet counted against a step. self._pending_unplaced = False + # The count a step last ended with: a rise past it, and past _taken, is a cancel that + # step swallowed or left to a later one, so a later step does not see it again. + self._seen = self._baseline self._failure: BaseException | None = None self._failure_label = "" @@ -309,8 +314,9 @@ async def take_a_pending_cancel(self) -> None: def leave_if_cancelled(self) -> None: """Called where the graph stop would begin: raise, as :meth:`finish` orders it, if a - step that leaves on a cancel saw one.""" - if self._leaves: + step that leaves on a cancel saw one, 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._leaves or self._pending_unplaced: self.finish() @contextlib.contextmanager @@ -323,14 +329,17 @@ def step( try: yield except GeneratorExit: - if self._failure is not None or self._cancel is not None: + if self._failure is not None: log.error( - "the engine stop was closed during step %r; what it held is dropped: " - "a cancel of the stop: %s; a failure from step %r: %s", + "the engine stop was closed during step %r; the failure held from step %r is " + "dropped: %s", label, - self._cancel is not None, self._failure_label, - "none" if self._failure is None else safe_exc(self._failure), + 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: @@ -352,8 +361,10 @@ def step( finally: # A cancel of the stop requested in this step that it swallowed, or left to a later # step: the engine's runner stops catch the CancelledError of their own await. - if leaves_on_cancel and self._cancels() > self._taken: - self._leaves = True + count = self._cancels() + if count > max(self._taken, self._seen): + self._leaves = self._leaves or leaves_on_cancel + self._seen = max(self._seen, count) def _hold(self, label: str, exc: BaseException, *, replaces: bool) -> None: """Hold ``exc`` as the failure to raise. A failure already held is kept, and ``exc`` is @@ -4738,7 +4749,8 @@ async def stop(self, *, budget_seconds: float | None = None) -> None: - a cancel of this stop requested in a step before the graph stop, other than the retention runner's stop, whether the step let it out or swallowed it, or requested - before this stop was called and first reaching such a step: where there is a registry + before this stop was called and first reaching such a step or the graph stop itself + (delivered early, it does not cut that first step's own wait): where there is a registry runner, this stop raises the cancel where its stop would begin, without beginning it or waiting on it, and leaves the store open, as a cancel that escaped an early step did before BACKLOG #8190. The steps before that point still run. A cancel in the retention runner's stop, diff --git a/tests/test_engine_stop_steps.py b/tests/test_engine_stop_steps.py index 7e46ffe924..a297015291 100644 --- a/tests/test_engine_stop_steps.py +++ b/tests/test_engine_stop_steps.py @@ -402,6 +402,64 @@ 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 From a07110830cb2dd01d844c60c795540f4994545ba Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 17:49:25 -0600 Subject: [PATCH 6/7] Engine.stop: a swallowed early cancel reaches the close; an early exit leaves before the graph Repair of the PR 3590 hold at e00d369e17fd: 1. A cancel of the stop that an early step swallows no longer marks the stop as leaving: the step guard's finally that did so is deleted, with the watermark only it read. The graph stop and the store's close run and the cancel is raised after the close; with a wedged inbound the graph stop then waits, as origin/main's did. Residual, kept: a cancel requested before the stop whose first step is not the retention stop still ends the stop before the graph stop with the store left open, even where that first step would have swallowed it. 2. A SystemExit, KeyboardInterrupt or other BaseException that is not an Exception, held by any step before the graph stop, ends the stop where the graph stop would begin, as origin/main ended it before the graph stop, so a wedged inbound cannot hold it. 3. The first failed step, when it is an ordinary Exception, is logged at ERROR when it happens, with exc_info, which the configured handlers render through safe_traceback. 4. docs/SERVICE.md, the _StopSteps and Engine.stop docstrings and the test module's lead say what the code does; the "Before this change" sentence is gone. Corrections to earlier commit bodies on this branch. 39f0eb995bd and 78ff2d55e90 said a step that raises or is cancelled no longer skips the later steps or the store close, and proposed a title saying a failure or cancel still reaches the store close. That is not true with a graph: a cancel an early step lets out, and a cancel requested before the stop whose first step is not the retention stop, end the stop before the graph stop and skip the store close. The docs at e00d369e17fd said a cancel requested before the stop ends it without waiting on the graph; that is false when the retention stop is the first step, where the graph stop and the close run. BACKLOG #8190. Verified-by: tests --- docs/SERVICE.md | 18 +++-- messagefoundry/pipeline/engine.py | 120 +++++++++++++++++------------- tests/test_engine_stop_steps.py | 96 +++++++++++++++++++++--- tests/test_intake_alert_expiry.py | 2 +- 4 files changed, 166 insertions(+), 70 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index e476aeb98b..7fbe155d3c 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -551,14 +551,16 @@ can be lost: 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, and the message graph's stop still runs first. The engine's other stop steps are - guarded the same way, with at least two exceptions, each of which ends the stop without closing - the store. A cancel taken in a stop step before the message graph's stop, other than this wait, - or requested before the stop began, ends the stop where the graph's stop would begin, when the - engine has a graph, without starting or waiting on it: a cancel taken early leaves the store - open. Before this change such a cancel either did the same or, where the step swallowed it, ran - the graph's stop, which could wait without end on an inbound that would not stop. And when the - message graph's own stop fails or is cancelled, a listener may still be live, so the stop ends - there. + guarded the same way, with at least the exceptions below, each of which ends the stop without + closing the store. When the engine has a message graph, at least these end the stop where the + graph's stop would begin, without starting or waiting on it: a cancel that a stop step before + the graph's stop, other than this wait, lets out; a cancel requested before the stop began, + whether or not the first stop step would swallow it, unless this wait is that first step; and + a `KeyboardInterrupt` or `SystemExit` raised in any stop step before the graph's stop. Without + a graph, these are held, the store closes, and they are raised after. A cancel that a stop + step swallows does not end the stop early: the graph's stop and the store's close run, and an + inbound that will not stop then holds the stop. And when the message graph's own stop fails + or is cancelled, a listener may still be live, so the stop ends there. - **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 d89d3b6167..cfc0a4b25e 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -247,8 +247,9 @@ def deadline(self, *, kept: float) -> StopDeadline | None: class _StopSteps: """The guard :meth:`Engine.stop` runs each of its steps under (BACKLOG #8190). - A step that raises or is cancelled does not skip the steps after it, the store's close above - all, so the guard is per step, as the managed lifespan's teardown is. A cancel of the stop is + The guard is per step, as the managed lifespan's teardown is, so a step that raises or is + cancelled does not skip the next step. It can still skip the graph stop and the store's + close, in at least the cases the two paragraphs below name. 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 @@ -259,15 +260,22 @@ class _StopSteps: 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. The first failure is held and raised by :meth:`finish`; - each later one is logged when it happens. A SystemExit or KeyboardInterrupt replaces a held - ordinary error, is never replaced, and is raised in place of a cancel. - - A cancel of the stop requested in a step before the graph stop marks the stop as leaving, - whether the step let it out, swallowed it, or left it to a later step, unless the step was - given ``leaves_on_cancel=False``. :meth:`leave_if_cancelled`, called where the graph stop - would begin, then raises as :meth:`finish` orders it, so that stop is never begun or waited - on and the store is left open. + 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 @@ -286,13 +294,11 @@ def __init__(self) -> None: # was requested by nobody since, so a step leaked it. self._taken = self._baseline self._cancel: asyncio.CancelledError | None = None - # Whether a cancel of the stop was requested in a step that leaves on one. + # 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 - # The count a step last ended with: a rise past it, and past _taken, is a cancel that - # step swallowed or left to a later one, so a later step does not see it again. - self._seen = self._baseline self._failure: BaseException | None = None self._failure_label = "" @@ -312,13 +318,21 @@ async def take_a_pending_cancel(self) -> None: self._cancel, self._taken = exc, self._cancels() self._pending_unplaced = True - def leave_if_cancelled(self) -> None: - """Called where the graph stop would begin: raise, as :meth:`finish` orders it, if a - step that leaves on a cancel saw one, 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._leaves or self._pending_unplaced: + 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 @@ -358,24 +372,23 @@ def step( self._hold(label, exc, replaces=barrier or not isinstance(exc, Exception)) if barrier: self.finish() - finally: - # A cancel of the stop requested in this step that it swallowed, or left to a later - # step: the engine's runner stops catch the CancelledError of their own await. - count = self._cancels() - if count > max(self._taken, self._seen): - self._leaves = self._leaves or leaves_on_cancel - self._seen = max(self._seen, count) def _hold(self, label: str, exc: BaseException, *, replaces: bool) -> None: - """Hold ``exc`` as the failure to raise. 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, the barrier's included, is - logged, and :meth:`finish` raises the held one.""" + """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. @@ -389,11 +402,12 @@ 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 failure is not None and not isinstance(failure, Exception): + 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, so it is logged here or not at all. + # 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, @@ -4743,22 +4757,27 @@ async def stop(self, *, budget_seconds: float | None = None) -> None: 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 steps after it or the store's close, and what the steps - raised is raised once the close has run, with at least these exceptions, each of which - raises before any later step or the close: - - - a cancel of this stop requested in a step before the graph stop, other than the - retention runner's stop, whether the step let it out or swallowed it, or requested - before this stop was called and first reaching such a step or the graph stop itself - (delivered early, it does not cut that first step's own wait): where there is a registry - runner, this stop raises the cancel where its stop would begin, without beginning it or - waiting on it, and leaves the store open, as a cancel that escaped an early step did - before BACKLOG #8190. The steps before that point still run. A cancel in the retention runner's stop, - or requested before this stop and first reaching that stop, is held, and the graph - stop and the close run, as before; + 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. @@ -4892,10 +4911,9 @@ async def _stop_steps(self, budget: _StopBudget) -> None: with steps.step("reference sync runner"): await self._reference_runner.stop() if self._registry_runner is not None: - # A cancel of this stop taken above, other than in the retention stop, ends it here, - # before the graph stop begins, so a wedged inbound stop cannot hold it; the store is - # left open. One that arrives during the graph stop is the barrier's, below. - steps.leave_if_cancelled() + # 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 diff --git a/tests/test_engine_stop_steps.py b/tests/test_engine_stop_steps.py index a297015291..f6395f916c 100644 --- a/tests/test_engine_stop_steps.py +++ b/tests/test_engine_stop_steps.py @@ -2,8 +2,11 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """BACKLOG #8190: every Engine.stop step runs under its own guard. -A step that raises or is cancelled must not skip the steps after it, the store's close above all, -and a CancelledError a step leaked from a task of its own must not read as a cancel of the stop. +A step that raises an ordinary error, or swallows a cancel of the stop, must not skip the steps +after it or the store's close. 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 @@ -227,7 +230,8 @@ async def test_an_exit_after_an_ordinary_failure_is_what_the_stop_raises( ): await eng.stop() assert closed == [True] - [logged] = [r for r in caplog.records if "first fault" in r.getMessage()] + [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) @@ -306,7 +310,10 @@ async def test_a_stop_coroutine_closed_mid_step_runs_no_further_step( stop.close() assert ran == ["backup", "update check"] assert closed == [] - assert any("held fault" in r.getMessage() for r in caplog.records) + 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) @@ -373,24 +380,26 @@ async def stop(self, **_kwargs: Any) -> None: await asyncio.Event().wait() -async def test_a_cancel_an_early_step_swallowed_does_not_wait_on_a_wedged_graph_stop( +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, so the cancel is seen - by the count: the stop still raises it where the graph stop would begin.""" + """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=True) + 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"], "the graph stop did not begin" - assert closed == [] + assert ran == ["backup", "update check", "inbound stop", "intake monitor"] + assert closed == [True] finally: if not stopping.done(): stopping.cancel() @@ -516,6 +525,73 @@ async def test_an_uncancelled_early_failure_still_runs_the_graph_stop_and_closes 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.""" diff --git a/tests/test_intake_alert_expiry.py b/tests/test_intake_alert_expiry.py index cf48bceda5..e4dd80df54 100644 --- a/tests/test_intake_alert_expiry.py +++ b/tests/test_intake_alert_expiry.py @@ -499,7 +499,7 @@ async def close() -> None: 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 the cancel replaces is logged, and only then" + 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( From 32f1133731af5bdd05138f645d5860029f234374 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Wed, 2 Dec 2026 18:37:58 -0600 Subject: [PATCH 7/7] Engine.stop text: the stop test lead, the _StopSteps opening and SERVICE.md say what the stop skips Text only, no code line; repair of the PR 3590 hold at a07110830cb: 1. The stop test module's lead says an ordinary error from a step other than the graph stop, or a cancel a step swallows, does not by itself skip the later steps or the store's close, and that a failed or cancelled graph stop skips both. 2. The _StopSteps docstring opens with: 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, and a failed or cancelled barrier skips every later step and the close. 3. docs/SERVICE.md lists, for a message graph, at least the cases that leave the store open, which of them never begin the graph's stop, what a swallowed cancel does, and that an inbound that will not stop holds the graph's stop. Corrections to the body of the previous commit a07110830cb: (a) It withdrew the earlier proposed PR title and ledger banner and proposed none. It also called the bodies of 39f0eb995bd and 78ff2d55e90 untrue. Those bodies held when they were written: the behaviour they describe changed in a4c3a15fbbd, where an early cancel began to end the stop before the graph stop. (b) Its residual omitted "with a graph". Without a registry runner there is no graph stop to end the stop before, and the store closes. BACKLOG #8190. Verified-by: tests --- docs/SERVICE.md | 17 +++++++---------- messagefoundry/pipeline/engine.py | 25 ++++++++++++------------- tests/test_engine_stop_steps.py | 10 +++++----- 3 files changed, 24 insertions(+), 28 deletions(-) diff --git a/docs/SERVICE.md b/docs/SERVICE.md index 7fbe155d3c..b3f9054c07 100644 --- a/docs/SERVICE.md +++ b/docs/SERVICE.md @@ -551,16 +551,13 @@ can be lost: 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, and the message graph's stop still runs first. The engine's other stop steps are - guarded the same way, with at least the exceptions below, each of which ends the stop without - closing the store. When the engine has a message graph, at least these end the stop where the - graph's stop would begin, without starting or waiting on it: a cancel that a stop step before - the graph's stop, other than this wait, lets out; a cancel requested before the stop began, - whether or not the first stop step would swallow it, unless this wait is that first step; and - a `KeyboardInterrupt` or `SystemExit` raised in any stop step before the graph's stop. Without - a graph, these are held, the store closes, and they are raised after. A cancel that a stop - step swallows does not end the stop early: the graph's stop and the store's close run, and an - inbound that will not stop then holds the stop. And when the message graph's own stop fails - or is cancelled, a listener may still be live, so the stop ends there. + 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 cfc0a4b25e..db6ce48416 100644 --- a/messagefoundry/pipeline/engine.py +++ b/messagefoundry/pipeline/engine.py @@ -247,19 +247,18 @@ def deadline(self, *, kept: float) -> StopDeadline | None: class _StopSteps: """The guard :meth:`Engine.stop` runs each of its steps under (BACKLOG #8190). - The guard is per step, as the managed lifespan's teardown is, so a step that raises or is - cancelled does not skip the next step. It can still skip the graph stop and the store's - close, in at least the cases the two paragraphs below name. 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 + 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 diff --git a/tests/test_engine_stop_steps.py b/tests/test_engine_stop_steps.py index f6395f916c..4f14cf2a87 100644 --- a/tests/test_engine_stop_steps.py +++ b/tests/test_engine_stop_steps.py @@ -2,11 +2,11 @@ # Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors """BACKLOG #8190: every Engine.stop step runs under its own guard. -A step that raises an ordinary error, or swallows a cancel of the stop, must not skip the steps -after it or the store's close. 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. +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