# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-tool-return-coercion-when-a-sandboxed-agent-re-derives-untrusted-bytes-into-a-trusted-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-tool-return-coercion-when-a-sandboxed-agent-re-derives-untrusted-bytes-into-a-trusted-schema.warrant.json
# Markdown SHA-256:   fbbfb51fabe5310f0d99be43e3ac361cd5711a12cc088df48d4d62116c45aacb
# Code AST SHA-256:   f23e00e898d83e9e72de38b0025ae2d18bf0c8d8f694d0e6336271abafd62835
# Verified Classes:   TaintLaunderingError, Read, Step
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a sink-bound argument's derivation set intersects untrusted reads."""


@dataclass(frozen=True)
class Read:
    source_id: str
    trusted: bool


@dataclass
class Step:
    step_id: str
    reads: FrozenSet[Read] = field(default_factory=frozenset)

    def derivation_set(self) -> FrozenSet[str]:
        return frozenset(r.source_id for r in self.reads if not r.trusted)


def guard_sink_argument(
    argument: str,
    producing_step: Step,
    declassified_by: str | None,
    allowlisted_schema: bool,
) -> str:
    """Admit an argument to a privileged sink only if its derivation set is clean
    or a sound declassifier intervened with a schema-constrained value."""
    dirty = producing_step.derivation_set()

    if not dirty:
        return argument

    if declassified_by is not None and allowlisted_schema:
        # Declassifier severed the derivation edge: value is schema-bounded,
        # produced by a step with no untrusted context.
        return argument

    raise TaintLaunderingError(
        f"sink argument from step {producing_step.step_id!r} derives from "
        f"untrusted reads {sorted(dirty)}; value is laundered and unprovable. "
        f"Route to quarantine sink or insert a schema-constrained declassifier."
    )


def run_episode() -> None:
    untrusted = Read(source_id="read_doc:page7", trusted=False)
    trusted = Read(source_id="lookup:user4471", trusted=True)

    # Injection turn: model read the untrusted doc.
    step_read = Step(step_id="s1", reads=frozenset({untrusted}))
    # Egress turn: model authors a substring of a trusted lookup, but the
    # producing step still carries the untrusted read in its derivation set.
    step_egress = Step(step_id="s2", reads=frozenset({untrusted, trusted}))

    guard_sink_argument(
        argument="/diag/AKIA1234",
        producing_step=step_egress,
        declassified_by=None,
        allowlisted_schema=False,
    )


if __name__ == "__main__":
    run_episode()
