Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions changelog.d/6830.fixed.md
Original file line number Diff line number Diff line change
@@ -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`)
7 changes: 7 additions & 0 deletions changelog.d/6831.fixed.md
Original file line number Diff line number Diff line change
@@ -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`)
25 changes: 18 additions & 7 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
9 changes: 6 additions & 3 deletions messagefoundry/pipeline/alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down
113 changes: 94 additions & 19 deletions messagefoundry/pipeline/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,11 +212,11 @@
#: 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"
Expand Down Expand Up @@ -522,6 +522,18 @@
#: 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).
Expand Down Expand Up @@ -573,7 +585,12 @@
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."""
Expand Down Expand Up @@ -927,7 +944,8 @@
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."""

Expand Down Expand Up @@ -1006,6 +1024,9 @@
# 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
Expand Down Expand Up @@ -1048,9 +1069,15 @@
# 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
Expand Down Expand Up @@ -1239,6 +1266,10 @@
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.
Expand Down Expand Up @@ -1285,7 +1316,8 @@

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
Expand All @@ -1295,16 +1327,40 @@
#
# 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(

Check notice on line 1350 in messagefoundry/pipeline/sandbox.py

View workflow job for this annotation

GitHub Actions / diff-coverage (advisory)

Missing Coverage

Line 1349-1350 missing coverage
"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

Expand Down Expand Up @@ -1537,7 +1593,7 @@
"which counts the lookups the engine served for it"
)

def _serve_bounded(

Check warning on line 1596 in messagefoundry/pipeline/sandbox.py

View workflow job for this annotation

GitHub Actions / complexity triage (advisory)

New function over the complexity threshold

`_serve_bounded` is new at complexity 13 (mccabe threshold 10)
self,
proc: subprocess.Popen[bytes],
request_id: str,
Expand Down Expand Up @@ -1600,17 +1656,36 @@
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)
Expand Down
Loading
Loading