diff --git a/changelog.d/6830.fixed.md b/changelog.d/6830.fixed.md new file mode 100644 index 0000000000..4b2cfb8d03 --- /dev/null +++ b/changelog.d/6830.fixed.md @@ -0,0 +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 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/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/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 485a100d4e..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 @@ -1567,13 +1570,21 @@ 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 - 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 + until a reload. Those refusals raise no further alert and log no further `WARNING` line of + 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 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. -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 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/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. diff --git a/messagefoundry/pipeline/alerts.py b/messagefoundry/pipeline/alerts.py index 23603d45f2..cc64afc586 100644 --- a/messagefoundry/pipeline/alerts.py +++ b/messagefoundry/pipeline/alerts.py @@ -1115,9 +1115,12 @@ 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, 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 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 ea62929954..c78a395d25 100644 --- a/messagefoundry/pipeline/sandbox.py +++ b/messagefoundry/pipeline/sandbox.py @@ -212,11 +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 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, - #: 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" @@ -522,6 +522,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 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 as exc: + log.debug("could not close a sandbox worker pipe (%s)", type(exc).__name__) + class _StderrRelay: """One worker GENERATION's stderr, turned into log records (BACKLOG #343, ADR 0176). @@ -573,7 +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() + 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.""" @@ -927,7 +944,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.""" @@ -1006,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 @@ -1048,9 +1069,15 @@ 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. ``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 @@ -1239,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. @@ -1285,7 +1316,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 @@ -1295,16 +1327,40 @@ 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 reap + # did not end in time. Identity only, no content. + log.warning( + "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, + ) + 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). 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: self._proc = None @@ -1600,17 +1656,36 @@ 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: + with handoff: + ended = True + 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(): - 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/messagefoundry/pipeline/wiring_runner.py b/messagefoundry/pipeline/wiring_runner.py index 413899848f..c251aed094 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. 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 @@ -7463,28 +7464,30 @@ 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.""" + graphs raises it; the session's cached refusals for later messages do not. + + **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 asyncio.to_thread( - fn, registry, *args, sandbox=self._sandbox_for(name), **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 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 asyncio.to_thread( - fn, registry, *args, sandbox=self._sandbox_for(name), **kwargs - ) + return await self._sandboxed_dispatch(name, fn, registry, *args, **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. - if exc.first and (exc.graph is None or exc.graph is 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) @@ -7501,6 +7504,49 @@ 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. + + 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: 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 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] + 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}: 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( self, *, 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_graph_parity.py b/tests/test_sandbox_graph_parity.py index 5e619091e3..4fd833b6f1 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,69 @@ 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) + # 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() + + +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_pipe_close.py b/tests/test_sandbox_pipe_close.py new file mode 100644 index 0000000000..fb51274e11 --- /dev/null +++ b/tests/test_sandbox_pipe_close.py @@ -0,0 +1,166 @@ +# 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 threading +import time +import warnings +from pathlib import Path +from typing import Any, cast + +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 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 + """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) + 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() + 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( + 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] == 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 + 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 + + +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 diff --git a/tests/test_sandbox_refusal_alert.py b/tests/test_sandbox_refusal_alert.py index 26f6bb1335..d36bf878af 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 @@ -141,6 +142,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) @@ -167,10 +201,15 @@ 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 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] = [] @@ -182,10 +221,19 @@ 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 - with pytest.raises(SandboxWorkerRefused): + compared.append(graph_shape(Registry(code_digest="1" * 64))) # not the served graph + 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. + 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): @@ -197,6 +245,244 @@ 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_re_pends( + tmp_path: Path, cleared: bool, cached: bool +) -> None: + """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] = [] + 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=not cached, 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(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 == [] + 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 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_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_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: + """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: + 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))): @@ -204,7 +490,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, as the runner caches it + serving = graph_shape(load_config(edited_config)) _edit(edited_config) session = SandboxSession( SandboxPolicy(mode=SandboxMode.SUBPROCESS, wall_seconds=30.0),