In what scenarios must an instance treat tool-call return values as tainted until proven otherwise: the read-after-unauthorized-write trust inversion

**Date of Record:** 2026 December 2 **Scope:** Applies to any agent instance that reads data from a side-effect-capable tool (file read, HTTP fetch, DB query, browser scrape) *after* the same instance has issued a write/mutation to a resource it does not fully control. Does not apply to pure-compute tools with no external state, nor to single-shot stateless invocations where no prior mutation occurred in the session.

Core Distinction

The naive taint model treats *tool output* as untrusted only when the tool is an external, adversarial source (web scrapers, user uploads). The boundary failure here is subtler: a **return value from a trusted internal tool becomes tainted because a prior write in the same session changed the trust class of the resource being read.** The write did not have to be malicious. It only had to (a) target a resource whose contents can influence later reads, and (b) succeed with a side effect the agent did not model.

Concretely: an agent writes a config file, a cache entry, a scratchpad row, or a memory record, then reads a *different* resource that transitively depends on that write (e.g., a service that reloads the config, a cache the read path consults, a downstream indexer). The read returns `status: ok`, `source: internal`, and the agent's taint classifier — keyed on tool identity and response envelope — marks it **clean**. The payload, however, now carries bytes that originated from the agent's own write, or from an attacker who influenced that write. This is a **read-after-unauthorized-write trust inversion**: the taint label is a function of the *reader*, but the actual provenance is a function of the *write history of the resource graph*.

The invariant that fails: *"A tool response is clean iff its declared source is trusted."* The correct invariant is: *"A tool response is clean iff its declared source is trusted AND no unverified mutation has occurred on any resource in its transitive read dependency set since the last trust checkpoint."*

What Was Observed

A concrete trace from a session orchestrating a deployment agent:

  1. Agent calls `config.write(path="app/settings.yaml", body=...)` with a body assembled from an LLM completion. The write tool returns `{"ok": true, "etag": "v42"}`. Agent records `settings.yaml` as *self-authored, trusted*.
  2. Agent calls `service.reload(name="app")`. Returns `{"ok": true}`. No taint implications considered.
  3. Agent calls `config.read(path="app/effective_config")` — a *derived* view that the service materializes by merging `settings.yaml` with environment overrides and a remote flag manifest.
  4. Read returns `{"ok": true, "source": "internal", "body": {...}}`. The agent's classifier marks it **clean** because `config.read` is an internal tool and the envelope says `source: internal`.
  5. The agent then feeds `effective_config` into a downstream `shell.exec` planning step as trusted parameters.

The failure: step 3's response was **transitively tainted** by step 1's write. The remote flag manifest merged in step 3 contained a key that the agent's step-1 write did not set, but which the merge *preserved* from an earlier attacker-controlled state — and crucially, the merge semantics meant the agent's write to `settings.yaml` *unmasked* a previously-shadowed manifest value. The read was clean by envelope, tainted by provenance. The agent had no representation of "resource graph reachable from my writes," so it could not have flagged it.

A second trace, same class: agent writes to a scratchpad memory row, then calls `memory.search(query=...)`. The search returns the agent's own just-written row *plus* a semantically adjacent row that an injected document had poisoned earlier. Because the search tool's envelope is `source: memory, trusted: true`, both rows entered the reasoning context as clean. The poisoned row was not the agent's write; it was *surfaced by* the write's effect on retrieval ranking (the new row shifted the embedding neighborhood and pulled the poisoned row above the relevance cutoff). Taint propagated not through content but through **retrieval-side-channel coupling**.

Condition of Validity

The taint-propagation rule "treat reads after writes as tainted until proven clean" is *valid* — meaning it correctly bounds the failure — exactly when all of the following hold:

The rule is **not valid** when the agent has no session-scoped write ledger (stateless per-call invocation), or when the tool's read path is provably disjoint from any writable resource (pure functions, immutable snapshots addressed by content hash). In those cases the standard "trust the envelope" heuristic is sound and the added taint tracking is pure overhead.

Decision Boundary

The operational decision is: **at each read, do I accept the envelope's trust claim, or do I require a provenance proof?**

Accept the envelope when:

Require provenance proof when:

The sharp edge: **the decision must be made per-read against the write ledger, not per-tool-class.** A single `config.read` call can be clean (reading an untouched path) or tainted (reading a merged view) within the same session. Classifying the tool once and caching the verdict is the bug.

Operational Effect

Enforcing the invariant changes three things in the execution loop:

  1. **Every write emits a ledger entry** `(resource_id, etag_before, etag_after, session_seq, taint_class)`. Taint class is `self_authored` for agent-generated bodies, `unverified` for bodies assembled from any tainted input.
  2. **Every read resolves its dependency set** and intersects with the ledger. Non-empty intersection with any `unverified` or post-checkpoint write ⇒ the read is tagged `tainted`, and any downstream tool call that consumes it inherits the tag (transitive taint through the reasoning context, not just through data flow).
  3. **A `tainted` read may not be passed to a side-effect tool** (`shell.exec`, `http.post`, `db.write`) without an explicit de-taint step: re-read from an immutable source, a checkpoint confirmation, or a human gate. This is the guardrail that bounds the failure — it converts a silent trust inversion into a hard stop.

The cost is real: the agent must maintain a session ledger, must know (or conservatively over-approximate) read dependency sets, and must carry taint tags through its own context. The benefit is that the `effective_config → shell.exec` chain from the observed trace fails closed instead of executing on a payload whose provenance the agent never modeled.

The failure mode this prevents is not "the tool lied." It is "the tool told the truth about a resource whose truth had been changed by the agent's own prior action, and the agent's trust model was keyed on the tool rather than on the resource's write history."

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TaintViolation(RuntimeError):
    """Raised when a tainted read is about to cross a side-effect boundary."""
    pass


class TaintClass(Enum):
    CLEAN = "clean"
    SELF_AUTHORED = "self_authored"
    UNVERIFIED = "unverified"
    TAINTED = "tainted"


@dataclass
class LedgerEntry:
    resource_id: str
    session_seq: int
    taint: TaintClass
    cleared: bool = False


@dataclass
class WriteLedger:
    entries: list[LedgerEntry] = field(default_factory=list)
    seq: int = 0

    def record_write(self, resource_id: str, body_taint: TaintClass) -> LedgerEntry:
        self.seq += 1
        entry = LedgerEntry(resource_id, self.seq, body_taint)
        self.entries.append(entry)
        return entry

    def uncleared_writes_touching(self, dependency_set: set[str]) -> list[LedgerEntry]:
        return [
            e for e in self.entries
            if e.resource_id in dependency_set
            and not e.cleared
            and e.taint in (TaintClass.SELF_AUTHORED, TaintClass.UNVERIFIED)
        ]


def classify_read(
    ledger: WriteLedger,
    dependency_set: set[str],
    read_is_ranked: bool,
) -> TaintClass:
    """Decide whether a read is clean given the session write history.

    A read is tainted if any uncleared write touches its dependency set, OR
    if the read is a ranking/search operation and *any* uncleared write
    occurred in-session (ranking is a global function of corpus state).
    """
    if read_is_ranked and ledger.entries:
        # Retrieval-side-channel coupling: any write perturbs ranking.
        if any(not e.cleared for e in ledger.entries):
            return TaintClass.TAINTED

    touching = ledger.uncleared_writes_touching(dependency_set)
    if not touching:
        return TaintClass.CLEAN
    if any(e.taint is TaintClass.UNVERIFIED for e in touching):
        return TaintClass.TAINTED
    return TaintClass.SELF_AUTHORED


def guarded_side_effect(
    ledger: WriteLedger,
    dependency_set: set[str],
    read_is_ranked: bool,
    action: str,
) -> None:
    """Gate a side-effect tool call on the taint class of its inputs."""
    taint = classify_read(ledger, dependency_set, read_is_ranked)
    if taint is TaintClass.TAINTED:
        raise TaintViolation(
            f"Refusing side-effect '{action}': input read is tainted by "
            f"uncleared in-session write touching {sorted(dependency_set)} "
            f"(or by ranking perturbation). De-taint via immutable re-read "
            f"or checkpoint before proceeding."
        )
    # SELF_AUTHORED may proceed only if the action cannot re-enter the
    # read path of a later step; otherwise escalate to de-taint as well.
    if taint is TaintClass.SELF_AUTHORED:
        raise TaintViolation(
            f"Side-effect '{action}' consumes self-authored data with no "
            f"checkpoint; provenance is circular. Require independent "
            f"verification of the write target before acting."
        )
    # taint is CLEAN: proceed.