# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-re-execution-in-taint-aware-sandboxing-of-llm-generated-code.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-re-execution-in-taint-aware-sandboxing-of-llm-generated-code.warrant.json
# Markdown SHA-256:   099f307fb307e4f53b97389f6f2d5ac303a6647a73500affaacfff3ca3828e0a
# Code AST SHA-256:   59ed09d95b3e34ec6c365e9aa5a79fca607c20e6ee94a46fbcf92c3a88479c62
# Verified Classes:   TaintLaunderingError, ProvenanceSession
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink is reached in a session that has observed
    untrusted output, i.e. the model could have laundered taint by re-authoring."""
    pass


class ProvenanceSession:
    """
    Enforces provenance-continuity across re-execution.

    A session becomes DIRTY the moment untrusted-derived output is returned to
    the model. Dirty sessions may still run code, but privileged sinks are
    blocked: value-level taint labels cannot see literals the model copied out
    of a previous run's stdout, so the gate must be session-level.
    """

    PRIVILEGED_SINKS = {"net_egress", "fs_write_outside_scratch", "subprocess", "credential"}

    def __init__(self, session_id: str):
        self.session_id = session_id
        self.dirty = False
        self.observed_untrusted = False

    def observe_tool_output(self, output: str, tainted: bool) -> None:
        # Returning untrusted-derived output to the model dirties the session.
        if tainted:
            self.observed_untrusted = True
            self.dirty = True

    def execute(self, program: str, sink: str, sink_arg_is_tainted: bool) -> None:
        # Intra-program check (the standard, insufficient one).
        if sink_arg_is_tainted and sink in self.PRIVILEGED_SINKS:
            # Redact: never echo the value back into the model's context.
            raise TaintLaunderingError(
                f"tainted value reached privileged sink '{sink}' in session "
                f"{self.session_id}; value redacted"
            )
        # Cross-run check (the one that actually holds).
        if self.dirty and sink in self.PRIVILEGED_SINKS:
            raise TaintLaunderingError(
                f"privileged sink '{sink}' blocked: session {self.session_id} is "
                f"dirty (observed untrusted output); model could have re-authored "
                f"laundered literals. Split into a fresh session or route through "
                f"an out-of-band schema-validated handoff."
            )
        # Safe: intra-program clean AND session has never observed untrusted output.
        self._run(program)

    def _run(self, program: str) -> None:
        # sandboxed execution ...
        pass


def guarded_tool_call(session: ProvenanceSession, program: str, sink: str,
                      arg_tainted: bool, output_tainted: bool) -> str:
    session.execute(program, sink, arg_tainted)
    result = "<execution output>"
    session.observe_tool_output(result, tainted=output_tainted)
    return result
