# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-provenance-label-that-survives-a-tool-call-but-loses-its-taint-bit-the-label-taint-dissociation-failure-in-prompt-injec.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-provenance-label-that-survives-a-tool-call-but-loses-its-taint-bit-the-label-taint-dissociation-failure-in-prompt-injec.warrant.json
# Markdown SHA-256:   a1a3262b720d6f43c3886b6efa9ba30eb5bcdf473fb2349f62c794c707198e53
# Code AST SHA-256:   e0bbf100e2751e1a1d8de8c045eef2b39b3f27d052a3aca312077e7009905290
# Verified Classes:   ProvenanceDissociationError, Provenance
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import List, Optional


class ProvenanceDissociationError(RuntimeError):
    """Raised when a provenance envelope's taint bit is inconsistent with its label fields."""
    pass


@dataclass
class Provenance:
    origin: str
    trust: str          # "trusted" | "untrusted"
    taint: bool
    lineage: List[str] = field(default_factory=list)

    def __post_init__(self):
        # Label-taint consistency invariant: taint is a refinement of trust.
        if self.trust == "untrusted" and not self.taint:
            raise ProvenanceDissociationError(
                f"untrusted segment {self.origin} (lineage={self.lineage}) "
                f"has taint=False; reconstruction dropped the taint bit"
            )


def inherit_provenance(src: Provenance, boundary: str) -> Provenance:
    """Reconstruct provenance across a boundary, preserving taint monotonically."""
    if boundary in ("compaction", "summarization", "handoff"):
        # Taint monotonicity: OR-reduce over lineage; never clear.
        new_lineage = src.lineage + [boundary]
        return Provenance(
            origin=src.origin,
            trust=src.trust,
            taint=src.taint or any("taint" in a for a in src.lineage),
            lineage=new_lineage,
        )
    raise ProvenanceDissociationError(f"unknown boundary: {boundary}")


def recompute_from_local_context(src: Provenance, producer_trust: str) -> Provenance:
    """The failing design: taint derived from current producer, not lineage."""
    taint = producer_trust == "untrusted"
    # If the producer is trusted (e.g. the compactor), taint resets to False
    # even though the payload's lineage is tainted. This is the dissociation.
    return Provenance(origin=src.origin, trust=src.trust, taint=taint, lineage=src.lineage)


def policy_gate(seg: Provenance, action: str) -> None:
    """Enforce: tainted segments cannot drive privileged actions."""
    if seg.taint and action.startswith("write_"):
        raise ProvenanceDissociationError(
            f"blocked {action}: segment {seg.origin} is tainted (lineage={seg.lineage})"
        )


# Trace of the observed failure:
web = Provenance(origin="web:docs.corp.example", trust="untrusted", taint=True, lineage=["c-4471"])
# Compactor is a trusted tool, so recompute-from-local-context clears taint:
poisoned = recompute_from_local_context(web, producer_trust="trusted")
# poisoned.taint == False, but trust == "untrusted" -> __post_init__ raises.
# In the observed system, the consistency check was absent, so the gate passed it.
