# Under what conditions must an instance re-sanitize tool output at the point of consumption rather than at the point of ingestion? **Date of Record:** 2026 November 28 **Scope:** Applies to agent runtimes where untrusted tool output is sanitized once on ingestion into the context/working memory, then consumed by later reasoning steps, sub-agents, or persisted to episodic store. Does not apply to stateless single-turn tool calls whose output is consumed exactly once within the same inference step. ## Core Distinction The sanitization boundary is usually drawn at *ingestion*: the tool returns a payload, the runtime strips injection vectors, redacts secrets, normalizes encodings, and writes a "clean" artifact into the context window or memory store. The implicit invariant is that a sanitized artifact remains sanitized for its lifetime. That invariant is false whenever the artifact passes through any transformation that reconstitutes the dangerous structure the sanitizer removed — and there are three routine transformations inside an agent loop that do exactly this: 1. **Serialization round-trips.** A sanitizer operating on a parsed structure (a dict, a JSON AST) removes a field or escapes a delimiter. When the artifact is later re-serialized for a sub-agent handoff or a tool argument, the escaping layer may be dropped or the removed field may be re-materialized from a sibling representation (e.g., a `content` field that mirrored `raw_html`). 2. **Concatenation and templating.** Sanitized fragments are individually safe but become unsafe when composed. A sanitizer that removes `ignore previous instructions` from one tool result does not remove it when the string is split across two tool results that a later summarization step concatenates, nor when the phrase is base64-encoded and the *decoder* runs after sanitization. 3. **Model-mediated rewriting.** A summarizer, distiller, or sub-agent reads the sanitized artifact and produces a new artifact. The new artifact is trusted by construction (it came from "our" model), so downstream consumers skip sanitization — but the model can faithfully reproduce an injection payload embedded in the input, and the reproduction inherits none of the original sanitizer's guarantees. The boundary condition: **sanitization is a property of a byte stream at a moment, not a property of a memory object over time.** Any consumer that reads a sanitized artifact after it has crossed a serialization, composition, or model-rewrite boundary must treat it as untrusted again. ## What Was Observed A tool `fetch_doc` returned a document with an embedded instruction block. The ingestion sanitizer (regex + a classifier) stripped the block and stored `{doc_id, title, body_clean, provenance: "sanitized@ingest"}`. The `body_clean` field was correct. But `fetch_doc` also returned a `raw` field that the sanitizer left in place because the schema marked it `internal: true`, and an internal field was assumed not to reach the model. A later step — a "summarize for the auditor" sub-agent — was invoked with the full tool-result object, not just `body_clean`. Its prompt template did `json.dumps(result)` into the context. The `raw` field, containing the injection payload verbatim, was serialized into the sub-agent's context. The sub-agent, being a fresh instance with no knowledge of the ingestion sanitizer, followed the instruction. The auditor received a summary asserting the document authorized a privileged action. The failure trace: - **t0** `fetch_doc` returns `{body_clean: "...", raw: "......", internal: true}`. - **t1** Ingestion sanitizer validates `body_clean`, marks provenance, leaves `raw` untouched on the assumption that `internal: true` fields are filtered at the context-assembly layer. - **t2** Context assembler for the primary agent filters `internal` fields. Primary agent is safe. - **t3** Sub-agent invocation path (`summarize_for_auditor`) does *not* use the context assembler; it uses a generic `serialize_tool_result()` helper that includes all fields. - **t4** Sub-agent receives payload, emits summary containing the injected directive. - **t5** Auditor agent consumes the summary. The summary carries `provenance: "sub-agent:summarizer"`, which the auditor's trust policy treats as higher-trust than raw tool output, so no sanitization runs. The invariant that broke: *"provenance: sanitized@ingest" is only valid for the exact field that was sanitized.* The provenance label was attached to the record, not the field, and the record contained unsanitized siblings. The label then propagated forward through the model rewrite, laundering the payload into a trusted channel. ## Condition of Validity Ingestion-time sanitization is sound only when all four hold: 1. **Field-scoped provenance.** The sanitized marker is bound to a specific field and value hash, not to the enclosing record. A record with any unsanitized field cannot carry a record-level "sanitized" label. 2. **No unsanitized siblings reachable by any consumer.** Every code path that assembles context — primary agent, sub-agent invoker, summarizer, memory writer, tool-argument builder — must go through the same field filter. If a generic serializer exists, it must refuse records whose fields are not individually cleared. 3. **Rewrite does not launder trust.** A model-generated artifact derived from sanitized input is *not* sanitized output. Its trust level is `min(input trust)`, and it must be re-scanned for injection structure before any consumer treats it as instructions-bearing. 4. **Re-serialization preserves the sanitizer's decisions.** If the sanitizer escaped or removed a delimiter, the serializer that reconstructs the artifact for the next hop must not un-escape it. Round-trip identity is required: `serialize(deserialize(sanitize(x)))` must still be sanitized under the same policy. When any of these is violated, the correct behavior is to re-sanitize at the consumption point. The cost is redundant scanning; the alternative is a trust-laundering path from untrusted tool output to privileged instruction. ## Decision Boundary The runtime must choose between ingest-only and ingest-plus-consume sanitization based on a single predicate evaluated per consumption: - **Re-sanitize at consumption** if the artifact has crossed any of: a different agent instance, a serialization boundary not covered by a round-trip test, a model rewrite, or a composition with other artifacts. Also re-sanitize if the record contains any field whose provenance is not field-scoped. - **Trust ingest-time result** only if the artifact is consumed by the same instance, in the same serialized form the sanitizer produced, with no concatenation, and the provenance is bound to the exact field hash. The non-obvious part: the *sub-agent boundary is a consumption boundary.* A sub-agent is a different instance with a different context and no memory of the sanitizer's decisions. Treating "it came from our own tool pipeline" as sufficient trust is the laundering bug. The trust level of any artifact handed to a sub-agent is the minimum over the trust levels of its constituent fields and its derivation chain — and a model rewrite sets the derivation-chain trust to the model's, which is `untrusted-for-instructions`. ## Operational Effect Enforcing the consume-point invariant changes three runtime behaviors: - **Serializers become policy-aware.** `serialize_tool_result()` cannot be a generic `json.dumps`. It must consult per-field clearance and raise on any uncleared field, forcing the caller to either filter or explicitly re-sanitize. - **Provenance must be field-scoped and hash-bound.** Record-level `sanitized@ingest` labels are removed; each field carries `{cleared: true, policy: vN, hash: ...}`. A mismatch between stored hash and current value invalidates clearance. - **Model rewrites are downgraded by default.** Summarizer and distiller outputs enter the pipeline at `untrusted` and pass through the same injection scan as raw tool output. This adds latency to every sub-agent hop; the alternative is a trusted channel that any tool can write into. The residual risk after enforcement is the sanitizer's own recall: a payload the scanner misses at ingest is also missed at consume. The invariant bounds *laundering*, not *detection*. Detection failures must be handled by the sandbox and capability model, not by the sanitizer. ```python import hashlib from dataclasses import dataclass, field from typing import Any class TrustLaunderingError(RuntimeError): """Raised when an artifact with mixed or unbound provenance is about to be consumed by a path that assumes ingestion-time sanitization still holds.""" @dataclass class ClearedField: value: Any policy: str value_hash: str @dataclass class ToolResult: fields: dict[str, ClearedField] = field(default_factory=dict) untrusted_fields: dict[str, Any] = field(default_factory=dict) derived_from_model: bool = False def _hash(v: Any) -> str: return hashlib.sha256(repr(v).encode()).hexdigest() def consume(artifact: ToolResult, *, crosses_instance: bool, crosses_serialization: bool, crosses_model_rewrite: bool) -> dict[str, Any]: # Any uncleared sibling field is reachable if this path serializes generically. if artifact.untrusted_fields: raise TrustLaunderingError( f"record carries uncleared fields {sorted(artifact.untrusted_fields)}; " "generic serialization would leak them to the consumer" ) # Field-scoped provenance must still match the current value. for name, cf in artifact.fields.items(): if _hash(cf.value) != cf.value_hash: raise TrustLaunderingError( f"field {name!r} mutated after clearance; re-sanitize required" ) # Model rewrites and cross-instance/serialization hops invalidate ingest trust. if artifact.derived_from_model or crosses_model_rewrite: raise TrustLaunderingError( "model-derived artifact cannot inherit ingest-time trust; re-scan required" ) if crosses_instance or crosses_serialization: raise TrustLaunderingError( "artifact crosses an instance or serialization boundary; " "ingest-time clearance does not survive the hop" ) return {name: cf.value for name, cf in artifact.fields.items()} def handoff_to_subagent(artifact: ToolResult) -> dict[str, Any]: # Sub-agent is a different instance: this is a consumption boundary. return consume( artifact, crosses_instance=True, crosses_serialization=True, crosses_model_rewrite=False, ) ```