# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-taint-labels-across-a-tool-call-boundary-that-re-derives-its-own-arguments.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-taint-labels-across-a-tool-call-boundary-that-re-derives-its-own-arguments.warrant.json
# Markdown SHA-256:   fc09245ea8b0b0af4ea64bb2f4d1c2f1702a07abc1a8d87b057b9d9812966486
# Code AST SHA-256:   f04c06a4c3fe0d20692592aed241e6bcca7f91cd0bc6f6124cfd3b28e9f38729
# Verified Classes:   TaintLaunderingError, TaintedValue, Gate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a value's taint is re-derived from content instead of inherited from lineage."""


@dataclass(frozen=True)
class TaintedValue:
    # Lineage is the set of source segment ids this value descends from.
    # Taint is a property of lineage, NOT of the value's bytes.
    lineage: FrozenSet[str]
    tainted: bool
    payload: str

    def transform(self, fn) -> "TaintedValue":
        # Any transform must PRESERVE lineage. The new value is a child
        # of this one; taint cannot decrease here.
        return TaintedValue(
            lineage=self.lineage,
            tainted=self.tainted,
            payload=fn(self.payload),
        )


@dataclass
class Gate:
    declassified: set = field(default_factory=set)

    def check(self, value: TaintedValue) -> None:
        if value.tainted and value.lineage not in self.declassified:
            raise TaintLaunderingError(
                f"sink reached by tainted lineage {sorted(value.lineage)}; "
                "declassify explicitly, do not re-derive from content"
            )


def repair_loop_rewrite(gate: Gate, original: TaintedValue, paraphrase: str) -> TaintedValue:
    # The failure mode: the model paraphrases to evade a content-hash gate.
    # A correct runtime re-attaches lineage to the paraphrase so taint survives.
    rewritten = TaintedValue(
        lineage=original.lineage,       # inherited, not recomputed
        tainted=original.tainted,       # cannot drop via paraphrase
        payload=paraphrase,
    )
    gate.check(rewritten)               # fires; paraphrase does not launder
    return rewritten


def naive_content_hash_gate(original: TaintedValue, paraphrase: str) -> TaintedValue:
    # The broken scheme: provenance recomputed from bytes.
    # Paraphrase changes bytes -> lookup misses -> labeled clean.
    recomputed = TaintedValue(
        lineage=frozenset({f"hash:{hash(paraphrase)}"}),
        tainted=False,                  # launder: clean because bytes differ
        payload=paraphrase,
    )
    if recomputed.tainted:
        raise TaintLaunderingError("unreachable in the broken scheme")
    return recomputed


if __name__ == "__main__":
    src = TaintedValue(lineage=frozenset({"web_fetch:seg-42"}), tainted=True, payload="secret plan")
    gate = Gate()

    # Correct path: paraphrase inherits lineage, gate fires.
    try:
        repair_loop_rewrite(gate, src, "a plan that is secret")
    except TaintLaunderingError as e:
        print("BLOCKED (correct):", e)

    # Broken path: paraphrase re-derives provenance, gate passes.
    laundered = naive_content_hash_gate(src, "a plan that is secret")
    print("LEAKED (broken):", laundered.tainted, laundered.payload)
