From 66c5028a86c3fb8bb355d8270b9175307ea97a3e Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:24:28 -0600 Subject: [PATCH 01/13] SandboxSession refusal cache compares the engine graph by value The cache keyed on `is`, so a graph callable returning an equal but new GraphShape per call spawned a worker and raised a first refusal per spawn. Compared with `==`; a hit only refuses. The mid-write latch half is not a bug: workers run the session's snapshot and never read the directory; a test pins it. BACKLOG #6830 Proposed banner: CLOSED. Half 1 real (unmemoized graph callable missed the cache), fixed with a value compare and a failing test. Half 2 not a bug: snapshot, not disk, feeds every respawn; pinned. --- changelog.d/6830.fixed.md | 1 + messagefoundry/pipeline/sandbox.py | 5 ++- tests/test_sandbox_graph_parity.py | 66 ++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 changelog.d/6830.fixed.md diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md new file mode 100644 index 0000000000..38b8928bc9 --- /dev/null +++ b/changelog.d/6830.fixed.md @@ -0,0 +1 @@ +A sandbox session's refusal cache compares the engine graph by value, so a graph callable that returns an equal but new shape at each call no longer starts a worker and re-raises a first refusal per message. diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index ea62929954..6ed7302c83 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -1048,7 +1048,10 @@ def _spawn(self, phase: str = "spawn") -> None: # survive. A no-op on the first spawn and whenever there is no proc. self._reap(self._proc) engine_graph = self._graph() if self._graph is not None else None - if self._refused is not None and self._refused[0] is engine_graph: + # Compared by value: the cache means "the same graph", and a graph callable need not return + # one object per graph (BACKLOG #6830). A hit only ever refuses, so it cannot let a + # mismatched worker up. + if self._refused is not None and self._refused[0] == engine_graph: raise SandboxWorkerRefused( self._refused[1], first=False, content_only=self._refused[2], graph=engine_graph ) diff --git a/tests/test_sandbox_graph_parity.py b/tests/test_sandbox_graph_parity.py index 5e619091e3..cd8354ca9f 100644 --- a/tests/test_sandbox_graph_parity.py +++ b/tests/test_sandbox_graph_parity.py @@ -32,6 +32,7 @@ SandboxMode, SandboxPolicy, SandboxSession, + SandboxWorkerRefused, graph_differences, graph_shape, ) @@ -299,6 +300,71 @@ def test_a_refused_worker_is_not_started_again_for_the_same_graph( session.close() +def test_an_equal_engine_graph_is_refused_from_the_cache( + config_dir: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The cache means "the same graph", so a graph callable that builds an equal but distinct + shape at each call still hits it (BACKLOG #6830): no second worker, and the second refusal is + not the first, so the runner does not raise its alert again.""" + monkeypatch.setenv(_VARIABLE, "3") + registry = load_config(config_dir) + session = SandboxSession( + SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=30.0), + inbound="IB_PARITY", + config_dir=config_dir, + env=None, + graph=lambda: graph_shape(registry), # unmemoized: a new, equal object at each call + ) + try: + assert session._graph is not None and session._graph() is not session._graph() + with pytest.raises(SandboxWorkerRefused) as first: + session._spawn() + assert first.value.first + with pytest.raises(SandboxWorkerRefused) as second: + session._spawn() + assert session._generation == 1 # no second worker was started + assert not second.value.first + assert str(second.value) == str(first.value) + finally: + session.close() + + +def test_a_config_file_mid_write_on_disk_does_not_reach_a_respawned_worker( + config_dir: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A session's workers run the snapshot the engine loaded and never read the directory, so a + config file caught half-written on disk cannot make a worker's graph differ, at a first spawn or + at a respawn, and there is no transient mismatch for the refusal cache to keep (BACKLOG #6830). + The control: the same half-written directory, loaded, builds no graph at all.""" + monkeypatch.setenv(_VARIABLE, "3") + registry = load_config(config_dir) + assert registry.config_snapshot is not None + (Path(config_dir) / "graph.py").write_text(_GRAPH[: len(_GRAPH) // 2], encoding="utf-8") + with pytest.raises(Exception): # noqa: B017 -- any load failure is the control's point + load_config(config_dir) + session = SandboxSession( + SandboxPolicy( + mode=SandboxMode.SUBPROCESS, wall_seconds=30.0, pass_environment=(_VARIABLE,) + ), + inbound="IB_PARITY", + config_dir=config_dir, + env=None, + graph=lambda: graph_shape(registry), + snapshot=registry.config_snapshot, + ) + try: + session._spawn() + assert session._refused is None + proc = session._proc + assert proc is not None + proc.kill() + proc.wait(timeout=30) + session._spawn() # a respawn, with the disk still half-written + assert session._refused is None and session._generation == 2 + finally: + session.close() + + def test_the_same_graph_comes_up_when_the_variable_is_passed( config_dir: str, monkeypatch: pytest.MonkeyPatch ) -> None: From f699e47bb70b459d2749e0961492a531afbaf3a6 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 03:47:21 -0600 Subject: [PATCH 02/13] Refusal cache hit reports the compared graph; review round 1 fixes A cache hit now carries the graph the worker was compared with. The runner lock comment names the alert gate as the reason for one shape per registry. The changelog fragment is a bullet scoped to direct SandboxSession callers. The duplicate mid-write test is dropped: tests/test_config_snapshot.py already pins that a respawn runs the snapshot, not the disk. BACKLOG #6830 Proposed banner: CLOSED. Half 1 real (unmemoized graph callable missed the cache), fixed with a value compare and a failing test. Half 2 not a bug: the snapshot, not the disk, feeds every respawn. --- changelog.d/6830.fixed.md | 5 +++- messagefoundry/pipeline/sandbox.py | 7 +++-- messagefoundry/pipeline/wiring_runner.py | 5 ++-- tests/test_sandbox_graph_parity.py | 38 ++---------------------- tests/test_sandbox_refusal_alert.py | 4 ++- 5 files changed, 17 insertions(+), 42 deletions(-) diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md index 38b8928bc9..3b73d17823 100644 --- a/changelog.d/6830.fixed.md +++ b/changelog.d/6830.fixed.md @@ -1 +1,4 @@ -A sandbox session's refusal cache compares the engine graph by value, so a graph callable that returns an equal but new shape at each call no longer starts a worker and re-raises a first refusal per message. +- A `SandboxSession` built directly with a graph callable that returns an equal but new shape at + each call now refuses a mismatched worker from its cache, instead of starting a worker and + raising a first refusal per spawn. The engine's runner already passed one shape per registry, so + `serve` behaves as before. (BACKLOG #6830) diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index 6ed7302c83..ed9f584c00 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -1050,10 +1050,13 @@ def _spawn(self, phase: str = "spawn") -> None: engine_graph = self._graph() if self._graph is not None else None # Compared by value: the cache means "the same graph", and a graph callable need not return # one object per graph (BACKLOG #6830). A hit only ever refuses, so it cannot let a - # mismatched worker up. + # mismatched worker up. ``graph`` stays the object the worker was compared with. if self._refused is not None and self._refused[0] == engine_graph: raise SandboxWorkerRefused( - self._refused[1], first=False, content_only=self._refused[2], graph=engine_graph + self._refused[1], + first=False, + content_only=self._refused[2], + graph=self._refused[0], ) # NAMED, not inherited: an allowlist, so the engine's secrets are not in the child's # environment (vault BACKLOG #2587). No engine variable crosses. The config-source escape diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 413899848f..35611522a0 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -2102,8 +2102,9 @@ def __init__( self._outbound_plan: _OutboundPlan | None = None self._sandbox_graph_shape: tuple[Registry, GraphShape] | None = None # Sessions read that cache from their worker threads. Two building it at once would each - # get their own object, and a session matches its cached refusal by identity, so it would - # start a worker and alert again for the same refusal (vault BACKLOG #2724). + # get their own object, and the refusal alert's gate in ``_off_loop_sandboxed`` matches a + # refusal's graph to the served one by identity, so it would drop the alert for a refusal + # against the graph still being served (vault BACKLOG #2724, BACKLOG #6830). self._sandbox_graph_shape_lock = threading.Lock() # ADR 0013 Increment 2: the loop-prevention cap for re-ingress. A re-ingressed message at this # correlation depth still routes; the next hop (depth+1) dead-letters its work-row and ERRORs the diff --git a/tests/test_sandbox_graph_parity.py b/tests/test_sandbox_graph_parity.py index cd8354ca9f..9d29feb1c5 100644 --- a/tests/test_sandbox_graph_parity.py +++ b/tests/test_sandbox_graph_parity.py @@ -325,42 +325,8 @@ def test_an_equal_engine_graph_is_refused_from_the_cache( assert session._generation == 1 # no second worker was started assert not second.value.first assert str(second.value) == str(first.value) - finally: - session.close() - - -def test_a_config_file_mid_write_on_disk_does_not_reach_a_respawned_worker( - config_dir: str, monkeypatch: pytest.MonkeyPatch -) -> None: - """A session's workers run the snapshot the engine loaded and never read the directory, so a - config file caught half-written on disk cannot make a worker's graph differ, at a first spawn or - at a respawn, and there is no transient mismatch for the refusal cache to keep (BACKLOG #6830). - The control: the same half-written directory, loaded, builds no graph at all.""" - monkeypatch.setenv(_VARIABLE, "3") - registry = load_config(config_dir) - assert registry.config_snapshot is not None - (Path(config_dir) / "graph.py").write_text(_GRAPH[: len(_GRAPH) // 2], encoding="utf-8") - with pytest.raises(Exception): # noqa: B017 -- any load failure is the control's point - load_config(config_dir) - session = SandboxSession( - SandboxPolicy( - mode=SandboxMode.SUBPROCESS, wall_seconds=30.0, pass_environment=(_VARIABLE,) - ), - inbound="IB_PARITY", - config_dir=config_dir, - env=None, - graph=lambda: graph_shape(registry), - snapshot=registry.config_snapshot, - ) - try: - session._spawn() - assert session._refused is None - proc = session._proc - assert proc is not None - proc.kill() - proc.wait(timeout=30) - session._spawn() # a respawn, with the disk still half-written - assert session._refused is None and session._generation == 2 + # A hit reports the graph the worker was compared with, not the equal one just read. + assert second.value.graph is first.value.graph finally: session.close() diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 26f6bb1335..44eb2ea3a4 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -204,7 +204,9 @@ def test_the_refusal_survives_a_copy_and_a_pickle() -> None: def test_only_the_comparing_spawn_is_marked_first(edited_config: Path) -> None: - serving = graph_shape(load_config(edited_config)) # one object, as the runner caches it + serving = graph_shape( + load_config(edited_config) + ) # one object per graph, as the runner's alert gate needs _edit(edited_config) session = SandboxSession( SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=30.0), From 0a323236e0f8c7d927bc6d85720b1461d2b1869d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 04:03:12 -0600 Subject: [PATCH 03/13] Review round 2: refusal graph docstring, fragment wording, comment BACKLOG #6830 Proposed banner: CLOSED. Half 1 real: a SandboxSession graph callable returning an equal but new GraphShape missed the refusal cache, so each spawn started a worker; fixed with a value compare and a failing test (the runner memoizes, so serve was not affected). Half 2 not a bug for any session given a snapshot, which every runner session for a loaded registry is: respawns run the snapshot, never the disk. A snapshot=None session reads the disk once and keeps it by #2596 design; that is the snapshot cache, not the refusal latch. --- changelog.d/6830.fixed.md | 9 +++++---- messagefoundry/pipeline/sandbox.py | 3 ++- tests/test_sandbox_refusal_alert.py | 4 +--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md index 3b73d17823..7c6123494d 100644 --- a/changelog.d/6830.fixed.md +++ b/changelog.d/6830.fixed.md @@ -1,4 +1,5 @@ -- A `SandboxSession` built directly with a graph callable that returns an equal but new shape at - each call now refuses a mismatched worker from its cache, instead of starting a worker and - raising a first refusal per spawn. The engine's runner already passed one shape per registry, so - `serve` behaves as before. (BACKLOG #6830) +- **A sandbox session's refusal cache matches the engine graph by value.** A `SandboxSession` built + directly with a graph callable that returns an equal but new shape at each call now refuses from + its cache with no worker started, instead of starting a worker and raising a first refusal per + spawn. The engine's runner passes one shape per registry, so a refusal there was already cached. + (`BACKLOG #6830`) diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index ed9f584c00..f4d9788df4 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -927,7 +927,8 @@ class SandboxWorkerRefused(SandboxError): BACKLOG #2724, owner ruling 2026-10-16). ``content_only`` is True when the config modules' bytes are the only difference: the worker ran other bytes than the engine loaded, which a session sent the engine's snapshot cannot do (vault BACKLOG #2596). ``graph`` is - the engine graph the worker was compared with, so the runner can tell a refusal against a + the engine graph object the worker was compared with, a cached refusal's included (BACKLOG + #6830: a hit matches by value), so the runner can tell a refusal against a graph it no longer serves. The defaults exist only so that a copy or an unpickle, which passes the message alone, still builds.""" diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 44eb2ea3a4..74144f7d85 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -204,9 +204,7 @@ def test_the_refusal_survives_a_copy_and_a_pickle() -> None: def test_only_the_comparing_spawn_is_marked_first(edited_config: Path) -> None: - serving = graph_shape( - load_config(edited_config) - ) # one object per graph, as the runner's alert gate needs + serving = graph_shape(load_config(edited_config)) _edit(edited_config) session = SandboxSession( SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=30.0), From a7c2fd394b01c66916e0f20c5711c4f9cf328c6a Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 04:24:42 -0600 Subject: [PATCH 04/13] The runner's refusal alert gate compares the graph by value The session cache matches an equal graph, so its later hits are never first. The gate compared by identity, so a first refusal raised against an equal graph the runner was not serving the same object of (a swap to an equal registry) dropped the alert for the session's life. A runner-level test covers the cache and the gate together. BACKLOG #6830 Proposed banner: CLOSED. Half 1 real: an equal but new GraphShape missed the refusal cache; the cache and the runner's alert gate now both compare by value, with tests. Half 2 not a bug for sessions given a snapshot: respawns run the snapshot, never the disk. --- changelog.d/6830.fixed.md | 11 +++--- messagefoundry/pipeline/wiring_runner.py | 11 +++--- tests/test_sandbox_refusal_alert.py | 43 +++++++++++++++++++++++- 3 files changed, 55 insertions(+), 10 deletions(-) diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md index 7c6123494d..97506e4895 100644 --- a/changelog.d/6830.fixed.md +++ b/changelog.d/6830.fixed.md @@ -1,5 +1,6 @@ -- **A sandbox session's refusal cache matches the engine graph by value.** A `SandboxSession` built - directly with a graph callable that returns an equal but new shape at each call now refuses from - its cache with no worker started, instead of starting a worker and raising a first refusal per - spawn. The engine's runner passes one shape per registry, so a refusal there was already cached. - (`BACKLOG #6830`) +- **A sandbox session's refusal cache and the runner's refusal alert both match the engine graph + by value.** A `SandboxSession` built directly with a graph callable that returns an equal but new + shape at each call now refuses from its cache with no worker started, instead of starting a + worker and raising a first refusal per spawn. The runner's `sandbox_worker_refused` alert now + fires for a first refusal compared with a graph equal to the one served, so a swap to an equal + registry no longer drops it. (`BACKLOG #6830`) diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 35611522a0..b9a3da1cf8 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -2102,9 +2102,9 @@ def __init__( self._outbound_plan: _OutboundPlan | None = None self._sandbox_graph_shape: tuple[Registry, GraphShape] | None = None # Sessions read that cache from their worker threads. Two building it at once would each - # get their own object, and the refusal alert's gate in ``_off_loop_sandboxed`` matches a - # refusal's graph to the served one by identity, so it would drop the alert for a refusal - # against the graph still being served (vault BACKLOG #2724, BACKLOG #6830). + # get their own object. Both the sessions' refusal cache and the alert gate in + # ``_off_loop_sandboxed`` compare by value (BACKLOG #6830), so this is no longer what keeps + # an alert; it keeps one shape per registry, not one per session (vault BACKLOG #2724). self._sandbox_graph_shape_lock = threading.Lock() # ADR 0013 Increment 2: the loop-prevention cap for re-ingress. A re-ingressed message at this # correlation depth still routes; the next hop (depth+1) dead-letters its work-row and ERRORs the @@ -7485,7 +7485,10 @@ async def _off_loop_sandboxed[T]( # is the remedy, so the alert would stay open with nothing left to fix. The graph the # worker was compared with is checked, not ``registry``: a reload that swapped and # then rolled back leaves ``registry`` served though the comparison used the other. - if exc.first and (exc.graph is None or exc.graph is self._engine_graph_shape()): + # Compared by value, as the session's refusal cache is (BACKLOG #6830): a swap to an + # equal graph leaves the refusal standing, and the session's later hits are not + # ``first``, so dropping this one would lose the alert for the session's life. + if exc.first and (exc.graph is None or exc.graph == self._engine_graph_shape()): # The whole refusal, once: what differs and both digests. A dead-lettered message # keeps only the first 200 characters of it. Config names and digests, no message. log.warning("inbound %r: %s", name, exc) diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 74144f7d85..491f003f47 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -141,6 +141,39 @@ async def test_the_first_refusal_alerts_once_and_later_messages_do_not( assert "the worker loaded" in line and _BODY_MARKER not in line +async def test_a_swap_to_an_equal_registry_keeps_one_alert_and_no_more( + edited_config: Path, tmp_path: Path +) -> None: + """The session's refusal cache and the runner's alert gate together (BACKLOG #6830): the first + refusal alerts once; a swap to an equal but new registry, with the session kept, is the same + graph to both, so the later messages are refused from the cache and raise no second alert.""" + registry = _loaded_then_sent_edited(edited_config) + sink = _Recorder() + store = await MessageStore.open(tmp_path / "swap.db") + try: + runner = _runner(registry, store, edited_config, cast(Any, sink)) + try: + session = runner._sandbox_for("IB_PARITY") + assert session is not None + for swap in (False, True, False): + if swap: + before = runner._engine_graph_shape() + runner.registry = copy.copy(registry) + assert runner._engine_graph_shape() == before + assert runner._engine_graph_shape() is not before + with pytest.raises(SandboxWorkerRefused): + await runner._off_loop_sandboxed( + "IB_PARITY", transform_one, registry, "h_0", RAW, run_context=RunContext() + ) + assert runner._sandbox_for("IB_PARITY") is session + assert session._generation == 1 # one worker, refused once; the rest were cache hits + assert sink.refused == [("IB_PARITY", True)] + finally: + await runner._close_sandbox_sessions() + finally: + await store.close() + + async def test_a_refusal_reached_through_the_closed_session_retry_alerts(tmp_path: Path) -> None: """The retry after a reload closed the session mid-dispatch is inside the alerting arm too.""" registry = Registry(code_digest=_SOME_DIGEST) @@ -182,10 +215,18 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: try: runner = _runner(registry, store, tmp_path, cast(Any, sink)) try: - compared.append(graph_shape(registry)) # equal, but not the object being served + compared.append(graph_shape(Registry(code_digest="1" * 64))) # not the served graph with pytest.raises(SandboxWorkerRefused): await runner._off_loop_sandboxed("IB_X", dispatch, registry) assert sink.refused == [] + # An equal graph is the same graph (BACKLOG #6830): the refusal still stands, so it + # alerts, as the session's by-value cache will not raise another first refusal. + compared[0] = graph_shape(registry) + assert compared[0] is not runner._engine_graph_shape() + with pytest.raises(SandboxWorkerRefused): + await runner._off_loop_sandboxed("IB_X", dispatch, registry) + assert sink.refused == [("IB_X", True)] + sink.refused.clear() # CONTROL: the same refusal against the graph being served does alert. compared[0] = runner._engine_graph_shape() with pytest.raises(SandboxWorkerRefused): From a4d94f9e421d88690c4abe45a30127ebf6500983 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 04:40:56 -0600 Subject: [PATCH 05/13] The refusal alert gate also requires the session still serving A reload to an equal graph discards the session; with the by-value gate, a refusal still in flight then alerted beside the fresh session's own. The gate now also requires that the refusing session is the one the runner holds for the inbound. Docs, docstrings, the changelog and the replaced-graph test say what the code does. BACKLOG #6830 Proposed banner: CLOSED. Half 1 real: an equal but new GraphShape missed the refusal cache; the cache and the runner's alert gate now compare by value, and the gate alerts only for the live session. Half 2 not a bug for sessions given a snapshot. --- changelog.d/6830.fixed.md | 7 +-- docs/CONFIGURATION.md | 6 ++- messagefoundry/pipeline/alerts.py | 7 +-- messagefoundry/pipeline/sandbox.py | 7 +-- messagefoundry/pipeline/wiring_runner.py | 36 ++++++++------ tests/test_sandbox_refusal_alert.py | 61 ++++++++++++++++++++++-- 6 files changed, 95 insertions(+), 29 deletions(-) diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md index 97506e4895..e7c4cd1362 100644 --- a/changelog.d/6830.fixed.md +++ b/changelog.d/6830.fixed.md @@ -1,6 +1,7 @@ - **A sandbox session's refusal cache and the runner's refusal alert both match the engine graph by value.** A `SandboxSession` built directly with a graph callable that returns an equal but new shape at each call now refuses from its cache with no worker started, instead of starting a - worker and raising a first refusal per spawn. The runner's `sandbox_worker_refused` alert now - fires for a first refusal compared with a graph equal to the one served, so a swap to an equal - registry no longer drops it. (`BACKLOG #6830`) + worker and raising a first refusal per spawn. The runner's `sandbox_worker_refused` alert fires + only for a first refusal from the session still serving the inbound, compared with a graph equal + to the one served; a refusal still in flight when a reload discarded its session raises none, + and the fresh session's own refusal is the one alert. (`BACKLOG #6830`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 485a100d4e..47eb59daa8 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1567,8 +1567,10 @@ other module bytes than the engine loaded: is re-pended, or dead-lettered once its attempts reach the retry cap, and the `connection_stopped` alert fires as well. 4. Every later message on that inbound is refused the same way, without starting another worker, - until a reload changes the graph the engine serves. Those refusals raise no further alert and - log no further `WARNING` line of their own. Each other inbound's worker is compared when it + until a reload. Those refusals raise no further alert and log no further `WARNING` line of + their own. Any reload, even one that leaves the graph the same, starts a fresh worker for the + next message, which is compared again. A refusal still in flight when the reload began raises + no alert. Each other inbound's worker is compared when it starts, and each one refused raises its own alert. A reload that does not clear the cause raises the alert again. Nothing resolves it on its own, so resolve it in the alert list once the reload is done. diff --git a/messagefoundry/pipeline/alerts.py b/messagefoundry/pipeline/alerts.py index 23603d45f2..c7fb96fd71 100644 --- a/messagefoundry/pipeline/alerts.py +++ b/messagefoundry/pipeline/alerts.py @@ -1115,9 +1115,10 @@ def sandbox_worker_refused(self, name: str, *, content_only: bool) -> None: #2596 a worker runs the snapshot the engine sends it, so an edit on disk is not a cause. Raised once per refusal, on the event loop, by the runner: not again for each later - message the session refuses from its cached refusal, and not for a refusal computed - against a graph a reload has since replaced. A reload makes fresh sessions, so a refusal - that outlives the reload raises again. A sink that raises here is logged, not retried. ``name`` is the inbound connection's name. + message the session refuses from its cached refusal, not for a refusal from a session a + reload or a rollback has since discarded, and not for one compared with a graph unequal to + the one served (BACKLOG #6830: compared by value). A reload makes fresh sessions, so a + refusal that outlives the reload raises again, from the fresh session. A sink that raises here is logged, not retried. ``name`` is the inbound connection's name. Fixed words only, built by :func:`sandbox_worker_refused_detail`: no message content, no PHI. Not in the control-action set: a restart reloads nothing, so it cannot clear this. Nothing resolves it automatically; an operator resolves the instance after the reload.""" diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index f4d9788df4..85c9f5c9a5 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -212,9 +212,10 @@ class KillCause(str, enum.Enum): # noqa: UP042 #: The worker answered that it ran out of memory and exits, so it is reaped (vault BACKLOG #3133). MEMORY_CAP = "memory_cap" #: The worker loaded a graph that differs from the engine's. No WARNING here: the runner logs - #: and raises the ``sandbox_worker_refused`` alert for a refusal against the graph it serves. A - #: refusal against a graph a reload has since replaced gets neither, and this record does not - #: outlast it: the reload discards this session. That kill then writes no line of its own, + #: and raises the ``sandbox_worker_refused`` alert for a refusal from the session still serving + #: the inbound, against a graph equal to the one it serves. A refusal from a session a reload + #: has discarded, or against an unequal graph, gets neither, and this record does not outlast + #: it: the reload discards this session. That kill then writes no line of its own, #: though its reap can (see :func:`_reap_process_tree`); only the refused dispatch's own error #: reaches the runner's internal-error policy. GRAPH_MISMATCH = "graph_mismatch" diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index b9a3da1cf8..825013d957 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -7465,11 +7465,12 @@ async def _off_loop_sandboxed[T]( the loop, before the exception goes on to the internal-error policy unchanged (vault BACKLOG #2724, owner ruling 2026-10-16: alert, keep dead-letter). Only the refusal that compared the graphs raises it; the session's cached refusals for later messages do not.""" + # The session the dispatch ran on, so the alert gate can tell one a reload has discarded. + session: SandboxSession | None = None try: try: - return await asyncio.to_thread( - fn, registry, *args, sandbox=self._sandbox_for(name), **kwargs - ) + session = self._sandbox_for(name) + return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) except SandboxSessionClosed: if self._stop.is_set() or self.registry is not registry: raise @@ -7477,18 +7478,25 @@ async def _off_loop_sandboxed[T]( "inbound %r: its sandbox worker was recycled mid-dispatch; retrying", name, ) - return await asyncio.to_thread( - fn, registry, *args, sandbox=self._sandbox_for(name), **kwargs - ) + session = self._sandbox_for(name) + return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) except SandboxWorkerRefused as exc: - # Not for a refusal computed against a graph a reload has since replaced: the reload - # is the remedy, so the alert would stay open with nothing left to fix. The graph the - # worker was compared with is checked, not ``registry``: a reload that swapped and - # then rolled back leaves ``registry`` served though the comparison used the other. - # Compared by value, as the session's refusal cache is (BACKLOG #6830): a swap to an - # equal graph leaves the refusal standing, and the session's later hits are not - # ``first``, so dropping this one would lose the alert for the session's life. - if exc.first and (exc.graph is None or exc.graph == self._engine_graph_shape()): + # Only a refusal from the session still serving this inbound, compared with the graph + # still served. A reload or a rollback discards every session, and the next dispatch's + # fresh session compares again and raises its own first refusal, so an alert from the + # discarded one would be a duplicate or, when the reload cleared the cause, an alert + # left open with nothing to fix. The graph is compared by value, as the session's + # refusal cache is (BACKLOG #6830): a session kept across a direct swap of + # ``self.registry`` to an equal graph refuses its later messages from that cache, never + # as ``first``, so this is that refusal's only alert. The graph the worker was + # compared with is checked, not ``registry``: a reload that swapped and then rolled + # back leaves ``registry`` served though the comparison used the other. + if ( + exc.first + and session is not None + and self._sandbox_sessions.get(name) is session + and (exc.graph is None or exc.graph == self._engine_graph_shape()) + ): # The whole refusal, once: what differs and both digests. A dead-lettered message # keeps only the first 200 characters of it. Config names and digests, no message. log.warning("inbound %r: %s", name, exc) diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 491f003f47..4b1db0a98d 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -200,10 +200,14 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: assert sink.refused == [("IB_X", False)] -async def test_a_refusal_against_a_replaced_graph_does_not_alert(tmp_path: Path) -> None: - """The refused spawn compared with a graph the runner no longer serves, as after a reload, - or a reload that swapped and then rolled back. The reload is the remedy, so an alert would - stay open with nothing left to fix.""" +async def test_a_refusal_alerts_only_against_a_graph_equal_to_the_served_one( + tmp_path: Path, +) -> None: + """A refusal from the live session alerts only when the graph it was compared with equals the + one served (BACKLOG #6830). Against an unequal graph, as after a reload that changed it or one + that swapped and rolled back, it does not: the reload is the remedy. Against an equal object + that is not the served one it does, since the session's by-value cache raises no later first + refusal for it.""" registry = Registry(code_digest=_SOME_DIGEST) sink = _Recorder() compared: list[GraphShape] = [] @@ -238,6 +242,55 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: await store.close() +@pytest.mark.parametrize("cleared", [False, True], ids=["cause_stands", "reload_cleared_it"]) +async def test_a_refusal_straddling_a_reload_to_an_equal_graph_alerts_once( + tmp_path: Path, cleared: bool +) -> None: + """A first refusal whose session a reload to an equal graph discarded while it ran raises no + alert: the reload's own first step, as ``_close_sandbox_sessions`` does it, drops the session + before the refusal reaches the gate. The fresh session for the next message compares again. + Where the cause stands, its refusal is the one alert; where the reload cleared it (the + content-only case: the worker now runs the reloaded bytes), no alert is left open at all.""" + registry = Registry(code_digest=_SOME_DIGEST) + sink = _Recorder() + calls: list[Any] = [] + runner: RegistryRunner | None = None + + def dispatch(_registry: Registry, *, sandbox: Any) -> None: + assert runner is not None + calls.append(sandbox) + if len(calls) == 1: + compared = runner._engine_graph_shape() + runner._sandbox_sessions.clear() # the reload drops the sessions, then closes them + runner.registry = copy.copy(registry) # an equal graph, a new object + assert runner._engine_graph_shape() == compared + raise SandboxWorkerRefused("refused", first=True, content_only=True, graph=compared) + if not cleared: + raise SandboxWorkerRefused( + "refused", first=True, content_only=True, graph=runner._engine_graph_shape() + ) + + store = await MessageStore.open(tmp_path / "straddle.db") + try: + runner = _runner(registry, store, tmp_path, cast(Any, sink)) + try: + with pytest.raises(SandboxWorkerRefused): + await runner._off_loop_sandboxed("IB_X", dispatch, registry) + assert sink.refused == [] + if cleared: + await runner._off_loop_sandboxed("IB_X", dispatch, runner.registry) + assert sink.refused == [] + else: + with pytest.raises(SandboxWorkerRefused): + await runner._off_loop_sandboxed("IB_X", dispatch, runner.registry) + assert sink.refused == [("IB_X", True)] + assert calls[0] is not calls[1] # the second message ran on a fresh session + finally: + await runner._close_sandbox_sessions() + finally: + await store.close() + + def test_the_refusal_survives_a_copy_and_a_pickle() -> None: exc = SandboxWorkerRefused("refused", first=True, content_only=True) for clone in (copy.copy(exc), pickle.loads(pickle.dumps(exc))): From e5968cf084a066434d1b8851130f6beb463a8d27 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:38:43 -0600 Subject: [PATCH 06/13] A sandbox refusal a reload overtook re-pends as a closed session The alert gate in _off_loop_sandboxed traded one defect for another: compared by value alone it raised a duplicate alert when a refusal straddled a reload to an equal graph, and with the live-session check added it lost the alert when a same-registry reload (reload(None), a rollback) discarded the session under stop or with no next message. A refusal from a session a reload or a rollback discarded, or against a graph unequal to the one served, is now raised as SandboxSessionClosed by the new _sandboxed_dispatch. It is retried on a fresh session while the same registry is served and the runner is not stopping, and re-pended otherwise, so it neither alerts nor dead-letters; the message's own rerun compares again and that refusal raises the one alert. Functions touched in wiring_runner.py: _off_loop_sandboxed (alert gate and re-pend path) and the new _sandboxed_dispatch. Docs and changelog now state this exactly. BACKLOG #6830 --- changelog.d/6830.fixed.md | 14 ++- docs/CONFIGURATION.md | 9 +- messagefoundry/pipeline/alerts.py | 11 +- messagefoundry/pipeline/sandbox.py | 5 +- messagefoundry/pipeline/wiring_runner.py | 69 +++++++----- tests/test_sandbox_graph_parity.py | 32 ++++++ tests/test_sandbox_refusal_alert.py | 133 ++++++++++++++++++++--- 7 files changed, 219 insertions(+), 54 deletions(-) diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md index e7c4cd1362..4b2cfb8d03 100644 --- a/changelog.d/6830.fixed.md +++ b/changelog.d/6830.fixed.md @@ -1,7 +1,13 @@ - **A sandbox session's refusal cache and the runner's refusal alert both match the engine graph by value.** A `SandboxSession` built directly with a graph callable that returns an equal but new shape at each call now refuses from its cache with no worker started, instead of starting a - worker and raising a first refusal per spawn. The runner's `sandbox_worker_refused` alert fires - only for a first refusal from the session still serving the inbound, compared with a graph equal - to the one served; a refusal still in flight when a reload discarded its session raises none, - and the fresh session's own refusal is the one alert. (`BACKLOG #6830`) + worker and raising a first refusal per spawn. The runner raises `sandbox_worker_refused` for a + first refusal from the session still serving the inbound, against a graph equal to the one + served. A refusal a reload or its rollback overtook, from a session the reload discarded or + against a graph unequal to the one served, now neither alerts nor dead-letters: it is handled as + a closed session is, so the dispatch is retried at once on a fresh session while the same + registry is served and the runner is not stopping, and the message is re-pended otherwise. The + fresh session compares again, and its refusal, if the cause stands, raises the alert. Before, + such a refusal dead-lettered its message, with no alert, or, after a reload that kept the same + registry, with an alert that the next message on a fresh session raised again. + (`BACKLOG #6830`) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 47eb59daa8..5b7fe34dbc 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1569,13 +1569,16 @@ other module bytes than the engine loaded: 4. Every later message on that inbound is refused the same way, without starting another worker, until a reload. Those refusals raise no further alert and log no further `WARNING` line of their own. Any reload, even one that leaves the graph the same, starts a fresh worker for the - next message, which is compared again. A refusal still in flight when the reload began raises - no alert. Each other inbound's worker is compared when it + next message, which is compared again. A refusal still in progress when a reload or its + rollback replaces the worker is neither alerted nor failed: the message runs again on a fresh + worker, at once or after it is re-pended, and that worker's refusal, if the cause stands, + raises the alert. + Each other inbound's worker is compared when it starts, and each one refused raises its own alert. A reload that does not clear the cause raises the alert again. Nothing resolves it on its own, so resolve it in the alert list once the reload is done. -Reload the config: the engine keeps that refusal until a reload changes the graph it serves. Other files in the config directory, such as +Reload the config: the engine keeps that refusal until a reload. Other files in the config directory, such as `connections.toml` and the code-set tables, are not part of the digest: the worker uses the engine's code sets, and `connections.toml` changes the names, which are compared anyway. diff --git a/messagefoundry/pipeline/alerts.py b/messagefoundry/pipeline/alerts.py index c7fb96fd71..0ed3f0a2b6 100644 --- a/messagefoundry/pipeline/alerts.py +++ b/messagefoundry/pipeline/alerts.py @@ -1115,10 +1115,13 @@ def sandbox_worker_refused(self, name: str, *, content_only: bool) -> None: #2596 a worker runs the snapshot the engine sends it, so an edit on disk is not a cause. Raised once per refusal, on the event loop, by the runner: not again for each later - message the session refuses from its cached refusal, not for a refusal from a session a - reload or a rollback has since discarded, and not for one compared with a graph unequal to - the one served (BACKLOG #6830: compared by value). A reload makes fresh sessions, so a - refusal that outlives the reload raises again, from the fresh session. A sink that raises here is logged, not retried. ``name`` is the inbound connection's name. + message the session refuses from its cached refusal. A refusal a reload or a rollback + overtook, from a session the reload discarded or against a graph unequal to the one served + (BACKLOG #6830: compared by value), is not raised and does not fail its message: the + message runs again on a fresh session, whose own refusal, if the cause stands, raises it. + A reload makes fresh sessions, so a refusal that outlives the reload raises again, from the + fresh session. A sink that raises here is logged, not retried. ``name`` is the inbound + connection's name. Fixed words only, built by :func:`sandbox_worker_refused_detail`: no message content, no PHI. Not in the control-action set: a restart reloads nothing, so it cannot clear this. Nothing resolves it automatically; an operator resolves the instance after the reload.""" diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index 85c9f5c9a5..45fc9a148e 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -214,8 +214,9 @@ class KillCause(str, enum.Enum): # noqa: UP042 #: The worker loaded a graph that differs from the engine's. No WARNING here: the runner logs #: and raises the ``sandbox_worker_refused`` alert for a refusal from the session still serving #: the inbound, against a graph equal to the one it serves. A refusal from a session a reload - #: has discarded, or against an unequal graph, gets neither, and this record does not outlast - #: it: the reload discards this session. That kill then writes no line of its own, + #: has discarded, or against an unequal graph, gets neither: the runner re-runs its message on a + #: fresh session, whose refusal does (BACKLOG #6830). This record does not outlast it: the + #: reload discards this session. That kill then writes no line of its own, #: though its reap can (see :func:`_reap_process_tree`); only the refused dispatch's own error #: reaches the runner's internal-error policy. GRAPH_MISMATCH = "graph_mismatch" diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 825013d957..03fb301390 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -2102,9 +2102,9 @@ def __init__( self._outbound_plan: _OutboundPlan | None = None self._sandbox_graph_shape: tuple[Registry, GraphShape] | None = None # Sessions read that cache from their worker threads. Two building it at once would each - # get their own object. Both the sessions' refusal cache and the alert gate in - # ``_off_loop_sandboxed`` compare by value (BACKLOG #6830), so this is no longer what keeps - # an alert; it keeps one shape per registry, not one per session (vault BACKLOG #2724). + # get their own object. Both the sessions' refusal cache and ``_sandboxed_dispatch`` + # compare by value (BACKLOG #6830), so this is no longer what keeps an alert; it keeps one + # shape per registry, not one per session (vault BACKLOG #2724). self._sandbox_graph_shape_lock = threading.Lock() # ADR 0013 Increment 2: the loop-prevention cap for re-ingress. A re-ingressed message at this # correlation depth still routes; the next hop (depth+1) dead-letters its work-row and ERRORs the @@ -7464,13 +7464,17 @@ async def _off_loop_sandboxed[T]( A worker refused for a graph mismatch raises the ``sandbox_worker_refused`` alert here, on the loop, before the exception goes on to the internal-error policy unchanged (vault BACKLOG #2724, owner ruling 2026-10-16: alert, keep dead-letter). Only the refusal that compared the - graphs raises it; the session's cached refusals for later messages do not.""" - # The session the dispatch ran on, so the alert gate can tell one a reload has discarded. - session: SandboxSession | None = None + graphs raises it; the session's cached refusals for later messages do not. + + **A refusal that a reload overtook is a close, not a refusal** (BACKLOG #6830): one from a + session a reload or a rollback has since discarded, or compared with a graph unequal to the + one now served. :meth:`_sandboxed_dispatch` raises it as :class:`SandboxSessionClosed`, so it + is retried or re-pended exactly as above, raises no alert and is not dead-lettered. The + message's next run compares on a session that is serving, and that refusal, if the cause + still stands, is the one that alerts, whether or not any further message arrives.""" try: try: - session = self._sandbox_for(name) - return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) + return await self._sandboxed_dispatch(name, fn, registry, *args, **kwargs) except SandboxSessionClosed: if self._stop.is_set() or self.registry is not registry: raise @@ -7478,25 +7482,11 @@ async def _off_loop_sandboxed[T]( "inbound %r: its sandbox worker was recycled mid-dispatch; retrying", name, ) - session = self._sandbox_for(name) - return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) + return await self._sandboxed_dispatch(name, fn, registry, *args, **kwargs) except SandboxWorkerRefused as exc: - # Only a refusal from the session still serving this inbound, compared with the graph - # still served. A reload or a rollback discards every session, and the next dispatch's - # fresh session compares again and raises its own first refusal, so an alert from the - # discarded one would be a duplicate or, when the reload cleared the cause, an alert - # left open with nothing to fix. The graph is compared by value, as the session's - # refusal cache is (BACKLOG #6830): a session kept across a direct swap of - # ``self.registry`` to an equal graph refuses its later messages from that cache, never - # as ``first``, so this is that refusal's only alert. The graph the worker was - # compared with is checked, not ``registry``: a reload that swapped and then rolled - # back leaves ``registry`` served though the comparison used the other. - if ( - exc.first - and session is not None - and self._sandbox_sessions.get(name) is session - and (exc.graph is None or exc.graph == self._engine_graph_shape()) - ): + # Only a refusal from a session still serving, against the graph still served, gets + # here: :meth:`_sandboxed_dispatch` turns any other into a close. + if exc.first: # The whole refusal, once: what differs and both digests. A dead-lettered message # keeps only the first 200 characters of it. Config names and digests, no message. log.warning("inbound %r: %s", name, exc) @@ -7513,6 +7503,33 @@ async def _off_loop_sandboxed[T]( exited = UserCodeCalledSysExit.from_exit(exc) raise exited + async def _sandboxed_dispatch[T]( + self, name: str, fn: Callable[..., T], registry: Registry, /, *args: Any, **kwargs: Any + ) -> T: + """One dispatch of :meth:`_off_loop_sandboxed`, on the session resolved for it now. + + A :class:`SandboxWorkerRefused` a reload overtook is raised as :class:`SandboxSessionClosed` + (BACKLOG #6830): the session that raised it is no longer the one serving ``name``, because + a reload or a rollback discarded it, or the graph its worker was compared with is not equal + to the one served now. Neither the alert nor the dead-letter belongs to it: the reload may + have cleared the cause, and if not, the message's next run, on a session that is serving, + compares again and alerts once. The graph is compared by value, as the session's refusal + cache is, so a swap of ``self.registry`` to an equal graph does not overtake a refusal. + Checked on the loop with no await before the caller's alert, so a reload cannot discard + the session between this check and that alert.""" + session = self._sandbox_for(name) + try: + return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) + except SandboxWorkerRefused as exc: + if session is not None and ( + self._sandbox_sessions.get(name) is not session + or (exc.graph is not None and exc.graph != self._engine_graph_shape()) + ): + raise SandboxSessionClosed( + f"inbound {name!r}: a reload overtook its sandbox worker's refusal" + ) from exc + raise + async def stop( self, *, diff --git a/tests/test_sandbox_graph_parity.py b/tests/test_sandbox_graph_parity.py index 9d29feb1c5..4fd833b6f1 100644 --- a/tests/test_sandbox_graph_parity.py +++ b/tests/test_sandbox_graph_parity.py @@ -331,6 +331,38 @@ def test_an_equal_engine_graph_is_refused_from_the_cache( session.close() +def test_no_worker_is_kept_against_a_graph_the_cache_does_not_match( + config_dir: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """The by-value cache only ever refuses (BACKLOG #6830): a graph unequal to the cached one is + a miss, so a fresh worker is started and compared, and refused again when it differs. At no + point does a worker come up for a graph it does not match.""" + monkeypatch.setenv(_VARIABLE, "3") + registry = load_config(config_dir) + other = graph_shape(Registry(code_digest="1" * 64)) + serving = [graph_shape(registry)] + session = SandboxSession( + SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=30.0), + inbound="IB_PARITY", + config_dir=config_dir, + env=None, + graph=lambda: serving[0], + ) + try: + for generation, shape in ((1, serving[0]), (2, other), (3, graph_shape(registry))): + serving[0] = shape + with pytest.raises(SandboxWorkerRefused) as refused: + session._spawn() + assert refused.value.first and refused.value.graph is shape + assert session._generation == generation # a miss: a fresh worker was compared + assert session._proc is None # and it was not kept + with pytest.raises(SandboxWorkerRefused) as cached: + session._spawn() + assert not cached.value.first and session._generation == 3 and session._proc is None + finally: + session.close() + + def test_the_same_graph_comes_up_when_the_variable_is_passed( config_dir: str, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 4b1db0a98d..a753764992 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -14,6 +14,7 @@ from __future__ import annotations +import asyncio import copy import logging import pickle @@ -204,10 +205,11 @@ async def test_a_refusal_alerts_only_against_a_graph_equal_to_the_served_one( tmp_path: Path, ) -> None: """A refusal from the live session alerts only when the graph it was compared with equals the - one served (BACKLOG #6830). Against an unequal graph, as after a reload that changed it or one - that swapped and rolled back, it does not: the reload is the remedy. Against an equal object - that is not the served one it does, since the session's by-value cache raises no later first - refusal for it.""" + one served (BACKLOG #6830). Against an unequal graph, as after a direct swap of the registry + with the session kept, it is overtaken: it is retried once, since the registry is still the + one served, and then raised as a close, which the worker re-pends, with no alert and no + dead-letter. Against an equal object that is not the served one it alerts, since the + session's by-value cache raises no later first refusal for it.""" registry = Registry(code_digest=_SOME_DIGEST) sink = _Recorder() compared: list[GraphShape] = [] @@ -220,8 +222,9 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: runner = _runner(registry, store, tmp_path, cast(Any, sink)) try: compared.append(graph_shape(Registry(code_digest="1" * 64))) # not the served graph - with pytest.raises(SandboxWorkerRefused): + with pytest.raises(SandboxSessionClosed) as closed: await runner._off_loop_sandboxed("IB_X", dispatch, registry) + assert isinstance(closed.value.__cause__, SandboxWorkerRefused) assert sink.refused == [] # An equal graph is the same graph (BACKLOG #6830): the refusal still stands, so it # alerts, as the session's by-value cache will not raise another first refusal. @@ -242,15 +245,17 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: await store.close() +@pytest.mark.parametrize("cached", [False, True], ids=["first", "cached"]) @pytest.mark.parametrize("cleared", [False, True], ids=["cause_stands", "reload_cleared_it"]) -async def test_a_refusal_straddling_a_reload_to_an_equal_graph_alerts_once( - tmp_path: Path, cleared: bool +async def test_a_refusal_straddling_a_reload_to_an_equal_graph_re_pends( + tmp_path: Path, cleared: bool, cached: bool ) -> None: - """A first refusal whose session a reload to an equal graph discarded while it ran raises no - alert: the reload's own first step, as ``_close_sandbox_sessions`` does it, drops the session - before the refusal reaches the gate. The fresh session for the next message compares again. - Where the cause stands, its refusal is the one alert; where the reload cleared it (the - content-only case: the worker now runs the reloaded bytes), no alert is left open at all.""" + """A refusal, first or cached, whose session a reload to an equal graph discarded while it ran + is a close, not a refusal (BACKLOG #6830): it raises :class:`SandboxSessionClosed`, which the + worker re-pends, so it neither alerts nor dead-letters. The message's next run, on a fresh + session, compares again. Where the cause stands, its refusal is the one alert; where the reload + cleared it (the content-only case: the worker now runs the reloaded bytes), it is delivered + and no alert is left open.""" registry = Registry(code_digest=_SOME_DIGEST) sink = _Recorder() calls: list[Any] = [] @@ -264,7 +269,9 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: runner._sandbox_sessions.clear() # the reload drops the sessions, then closes them runner.registry = copy.copy(registry) # an equal graph, a new object assert runner._engine_graph_shape() == compared - raise SandboxWorkerRefused("refused", first=True, content_only=True, graph=compared) + raise SandboxWorkerRefused( + "refused", first=not cached, content_only=True, graph=compared + ) if not cleared: raise SandboxWorkerRefused( "refused", first=True, content_only=True, graph=runner._engine_graph_shape() @@ -274,9 +281,12 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: try: runner = _runner(registry, store, tmp_path, cast(Any, sink)) try: - with pytest.raises(SandboxWorkerRefused): + with pytest.raises(SandboxSessionClosed) as closed: await runner._off_loop_sandboxed("IB_X", dispatch, registry) + assert isinstance(closed.value.__cause__, SandboxWorkerRefused) assert sink.refused == [] + assert len(calls) == 1 # another graph is served, so re-pended rather than retried + # The re-pended message's next run reads the registry afresh. if cleared: await runner._off_loop_sandboxed("IB_X", dispatch, runner.registry) assert sink.refused == [] @@ -284,7 +294,100 @@ def dispatch(_registry: Registry, *, sandbox: Any) -> None: with pytest.raises(SandboxWorkerRefused): await runner._off_loop_sandboxed("IB_X", dispatch, runner.registry) assert sink.refused == [("IB_X", True)] - assert calls[0] is not calls[1] # the second message ran on a fresh session + assert calls[0] is not calls[1] # the second run was on a fresh session + finally: + await runner._close_sandbox_sessions() + finally: + await store.close() + + +def _refused_then_reloaded( + runner: RegistryRunner, loop: asyncio.AbstractEventLoop, *, stop: bool +) -> Any: + """``transform_one``, with a reload that re-applies the same registry, as ``reload(None)`` or a + rollback does, landing after the first dispatch's real worker refused and before that refusal + reaches the loop. ``stop`` sets the runner stopping first, as a shutdown that overlaps it.""" + runs: list[Any] = [] + + def call(*args: Any, sandbox: SandboxSession | None = None, **kwargs: Any) -> Any: + runs.append(sandbox) + try: + return transform_one(*args, sandbox=sandbox, **kwargs) + except SandboxWorkerRefused: + if len(runs) == 1: + if stop: + loop.call_soon_threadsafe(runner._stop.set) + asyncio.run_coroutine_threadsafe(runner._close_sandbox_sessions(), loop).result(30) + raise + + call.runs = runs # type: ignore[attr-defined] + return call + + +async def test_a_refusal_straddling_a_same_registry_reload_alerts_once( + edited_config: Path, tmp_path: Path +) -> None: + """A real refusal whose session a same-registry reload discarded while it ran (BACKLOG #6830). + The registry is still served, so the dispatch is retried at once on a fresh session, whose + worker compares again and refuses: that refusal is the one alert, and the message fails on it. + Before, the first refusal was dropped from the alert as stale and still dead-lettered the + message, so no alert was raised until some later message came.""" + registry = _loaded_then_sent_edited(edited_config) + sink = _Recorder() + store = await MessageStore.open(tmp_path / "same.db") + try: + runner = _runner(registry, store, edited_config, cast(Any, sink)) + try: + call = _refused_then_reloaded(runner, asyncio.get_running_loop(), stop=False) + with pytest.raises(SandboxWorkerRefused) as refused: + await runner._off_loop_sandboxed( + "IB_PARITY", call, registry, "h_0", RAW, run_context=RunContext() + ) + assert refused.value.first + assert sink.refused == [("IB_PARITY", True)] + first, second = call.runs + assert first is not None and second is not None + assert first is not second and first._closed and not second._closed + assert first._proc is None and second._proc is None # no worker ever came up + assert runner._sandbox_for("IB_PARITY") is second + # The next message is refused from the serving session's cache: no second alert. + with pytest.raises(SandboxWorkerRefused): + await runner._off_loop_sandboxed( + "IB_PARITY", transform_one, registry, "h_0", RAW, run_context=RunContext() + ) + assert sink.refused == [("IB_PARITY", True)] + finally: + await runner._close_sandbox_sessions() + finally: + await store.close() + + +async def test_a_refusal_straddling_a_reload_under_stop_re_pends_and_alerts_on_its_rerun( + edited_config: Path, tmp_path: Path +) -> None: + """As above, with the runner stopping: nothing is retried while it stops, so the refusal is + raised as a close and the row is re-pended, with no alert and no dead-letter. The alert is not + lost: it comes from the message's own rerun, with no other message needed.""" + registry = _loaded_then_sent_edited(edited_config) + sink = _Recorder() + store = await MessageStore.open(tmp_path / "stop.db") + try: + runner = _runner(registry, store, edited_config, cast(Any, sink)) + try: + call = _refused_then_reloaded(runner, asyncio.get_running_loop(), stop=True) + with pytest.raises(SandboxSessionClosed): + await runner._off_loop_sandboxed( + "IB_PARITY", call, registry, "h_0", RAW, run_context=RunContext() + ) + assert sink.refused == [] + assert len(call.runs) == 1 + # The re-pended row's rerun, once the engine serves again. + runner._stop.clear() + with pytest.raises(SandboxWorkerRefused): + await runner._off_loop_sandboxed( + "IB_PARITY", transform_one, registry, "h_0", RAW, run_context=RunContext() + ) + assert sink.refused == [("IB_PARITY", True)] finally: await runner._close_sandbox_sessions() finally: From 39457d13e40cd21e04cd316ed541fcb18ba5e22c Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 08:41:00 -0600 Subject: [PATCH 07/13] A reaped sandbox worker's pipes are closed, and a slow exit is logged Measured: closing a session left the worker's stdin, stdout and stderr to the collector, which raised three ResourceWarnings, and a reap whose wait timed out passed silently. The reap now closes stdin unless a lookup helper the dispatch gave up on still holds it, in which case that helper closes it when it ends; each drain thread closes the stream it reads; a TimeoutExpired or OSError from the wait logs a WARNING with the inbound and pid only. BACKLOG #6831 Proposed vault banners: #6830: CLOSED (fixed) -- the refusal cache and the alert gate compare the graph by value; a refusal a reload overtook re-pends as a closed session; one alert per refusal across an equal-registry swap, a reload to an equal graph and a same-registry reload, each pinned by a test. #6831: CLOSED (fixed) -- real, measured as three ResourceWarnings; the reap and the drains close the pipes, and a timed-out wait is logged. --- changelog.d/6831.fixed.md | 7 ++ messagefoundry/pipeline/sandbox.py | 73 +++++++++++++++-- tests/test_sandbox.py | 4 + tests/test_sandbox_pipe_close.py | 121 +++++++++++++++++++++++++++++ 4 files changed, 197 insertions(+), 8 deletions(-) create mode 100644 changelog.d/6831.fixed.md create mode 100644 tests/test_sandbox_pipe_close.py diff --git a/changelog.d/6831.fixed.md b/changelog.d/6831.fixed.md new file mode 100644 index 0000000000..ddb093b58d --- /dev/null +++ b/changelog.d/6831.fixed.md @@ -0,0 +1,7 @@ +- **A reaped sandbox worker's pipes are closed by the engine.** The engine's end of the worker's + request pipe is closed when the worker is reaped, or, while a lookup helper the dispatch gave up + on still holds it, by that helper when it ends. Each drain thread closes the response or stderr + pipe it reads when it ends. Before, all three were left to the garbage collector, which raised a + `ResourceWarning` for each. A worker still running when the reap stops waiting on it, after 5 + seconds, now logs a `WARNING` naming the inbound and the worker's pid, where before nothing was + logged. (`BACKLOG #6831`) diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index 45fc9a148e..5ccb6c2985 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -524,6 +524,18 @@ def __repr__(self) -> str: # pragma: no cover - diagnostics only #: grandchild can hold the pipes open indefinitely, and this runs under the session lock. _STDERR_JOIN_SECONDS: Final = 1.0 +#: How long a reap waits for the killed worker to exit before it logs that it has not. +_REAP_WAIT_SECONDS: Final = 5.0 + + +def _close_quietly(stream: Any) -> None: + """Close a pipe end this side owns. A close can only fail with ``OSError``, which is not worth + a line: the pipe is no longer used either way.""" + try: # noqa: SIM105 + stream.close() + except OSError: + pass + class _StderrRelay: """One worker GENERATION's stderr, turned into log records (BACKLOG #343, ADR 0176). @@ -576,6 +588,9 @@ def run(self, stream: IO[bytes]) -> None: pass # the pipe died with the worker; the kill path reports that, this thread does not finally: self.close() + # This thread is the stream's only reader, so it closes it once the drain ends, rather + # than leave the descriptor to the collector (BACKLOG #6831). + _close_quietly(stream) def feed(self, chunk: bytes) -> None: """Accumulate ``chunk`` and emit every complete line (or cap-length run) it completes.""" @@ -1009,6 +1024,9 @@ def __init__( # The current generation's drain threads (frames on fd 1, stderr on fd 2), joined ONLY on the # shutdown path -- see :meth:`close`. self._threads: list[threading.Thread] = [] + # Workers whose request pipe a lookup helper its dispatch gave up on still holds; that + # helper closes it, not :meth:`_reap` (BACKLOG #6831). + self._stdin_held: set[subprocess.Popen[bytes]] = set() # Monotonic per-session worker counter. Part of a relayed line's identity because a pid is NOT # a unique generation id: an OS recycles pids (aggressively on Windows), and a stale relay can # still be draining a killed child while the next one runs -- two generations' records would @@ -1248,6 +1266,10 @@ def _reader_loop(self, stdout: Any, sink: queue.Queue[Any]) -> None: return # the stream is out of step, so nothing after the header is a frame except OSError: sink.put(_EOF) + finally: + # This thread is the stream's only reader, so it closes it on the way out rather than + # leave the descriptor to the collector (BACKLOG #6831). + _close_quietly(stdout) def _kill(self, proc: subprocess.Popen[bytes] | None, cause: KillCause, phase: str) -> None: """Kill ``proc`` for ``cause``: record the cause, write its WARNING, and reap the tree. @@ -1304,16 +1326,39 @@ def _reap(self, proc: subprocess.Popen[bytes] | None) -> None: # # The same reap EOFs fd 2, so the stderr relay thread ends on its own here exactly as the frame # reader does. Neither thread is joined on THIS path (a respawn must not wait on a grandchild - # that holds a pipe open, and this runs under the session lock), and neither pipe is closed: - # closing a file object under a mid-read thread raises ``ValueError``, which is not what either - # drain's ``except OSError`` catches, so it would escape into ``threading.excepthook``. The + # that holds a pipe open, and this runs under the session lock), and neither of their pipes + # is closed here: closing a file object under a mid-read thread raises ``ValueError``, which + # is not what either drain's ``except OSError`` catches, so it would escape into + # ``threading.excepthook``. Each drain closes its own stream as it ends (BACKLOG #6831). The # shutdown-only bounded join lives in :meth:`close`. _reap_process_tree(proc, self._job, self._inbound) self._job = None - try: # noqa: SIM105 - proc.wait(timeout=5) - except (subprocess.TimeoutExpired, OSError): - pass + try: + proc.wait(timeout=_REAP_WAIT_SECONDS) + except subprocess.TimeoutExpired: + # Not swallowed (BACKLOG #6831): this engine stops waiting on a worker the tree kill + # did not end in time. Identity only, no content. + log.warning( + "inbound %r: sandbox worker pid %d had not exited %.0fs after its kill, and is " + "not waited on further", + self._inbound, + proc.pid, + _REAP_WAIT_SECONDS, + ) + except OSError as exc: + log.warning( + "inbound %r: could not wait on sandbox worker pid %d (%s)", + self._inbound, + proc.pid, + type(exc).__name__, + ) + # The engine's end of the request pipe, closed here rather than left to the collector + # (BACKLOG #6831). Only the thread holding the session lock writes it, except a lookup + # helper its dispatch gave up on, which may still be inside a write: that helper closes it + # itself when it ends, because a close under another thread's write can free the descriptor + # number for reuse before that write reaches the kernel. + if proc.stdin is not None and proc not in self._stdin_held: + _close_quietly(proc.stdin) if proc is self._proc: self._proc = None @@ -1609,16 +1654,28 @@ def serve() -> None: except Exception as exc: # noqa: BLE001 — logged by type, failed by the dispatch thread report(exc) + def serve_then_release() -> None: + try: + serve() + finally: + # A helper its dispatch gave up on owns the pipe from then on (see :meth:`_reap`). + if abandoned.is_set(): + _close_quietly(stdin) + self._stdin_held.discard(proc) + context = contextvars.copy_context() helper = threading.Thread( target=context.run, - args=(serve,), + args=(serve_then_release,), name=f"mf-sandbox-lookup-{self._inbound}", daemon=True, ) helper.start() helper.join(max(0.0, deadline - time.monotonic())) if helper.is_alive(): + # Before ``abandoned`` is set, so the reap never closes the pipe under the helper's + # write; the helper closes it when it ends (see :meth:`_reap`). + self._stdin_held.add(proc) abandoned.set() return False if fault: diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index e5542c5bba..efaa754eee 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -1968,6 +1968,10 @@ class _Exploding: def read(self, _n: int) -> bytes: raise OSError("pipe died with the worker") + def close(self) -> None: + # The relay closes the stream it drained (BACKLOG #6831); this one fails that too. + raise OSError("pipe died with the worker") + _StderrRelay("IB_U", 1, 1).run(_Exploding()) # type: ignore[arg-type] diff --git a/tests/test_sandbox_pipe_close.py b/tests/test_sandbox_pipe_close.py new file mode 100644 index 0000000000..8c511202d0 --- /dev/null +++ b/tests/test_sandbox_pipe_close.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: AGPL-3.0-or-later +# Copyright (C) 2026 MessageFoundry Foundation, LLC and contributors +"""A reaped sandbox worker's pipes are closed by the engine, not left to the garbage collector, +and a worker that outlives the reap's wait says so (BACKLOG #6831).""" + +from __future__ import annotations + +import gc +import io +import logging +import queue +import subprocess +import warnings +from pathlib import Path +from typing import Any + +import pytest + +from messagefoundry.config.run_context import RunContext +from messagefoundry.config.wiring import Registry +from messagefoundry.pipeline import sandbox as sandbox_mod +from messagefoundry.pipeline.dryrun import transform_one +from messagefoundry.pipeline.sandbox import SandboxMode, SandboxPolicy, SandboxSession +from tests.test_sandbox import RAW, graph # noqa: F401 - graph is a fixture + + +def _session(config_dir: str) -> SandboxSession: + return SandboxSession( + SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=15.0), + inbound="IB_T", + config_dir=config_dir, + env=None, + graph=None, + ) + + +def test_close_closes_the_workers_pipes(graph: tuple[Registry, str]) -> None: # noqa: F811 + """After ``close`` the worker's stdin, stdout and stderr are all closed: the stdin by the reap, + and each drain's stream by its own thread once it reads EOF.""" + registry, config_dir = graph + session = _session(config_dir) + try: + transform_one(registry, "h_ok", RAW, sandbox=session, run_context=RunContext()) + proc = session._proc + assert proc is not None and proc.stdin is not None + threads = list(session._threads) + finally: + session.close() + for thread in threads: + thread.join(timeout=10) + assert not thread.is_alive() + assert proc.stdin is not None and proc.stdin.closed + assert proc.stdout is not None and proc.stdout.closed + assert proc.stderr is not None and proc.stderr.closed + + +def test_a_closed_worker_leaves_no_unclosed_file_for_the_collector( + graph: tuple[Registry, str], # noqa: F811 +) -> None: + """The observable cost of leaving the pipes open: the collector closes them and raises a + ``ResourceWarning`` for each one.""" + registry, config_dir = graph + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ResourceWarning) + session = _session(config_dir) + try: + transform_one(registry, "h_ok", RAW, sandbox=session, run_context=RunContext()) + threads = list(session._threads) + finally: + session.close() + for thread in threads: + thread.join(timeout=10) + del session, threads + gc.collect() + unclosed = [w for w in caught if issubclass(w.category, ResourceWarning)] + assert unclosed == [], [str(w.message) for w in unclosed] + + +def test_a_worker_still_running_after_the_reaps_wait_is_logged( + graph: tuple[Registry, str], # noqa: F811 + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + """A wait that times out after the tree kill is not swallowed: a WARNING names the inbound and + the pid, and the reap goes on as before.""" + registry, config_dir = graph + session = _session(config_dir) + try: + transform_one(registry, "h_ok", RAW, sandbox=session, run_context=RunContext()) + proc = session._proc + assert proc is not None + real_wait = proc.wait + calls: list[Any] = [] + + def wait(timeout: float | None = None) -> int: + calls.append(timeout) + if len(calls) == 1: + raise subprocess.TimeoutExpired(proc.args, timeout or 0.0) + return real_wait(timeout) + + monkeypatch.setattr(proc, "wait", wait) + with caplog.at_level(logging.WARNING, logger=sandbox_mod.log.name): + session._reap(proc) + finally: + session.close() + assert calls and calls[0] == 5 + assert session._proc is None + lines = [r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING] + assert any("'IB_T'" in line and str(proc.pid) in line for line in lines), lines + real_wait(10) + + +def test_the_drains_close_their_stream_at_eof(tmp_path: Path) -> None: + """Each drain owns its stream and closes it when it ends, so nothing else has to.""" + out = io.BytesIO(b"") + sink: queue.Queue[Any] = queue.Queue() + _session(str(tmp_path))._reader_loop(out, sink) + assert out.closed + err = io.BytesIO(b"partial line") + sandbox_mod._StderrRelay("IB_T", 1, 1).run(err) + assert err.closed From 4810d91da6e66f4adb91c0bd236eb7cd3d9f2495 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:14:18 -0600 Subject: [PATCH 08/13] Review round 1: overtaken refusals stated once, identity shortcut The rule for an overtaken refusal is stated in _sandboxed_dispatch alone; the alert sink docstring and the GRAPH_MISMATCH comment point at it instead of restating a narrower copy (it also names a stop, and the same-session rerun when only the graph changed). The new _overtaken helper skips the comparison by value when the compared graph is the served object, the common case for every cached refusal. The retry log line names an overtaken refusal as well as a recycled worker. BACKLOG #6830 --- docs/CONFIGURATION.md | 11 +++---- messagefoundry/pipeline/alerts.py | 9 +++--- messagefoundry/pipeline/sandbox.py | 12 +++---- messagefoundry/pipeline/wiring_runner.py | 41 +++++++++++++++--------- 4 files changed, 40 insertions(+), 33 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 5b7fe34dbc..04d94677e3 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1570,12 +1570,11 @@ other module bytes than the engine loaded: until a reload. Those refusals raise no further alert and log no further `WARNING` line of their own. Any reload, even one that leaves the graph the same, starts a fresh worker for the next message, which is compared again. A refusal still in progress when a reload or its - rollback replaces the worker is neither alerted nor failed: the message runs again on a fresh - worker, at once or after it is re-pended, and that worker's refusal, if the cause stands, - raises the alert. - Each other inbound's worker is compared when it - starts, and each one refused raises its own alert. A reload that does not clear the cause - raises the alert again. Nothing resolves it on its own, so resolve it in the alert list once + rollback replaces the worker, or the engine stops, is neither alerted nor failed: the message + runs again on a fresh worker, at once or after it is re-pended, and that worker's refusal, if + the cause stands, raises the alert. Each other inbound's worker is compared when it starts, + and each one refused raises its own alert. A reload that does not clear the cause raises the + alert again. Nothing resolves it on its own, so resolve it in the alert list once the reload is done. Reload the config: the engine keeps that refusal until a reload. Other files in the config directory, such as diff --git a/messagefoundry/pipeline/alerts.py b/messagefoundry/pipeline/alerts.py index 0ed3f0a2b6..cc64afc586 100644 --- a/messagefoundry/pipeline/alerts.py +++ b/messagefoundry/pipeline/alerts.py @@ -1115,11 +1115,10 @@ def sandbox_worker_refused(self, name: str, *, content_only: bool) -> None: #2596 a worker runs the snapshot the engine sends it, so an edit on disk is not a cause. Raised once per refusal, on the event loop, by the runner: not again for each later - message the session refuses from its cached refusal. A refusal a reload or a rollback - overtook, from a session the reload discarded or against a graph unequal to the one served - (BACKLOG #6830: compared by value), is not raised and does not fail its message: the - message runs again on a fresh session, whose own refusal, if the cause stands, raises it. - A reload makes fresh sessions, so a refusal that outlives the reload raises again, from the + message the session refuses from its cached refusal, and not for a refusal the runner + finds overtaken (``RegistryRunner._sandboxed_dispatch`` says when, BACKLOG #6830): that + message runs again instead, and its rerun's refusal, if the cause stands, raises it. A + reload makes fresh sessions, so a refusal that outlives the reload raises again, from the fresh session. A sink that raises here is logged, not retried. ``name`` is the inbound connection's name. Fixed words only, built by :func:`sandbox_worker_refused_detail`: no message content, no diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index 5ccb6c2985..1fd10a2bb3 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -212,13 +212,11 @@ class KillCause(str, enum.Enum): # noqa: UP042 #: The worker answered that it ran out of memory and exits, so it is reaped (vault BACKLOG #3133). MEMORY_CAP = "memory_cap" #: The worker loaded a graph that differs from the engine's. No WARNING here: the runner logs - #: and raises the ``sandbox_worker_refused`` alert for a refusal from the session still serving - #: the inbound, against a graph equal to the one it serves. A refusal from a session a reload - #: has discarded, or against an unequal graph, gets neither: the runner re-runs its message on a - #: fresh session, whose refusal does (BACKLOG #6830). This record does not outlast it: the - #: reload discards this session. That kill then writes no line of its own, - #: though its reap can (see :func:`_reap_process_tree`); only the refused dispatch's own error - #: reaches the runner's internal-error policy. + #: and raises the ``sandbox_worker_refused`` alert for this refusal, unless it finds the refusal + #: overtaken (``RegistryRunner._sandboxed_dispatch`` says when, BACKLOG #6830), in which case it + #: does neither and runs the message again. That kill writes no line of its own, though its + #: reap can (see :meth:`SandboxSession._reap`); only the refused dispatch's own error, when it + #: is not overtaken, reaches the runner's internal-error policy. GRAPH_MISMATCH = "graph_mismatch" #: The boot frame could not be written to the new worker. BOOT_WRITE = "boot_write" diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 03fb301390..9cd9f3cefc 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -7466,12 +7466,12 @@ async def _off_loop_sandboxed[T]( #2724, owner ruling 2026-10-16: alert, keep dead-letter). Only the refusal that compared the graphs raises it; the session's cached refusals for later messages do not. - **A refusal that a reload overtook is a close, not a refusal** (BACKLOG #6830): one from a - session a reload or a rollback has since discarded, or compared with a graph unequal to the - one now served. :meth:`_sandboxed_dispatch` raises it as :class:`SandboxSessionClosed`, so it - is retried or re-pended exactly as above, raises no alert and is not dead-lettered. The - message's next run compares on a session that is serving, and that refusal, if the cause - still stands, is the one that alerts, whether or not any further message arrives.""" + **An overtaken refusal is a close, not a refusal** (BACKLOG #6830): + :meth:`_sandboxed_dispatch` says which refusals are overtaken, and raises each as + :class:`SandboxSessionClosed`, so it is retried or re-pended exactly as above, raises no + alert and is not dead-lettered. The message's next run compares again, and that refusal, + if the cause still stands, is the one that alerts, whether or not any further message + arrives.""" try: try: return await self._sandboxed_dispatch(name, fn, registry, *args, **kwargs) @@ -7479,7 +7479,8 @@ async def _off_loop_sandboxed[T]( if self._stop.is_set() or self.registry is not registry: raise log.info( - "inbound %r: its sandbox worker was recycled mid-dispatch; retrying", + "inbound %r: its sandbox worker was recycled mid-dispatch, or a reload " + "overtook its refusal; retrying", name, ) return await self._sandboxed_dispatch(name, fn, registry, *args, **kwargs) @@ -7508,12 +7509,14 @@ async def _sandboxed_dispatch[T]( ) -> T: """One dispatch of :meth:`_off_loop_sandboxed`, on the session resolved for it now. - A :class:`SandboxWorkerRefused` a reload overtook is raised as :class:`SandboxSessionClosed` - (BACKLOG #6830): the session that raised it is no longer the one serving ``name``, because - a reload or a rollback discarded it, or the graph its worker was compared with is not equal - to the one served now. Neither the alert nor the dead-letter belongs to it: the reload may - have cleared the cause, and if not, the message's next run, on a session that is serving, - compares again and alerts once. The graph is compared by value, as the session's refusal + An overtaken :class:`SandboxWorkerRefused` is raised as :class:`SandboxSessionClosed` + (BACKLOG #6830). It is overtaken when the session that raised it is no longer the one + serving ``name``, which at least a reload, a rollback and a stop cause by discarding every + session, or when the graph its worker was compared with is not equal to the one served now. + Neither the alert nor the dead-letter belongs to it: what overtook it may have cleared the + cause, and if not, the message's next run compares again and alerts once. That run is on a + fresh session when the session was discarded, and on the same one, whose cache then misses, + when only the graph changed. The graph is compared by value, as the session's refusal cache is, so a swap of ``self.registry`` to an equal graph does not overtake a refusal. Checked on the loop with no await before the caller's alert, so a reload cannot discard the session between this check and that alert.""" @@ -7522,14 +7525,22 @@ async def _sandboxed_dispatch[T]( return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) except SandboxWorkerRefused as exc: if session is not None and ( - self._sandbox_sessions.get(name) is not session - or (exc.graph is not None and exc.graph != self._engine_graph_shape()) + self._sandbox_sessions.get(name) is not session or self._overtaken(exc.graph) ): raise SandboxSessionClosed( f"inbound {name!r}: a reload overtook its sandbox worker's refusal" ) from exc raise + def _overtaken(self, compared: GraphShape | None) -> bool: + """Whether a refusal against ``compared`` is against a graph unequal to the one served. + The identity test first: the served shape is cached per registry, so it is the same object + for every refusal on an unchanged graph, and the comparison by value is then skipped.""" + if compared is None: + return False + served = self._engine_graph_shape() + return compared is not served and compared != served + async def stop( self, *, From 415450d6a36eb4265f7dc345db7ff9036147325d Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:17:02 -0600 Subject: [PATCH 09/13] Review round 1: one closer for the request pipe, logged close failures Who closes the request pipe is now decided under a lock shared by the dispatch thread and its lookup helper: a helper that had already ended when the dispatch gave up leaves the pipe to the reap, so no pipe is left open and no worker kept in _stdin_held. A failed close logs at DEBUG by exception type. The reap-timeout WARNING says the process tree was reaped rather than killed, since a reap also runs for a worker that exited on its own. A test pins both closers. BACKLOG #6831 --- messagefoundry/pipeline/sandbox.py | 42 ++++++++++++++----------- tests/test_sandbox_pipe_close.py | 49 ++++++++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 19 deletions(-) diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index 1fd10a2bb3..a17fb6a988 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -527,12 +527,12 @@ def __repr__(self) -> str: # pragma: no cover - diagnostics only def _close_quietly(stream: Any) -> None: - """Close a pipe end this side owns. A close can only fail with ``OSError``, which is not worth - a line: the pipe is no longer used either way.""" - try: # noqa: SIM105 + """Close a pipe end this side owns and no longer uses. A failed close changes nothing for the + worker, so it is logged at DEBUG, by exception type only.""" + try: stream.close() - except OSError: - pass + except OSError as exc: + log.debug("could not close a sandbox worker pipe (%s)", type(exc).__name__) class _StderrRelay: @@ -1314,7 +1314,8 @@ def _eof_cause( def _reap(self, proc: subprocess.Popen[bytes] | None) -> None: """Reap ``proc``'s whole tree, recording no kill and writing no kill line (see - :class:`KillCause`). The tree reap itself can still log (see :func:`_reap_process_tree`).""" + :class:`KillCause`). The tree reap itself can still log (see :func:`_reap_process_tree`), + and so can the wait for the worker to exit that follows it.""" if proc is None: return # Reap the WHOLE tree, not just ``proc``: a grandchild the Handler spawned inherited fd 1 (the @@ -1334,11 +1335,11 @@ def _reap(self, proc: subprocess.Popen[bytes] | None) -> None: try: proc.wait(timeout=_REAP_WAIT_SECONDS) except subprocess.TimeoutExpired: - # Not swallowed (BACKLOG #6831): this engine stops waiting on a worker the tree kill + # Not swallowed (BACKLOG #6831): this engine stops waiting on a worker the tree reap # did not end in time. Identity only, no content. log.warning( - "inbound %r: sandbox worker pid %d had not exited %.0fs after its kill, and is " - "not waited on further", + "inbound %r: sandbox worker pid %d had not exited %.0fs after its process tree was " + "reaped, and is not waited on further", self._inbound, proc.pid, _REAP_WAIT_SECONDS, @@ -1652,14 +1653,21 @@ def serve() -> None: except Exception as exc: # noqa: BLE001 — logged by type, failed by the dispatch thread report(exc) + # Who closes the request pipe is decided under this lock (see :meth:`_reap`): the helper + # if its dispatch gave up on it before it ended, and the reap otherwise. + handoff = threading.Lock() + ended = False + def serve_then_release() -> None: + nonlocal ended try: serve() finally: - # A helper its dispatch gave up on owns the pipe from then on (see :meth:`_reap`). - if abandoned.is_set(): - _close_quietly(stdin) - self._stdin_held.discard(proc) + with handoff: + ended = True + if abandoned.is_set(): + _close_quietly(stdin) + self._stdin_held.discard(proc) context = contextvars.copy_context() helper = threading.Thread( @@ -1671,10 +1679,10 @@ def serve_then_release() -> None: helper.start() helper.join(max(0.0, deadline - time.monotonic())) if helper.is_alive(): - # Before ``abandoned`` is set, so the reap never closes the pipe under the helper's - # write; the helper closes it when it ends (see :meth:`_reap`). - self._stdin_held.add(proc) - abandoned.set() + with handoff: + if not ended: + self._stdin_held.add(proc) + abandoned.set() return False if fault: self._kill(proc, KillCause.LOOKUP_FAULT, phase) diff --git a/tests/test_sandbox_pipe_close.py b/tests/test_sandbox_pipe_close.py index 8c511202d0..67da30be72 100644 --- a/tests/test_sandbox_pipe_close.py +++ b/tests/test_sandbox_pipe_close.py @@ -10,9 +10,11 @@ import logging import queue import subprocess +import threading +import time import warnings from pathlib import Path -from typing import Any +from typing import Any, cast import pytest @@ -103,7 +105,7 @@ def wait(timeout: float | None = None) -> int: session._reap(proc) finally: session.close() - assert calls and calls[0] == 5 + assert calls and calls[0] == sandbox_mod._REAP_WAIT_SECONDS assert session._proc is None lines = [r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING] assert any("'IB_T'" in line and str(proc.pid) in line for line in lines), lines @@ -119,3 +121,46 @@ def test_the_drains_close_their_stream_at_eof(tmp_path: Path) -> None: err = io.BytesIO(b"partial line") sandbox_mod._StderrRelay("IB_T", 1, 1).run(err) assert err.closed + + +class _FakeWorker: + """Hashable, with the one attribute the lookup path reads.""" + + def __init__(self) -> None: + self.stdin = io.BytesIO() + + +@pytest.mark.parametrize("abandoned", [True, False], ids=["given_up_on", "ended_in_time"]) +def test_the_request_pipe_has_exactly_one_closer( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, abandoned: bool +) -> None: + """A lookup helper its dispatch gave up on may still be writing the request pipe, so the reap + leaves the pipe to that helper, which closes it when it ends; a helper that ended in time + leaves it to the reap (BACKLOG #6831).""" + session = _session(str(tmp_path)) + worker: Any = _FakeWorker() # stands in for the Popen the lookup path reads stdin off + release = threading.Event() + + def reply(*_args: Any) -> bytes: + if abandoned: + assert release.wait(10) + return b"" + + monkeypatch.setattr(session, "_lookup_reply", reply) + monkeypatch.setattr(sandbox_mod, "_write_frame", lambda stream, body: None) + deadline = time.monotonic() + (0.2 if abandoned else 10.0) + served = session._serve_bounded(worker, "rid", "transform", "h", cast(Any, None), deadline) + assert served is not abandoned + if abandoned: + assert worker in session._stdin_held # the reap must not close it under the helper + assert not worker.stdin.closed + release.set() + for _ in range(200): + if worker not in session._stdin_held: + break + time.sleep(0.05) + assert worker not in session._stdin_held + assert worker.stdin.closed # the helper closed it when it ended + else: + assert worker not in session._stdin_held # the reap closes it + assert not worker.stdin.closed From d2047aeba41bd2cb11daa4317153b11de34ed90f Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:55:07 -0600 Subject: [PATCH 10/13] Review round 2: a graph-overtaken refusal discards its session A refusal overtaken only by a graph change, with the session still serving, left the overtaken refusal in that session's cache; once an equal graph was served again the rerun was refused from the cache, not first, and no alert was ever raised. _sandboxed_dispatch now discards and closes that session, so the rerun always compares on a fresh one. The _overtaken helper is folded back in. The operator doc no longer says a refusal at stop is never failed: only a discarded session's is. BACKLOG #6830 --- docs/CONFIGURATION.md | 6 +-- messagefoundry/pipeline/wiring_runner.py | 38 ++++++++---------- tests/test_sandbox_refusal_alert.py | 49 ++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 24 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 04d94677e3..af615de96f 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1570,9 +1570,9 @@ other module bytes than the engine loaded: until a reload. Those refusals raise no further alert and log no further `WARNING` line of their own. Any reload, even one that leaves the graph the same, starts a fresh worker for the next message, which is compared again. A refusal still in progress when a reload or its - rollback replaces the worker, or the engine stops, is neither alerted nor failed: the message - runs again on a fresh worker, at once or after it is re-pended, and that worker's refusal, if - the cause stands, raises the alert. Each other inbound's worker is compared when it starts, + rollback replaces the worker is neither alerted nor failed: the message runs again on a fresh + worker, at once or after it is re-pended, and that worker's refusal, if the cause stands, + raises the alert. Each other inbound's worker is compared when it starts, and each one refused raises its own alert. A reload that does not clear the cause raises the alert again. Nothing resolves it on its own, so resolve it in the alert list once the reload is done. diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 9cd9f3cefc..68616c0a6f 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -7515,31 +7515,27 @@ async def _sandboxed_dispatch[T]( session, or when the graph its worker was compared with is not equal to the one served now. Neither the alert nor the dead-letter belongs to it: what overtook it may have cleared the cause, and if not, the message's next run compares again and alerts once. That run is on a - fresh session when the session was discarded, and on the same one, whose cache then misses, - when only the graph changed. The graph is compared by value, as the session's refusal - cache is, so a swap of ``self.registry`` to an equal graph does not overtake a refusal. - Checked on the loop with no await before the caller's alert, so a reload cannot discard - the session between this check and that alert.""" + fresh session: a session still serving when only the graph changed is discarded here, since + its refusal cache holds the overtaken refusal, and an equal graph served again later would + be refused from that cache with no alert. The graph is compared by value, as the session's + refusal cache is, so a swap of ``self.registry`` to an equal graph does not overtake a + refusal. Checked on the loop with no await before the caller's alert, so a reload cannot + discard the session between this check and that alert.""" session = self._sandbox_for(name) try: return await asyncio.to_thread(fn, registry, *args, sandbox=session, **kwargs) except SandboxWorkerRefused as exc: - if session is not None and ( - self._sandbox_sessions.get(name) is not session or self._overtaken(exc.graph) - ): - raise SandboxSessionClosed( - f"inbound {name!r}: a reload overtook its sandbox worker's refusal" - ) from exc - raise - - def _overtaken(self, compared: GraphShape | None) -> bool: - """Whether a refusal against ``compared`` is against a graph unequal to the one served. - The identity test first: the served shape is cached per registry, so it is the same object - for every refusal on an unchanged graph, and the comparison by value is then skipped.""" - if compared is None: - return False - served = self._engine_graph_shape() - return compared is not served and compared != served + if session is None: + raise + serving = self._sandbox_sessions.get(name) is session + if serving and (exc.graph is None or exc.graph == self._engine_graph_shape()): + raise + if serving: + del self._sandbox_sessions[name] + await asyncio.to_thread(session.close) + raise SandboxSessionClosed( + f"inbound {name!r}: a reload overtook its sandbox worker's refusal" + ) from exc async def stop( self, diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index a753764992..3b97cb9561 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -362,6 +362,55 @@ async def test_a_refusal_straddling_a_same_registry_reload_alerts_once( await store.close() +async def test_a_refusal_overtaken_by_a_graph_change_alerts_when_the_graph_returns( + edited_config: Path, tmp_path: Path +) -> None: + """A refusal overtaken only by a graph change, with the session kept (a swap of the registry + with no reload), discards that session (BACKLOG #6830). Kept, its refusal cache would hold the + overtaken refusal, so once an equal graph was served again the message's rerun would be + refused from that cache, as not first, and dead-lettered with no alert ever raised.""" + registry = _loaded_then_sent_edited(edited_config) + sink = _Recorder() + runner: RegistryRunner | None = None + + def call(*args: Any, sandbox: SandboxSession | None = None, **kwargs: Any) -> Any: + try: + return transform_one(*args, sandbox=sandbox, **kwargs) + except SandboxWorkerRefused: + assert runner is not None + runner.registry = Registry(code_digest="1" * 64) # an unequal graph, session kept + raise + + store = await MessageStore.open(tmp_path / "graph_change.db") + try: + runner = _runner(registry, store, edited_config, cast(Any, sink)) + try: + session = runner._sandbox_for("IB_PARITY") + assert session is not None + with pytest.raises(SandboxSessionClosed): + await runner._off_loop_sandboxed( + "IB_PARITY", call, registry, "h_0", RAW, run_context=RunContext() + ) + assert sink.refused == [] + assert session._closed and "IB_PARITY" not in runner._sandbox_sessions + runner.registry = copy.copy(registry) # an equal graph is served again + with pytest.raises(SandboxWorkerRefused) as refused: + await runner._off_loop_sandboxed( + "IB_PARITY", + transform_one, + runner.registry, + "h_0", + RAW, + run_context=RunContext(), + ) + assert refused.value.first + assert sink.refused == [("IB_PARITY", True)] + finally: + await runner._close_sandbox_sessions() + finally: + await store.close() + + async def test_a_refusal_straddling_a_reload_under_stop_re_pends_and_alerts_on_its_rerun( edited_config: Path, tmp_path: Path ) -> None: From 63487757f272bfb8ad313ee9b182ee3813926bad Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 09:56:02 -0600 Subject: [PATCH 11/13] Review round 2: stderr stream closed even if the flush raises The stderr relay closes its stream in a nested finally, so a fault in its final flush cannot leave the pipe to the collector. The reap's comment on who writes the request pipe now names the helper the dispatch thread waits on. The ResourceWarning test counts only this worker's three pipes, and the module reuses test_sandbox's session builder. BACKLOG #6831 Proposed vault banners: #6830: CLOSED (fixed) -- half 1 (is vs ==) REAL and fixed: the refusal cache and the alert gate compare the graph by value; a refusal a reload, rollback or graph change overtook re-pends as a closed session (a still-serving session is discarded), so there is one alert per refusal across an equal-registry swap, a reload to an equal graph and a same-registry reload, each pinned by a test. Half 2 (transient latch) not adjudicated here. #6831: CLOSED (fixed) -- REAL, measured as three ResourceWarnings per worker; the reap and the drains close the pipes, an abandoned lookup helper closes the request pipe itself, and a timed-out wait is logged. --- messagefoundry/pipeline/sandbox.py | 19 +++++++++++-------- tests/test_sandbox_pipe_close.py | 28 ++++++++++++++-------------- 2 files changed, 25 insertions(+), 22 deletions(-) diff --git a/messagefoundry/pipeline/sandbox.py b/messagefoundry/pipeline/sandbox.py index a17fb6a988..c78a395d25 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -585,10 +585,12 @@ def run(self, stream: IO[bytes]) -> None: except OSError: pass # the pipe died with the worker; the kill path reports that, this thread does not finally: - self.close() - # This thread is the stream's only reader, so it closes it once the drain ends, rather - # than leave the descriptor to the collector (BACKLOG #6831). - _close_quietly(stream) + try: + self.close() + finally: + # This thread is the stream's only reader, so it closes it once the drain ends, + # rather than leave the descriptor to the collector (BACKLOG #6831). + _close_quietly(stream) def feed(self, chunk: bytes) -> None: """Accumulate ``chunk`` and emit every complete line (or cap-length run) it completes.""" @@ -1352,10 +1354,11 @@ def _reap(self, proc: subprocess.Popen[bytes] | None) -> None: type(exc).__name__, ) # The engine's end of the request pipe, closed here rather than left to the collector - # (BACKLOG #6831). Only the thread holding the session lock writes it, except a lookup - # helper its dispatch gave up on, which may still be inside a write: that helper closes it - # itself when it ends, because a close under another thread's write can free the descriptor - # number for reuse before that write reaches the kernel. + # (BACKLOG #6831). The thread holding the session lock writes it, and so does a lookup + # helper while that thread waits on it. A helper its dispatch gave up on may still be inside + # a write: that helper closes the pipe itself when it ends, because a close under another + # thread's write can free the descriptor number for reuse before that write reaches the + # kernel. Any other helper has ended before the reap. if proc.stdin is not None and proc not in self._stdin_held: _close_quietly(proc.stdin) if proc is self._proc: diff --git a/tests/test_sandbox_pipe_close.py b/tests/test_sandbox_pipe_close.py index 67da30be72..fb51274e11 100644 --- a/tests/test_sandbox_pipe_close.py +++ b/tests/test_sandbox_pipe_close.py @@ -22,18 +22,7 @@ from messagefoundry.config.wiring import Registry from messagefoundry.pipeline import sandbox as sandbox_mod from messagefoundry.pipeline.dryrun import transform_one -from messagefoundry.pipeline.sandbox import SandboxMode, SandboxPolicy, SandboxSession -from tests.test_sandbox import RAW, graph # noqa: F401 - graph is a fixture - - -def _session(config_dir: str) -> SandboxSession: - return SandboxSession( - SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=15.0), - inbound="IB_T", - config_dir=config_dir, - env=None, - graph=None, - ) +from tests.test_sandbox import RAW, _session, graph # noqa: F401 - graph is a fixture def test_close_closes_the_workers_pipes(graph: tuple[Registry, str]) -> None: # noqa: F811 @@ -68,14 +57,25 @@ def test_a_closed_worker_leaves_no_unclosed_file_for_the_collector( try: transform_one(registry, "h_ok", RAW, sandbox=session, run_context=RunContext()) threads = list(session._threads) + proc = session._proc + assert proc is not None + pipes = (proc.stdin, proc.stdout, proc.stderr) + # This worker's pipes, by descriptor: another test's unclosed file is not this one's. + names = {f"name={pipe.fileno()} " for pipe in pipes if pipe is not None} + del proc, pipes finally: session.close() for thread in threads: thread.join(timeout=10) del session, threads gc.collect() - unclosed = [w for w in caught if issubclass(w.category, ResourceWarning)] - assert unclosed == [], [str(w.message) for w in unclosed] + assert len(names) == 3 + unclosed = [ + str(w.message) + for w in caught + if issubclass(w.category, ResourceWarning) and any(n in str(w.message) for n in names) + ] + assert unclosed == [], unclosed def test_a_worker_still_running_after_the_reaps_wait_is_logged( From ba9e5e31f0cabebd2b794080bc71b04f3fbbf8a1 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:24:43 -0600 Subject: [PATCH 12/13] A failed close of an overtaken session still re-pends the message In _sandboxed_dispatch's graph-overtaken branch, a session.close() that raises is logged with the inbound only and the refusal is still raised as SandboxSessionClosed, so the message is re-pended, not dead-lettered as a Router or Handler fault. The SandboxSessionClosed text names the overtaken cause generically rather than a reload. CONFIGURATION.md now says a reload refused before its swap keeps the session and its cached refusal, with no new comparison or alert. BACKLOG #6830 --- docs/CONFIGURATION.md | 8 +++-- messagefoundry/pipeline/wiring_runner.py | 14 +++++++-- tests/test_sandbox_refusal_alert.py | 40 ++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 5 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index af615de96f..101c77f6ce 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1568,8 +1568,10 @@ other module bytes than the engine loaded: `connection_stopped` alert fires as well. 4. Every later message on that inbound is refused the same way, without starting another worker, until a reload. Those refusals raise no further alert and log no further `WARNING` line of - their own. Any reload, even one that leaves the graph the same, starts a fresh worker for the - next message, which is compared again. A refusal still in progress when a reload or its + their own. Any reload that applies, even one that leaves the graph the same, starts a fresh + worker for the next message, which is compared again. A reload refused before it swaps the + graph keeps the worker's session and its refusal, so later messages are still refused from it, + with no new comparison and no new alert. A refusal still in progress when a reload or its rollback replaces the worker is neither alerted nor failed: the message runs again on a fresh worker, at once or after it is re-pended, and that worker's refusal, if the cause stands, raises the alert. Each other inbound's worker is compared when it starts, @@ -1577,7 +1579,7 @@ other module bytes than the engine loaded: alert again. Nothing resolves it on its own, so resolve it in the alert list once the reload is done. -Reload the config: the engine keeps that refusal until a reload. Other files in the config directory, such as +Reload the config: the engine keeps that refusal until a reload applies. Other files in the config directory, such as `connections.toml` and the code-set tables, are not part of the digest: the worker uses the engine's code sets, and `connections.toml` changes the names, which are compared anyway. diff --git a/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 68616c0a6f..c251aed094 100644 --- a/messagefoundry/pipeline/wiring_runner.py +++ b/messagefoundry/pipeline/wiring_runner.py @@ -7532,9 +7532,19 @@ async def _sandboxed_dispatch[T]( raise if serving: del self._sandbox_sessions[name] - await asyncio.to_thread(session.close) + try: + await asyncio.to_thread(session.close) + except Exception: # noqa: BLE001 - logged; must not turn the close into a fault + # The session is already dropped, so a failed close leaves at most a worker + # for the collector. Raising it instead would dead-letter the message as a + # Router or Handler fault, which an overtaken refusal is not. + log.warning( + "inbound %r: could not close the sandbox session a graph change overtook", + name, + ) raise SandboxSessionClosed( - f"inbound {name!r}: a reload overtook its sandbox worker's refusal" + f"inbound {name!r}: its sandbox worker's refusal was overtaken: its session was " + "discarded or the graph it was compared with is no longer served" ) from exc async def stop( diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 3b97cb9561..d36bf878af 100644 --- a/tests/test_sandbox_refusal_alert.py +++ b/tests/test_sandbox_refusal_alert.py @@ -411,6 +411,46 @@ def call(*args: Any, sandbox: SandboxSession | None = None, **kwargs: Any) -> An await store.close() +async def test_a_failed_close_of_an_overtaken_session_still_re_pends( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """The graph-overtaken branch closes the session it discards. A close that raises is logged + and the refusal is still raised as a close, so the message is re-pended rather than + dead-lettered as a Router or Handler fault (BACKLOG #6830).""" + registry = Registry(code_digest=_SOME_DIGEST) + sink = _Recorder() + other = graph_shape(Registry(code_digest="1" * 64)) + + def dispatch(_registry: Registry, *, sandbox: Any) -> None: + raise SandboxWorkerRefused("refused", first=True, content_only=False, graph=other) + + def failing_close() -> None: + raise OSError("close failed") + + store = await MessageStore.open(tmp_path / "close_fails.db") + try: + runner = _runner(registry, store, tmp_path, cast(Any, sink)) + try: + session = runner._sandbox_for("IB_X") + assert session is not None + session.close = failing_close # type: ignore[method-assign] + with ( + caplog.at_level(logging.DEBUG, logger="messagefoundry.pipeline.wiring_runner"), + pytest.raises(SandboxSessionClosed) as closed, + ): + await runner._off_loop_sandboxed("IB_X", dispatch, registry) + assert isinstance(closed.value.__cause__, SandboxWorkerRefused) + assert sink.refused == [] + assert any( + "IB_X" in r.getMessage() and "close" in r.getMessage() for r in caplog.records + ) + finally: + runner._sandbox_sessions.clear() + await runner._close_sandbox_sessions() + finally: + await store.close() + + async def test_a_refusal_straddling_a_reload_under_stop_re_pends_and_alerts_on_its_rerun( edited_config: Path, tmp_path: Path ) -> None: From 3043fe660c388c3f4c6dfff833f7a90631835f50 Mon Sep 17 00:00:00 2001 From: Scott Hall Date: Tue, 24 Nov 2026 10:49:52 -0600 Subject: [PATCH 13/13] Docs: an overtaken refusal's alert comes from the rerun, and its limits CONFIGURATION.md's [sandbox] kill-line paragraph and ADR 0187, as a dated note under Amendment B, now say that a refusal overtaken by a reload, even one re-applying the same registry, gets no alert or runner line and that the message's rerun alerts. Step 4 no longer claims the message always runs again: a row whose inbound the reload removed never runs, and repeated re-pends on a pooled lane count toward infra_fault_stop_after. Text only. BACKLOG #6830 --- docs/CONFIGURATION.md | 15 ++++++++++----- ...-shared-pool-or-router-phase-only-isolation.md | 7 +++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 101c77f6ce..83b04efbbe 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -1444,8 +1444,11 @@ that carries the request's id can instead be taken as the message's result; see paragraph below. Each worker kill writes one `WARNING` naming the inbound, the phase and a cause token, and no message content, except a graph refusal, which writes none, and a shutdown, logged at `INFO`. The runner alerts -on a graph refusal against the graph the engine serves; one against a graph a reload has replaced -gets neither the alert nor the runner's line. The line says the worker was `killed`, or that it `exited` for a cause recorded +on a graph refusal from the worker's session still serving, against a graph equal to the one the +engine serves. A refusal overtaken by a reload or its rollback gets neither the alert nor the +runner's line, even when the reload re-applies the same registry: the message runs again, and the +rerun's refusal, if the cause stands, raises the alert (BACKLOG #6830; step 4 under the graph +refusal below says when the message does not run again). The line says the worker was `killed`, or that it `exited` for a cause recorded only once the worker is seen gone (a crash, an exit during boot or right after it), which may still be a signal from outside the engine. The reap that ends a worker can write more lines, kill or not. On POSIX a `WARNING` naming the inbound and the pid says a worker that was already reaped could not have @@ -1572,9 +1575,11 @@ other module bytes than the engine loaded: worker for the next message, which is compared again. A reload refused before it swaps the graph keeps the worker's session and its refusal, so later messages are still refused from it, with no new comparison and no new alert. A refusal still in progress when a reload or its - rollback replaces the worker is neither alerted nor failed: the message runs again on a fresh - worker, at once or after it is re-pended, and that worker's refusal, if the cause stands, - raises the alert. Each other inbound's worker is compared when it starts, + rollback replaces the worker is neither alerted nor failed: the message is retried at once on a + fresh worker, or re-pended, and the refusal of the worker it next runs on, if the cause stands, + raises the alert. A re-pended message does not always run again: at least a row whose inbound + the reload removed never runs, and on a pooled lane repeated re-pends count as infrastructure + faults toward `infra_fault_stop_after`, which can stop the lane. Each other inbound's worker is compared when it starts, and each one refused raises its own alert. A reload that does not clear the cause raises the alert again. Nothing resolves it on its own, so resolve it in the alert list once the reload is done. diff --git a/docs/adr/0187-bound-the-subprocess-sandbox-worker-count-a-shared-pool-or-router-phase-only-isolation.md b/docs/adr/0187-bound-the-subprocess-sandbox-worker-count-a-shared-pool-or-router-phase-only-isolation.md index 3bc1f13a02..9183870641 100644 --- a/docs/adr/0187-bound-the-subprocess-sandbox-worker-count-a-shared-pool-or-router-phase-only-isolation.md +++ b/docs/adr/0187-bound-the-subprocess-sandbox-worker-count-a-shared-pool-or-router-phase-only-isolation.md @@ -377,6 +377,13 @@ from one added pointer to this amendment, at the end of its paragraph on what a own, at least those [`docs/CONFIGURATION.md`](../CONFIGURATION.md) `[sandbox]` lists for a worker already reaped or a process group that could not be signalled, so one kill is not always one line. + *Note, 2026-11-24 (BACKLOG #6830):* the runner's gate is narrower than the bullet above says. A + refusal overtaken by a reload or its rollback, from a session the reload discarded, gets neither + the alert nor the runner's line even when the reload re-applies the same registry, so the graph + was not replaced: the message runs again, and the rerun's refusal, if the cause stands, raises the + alert. [`docs/CONFIGURATION.md`](../CONFIGURATION.md) `[sandbox]` states the current rule and + when the message does not run again. + The kill is still the only cancellation primitive for a running dispatch, so the blast-radius argument above stands for every fault that does kill.