# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-dynamic-taint-label-as-irreversible-across-a-memory-write.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-dynamic-taint-label-as-irreversible-across-a-memory-write.warrant.json
# Markdown SHA-256:   01dd01dd011a0c6a6e909a6f1344714c523b61177e0ce8c22b01dc80b1070727
# Code AST SHA-256:   0afa302f91e151a77f925818c36b901101f994fd348978458e47fe0db14c49d4
# Verified Classes:   TaintLaunderingError, Label, Record, ProvenanceStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write would lower the taint of its contributors."""
    pass


@dataclass(frozen=True)
class Label:
    external: bool
    epoch: int

    def join(self, other: "Label") -> "Label":
        return Label(
            external=self.external or other.external,
            epoch=max(self.epoch, other.epoch),
        )


@dataclass
class Record:
    text: str
    contributors: FrozenSet[str] = field(default_factory=frozenset)
    label: Label = Label(external=False, epoch=0)


class ProvenanceStore:
    def __init__(self) -> None:
        self._records: dict[str, Record] = {}

    def write(
        self,
        record_id: str,
        text: str,
        source_label: Label,
        source_ids: FrozenSet[str] = frozenset(),
    ) -> None:
        # The writer's own identity is deliberately NOT an input to the label.
        # Trust is the join of contributors' labels, never the caller's class.
        contributors = source_ids | (frozenset({record_id}) if source_ids else frozenset())
        derived = source_label
        for sid in source_ids:
            prior = self._records.get(sid)
            if prior is not None:
                derived = derived.join(prior.label)
        # Invariant: a write may widen but never narrow the taint of its inputs.
        if source_label.external and not derived.external:
            raise TaintLaunderingError(
                f"write of {record_id!r} from EXTERNAL span produced TRUSTED label"
            )
        self._records[record_id] = Record(
            text=text, contributors=contributors, label=derived
        )

    def recall(self, record_id: str) -> Record:
        rec = self._records.get(record_id)
        if rec is None:
            raise KeyError(record_id)
        # Reconstruct from stored contributors; do not inherit reader trust.
        for cid in rec.contributors:
            other = self._records.get(cid)
            if other is not None and other.label.external and not rec.label.external:
                raise TaintLaunderingError(
                    f"recall of {record_id!r} found EXTERNAL contributor {cid!r} "
                    f"but record is TRUSTED"
                )
        return rec

    def paraphrase(self, record_id: str, new_id: str, new_text: str) -> None:
        # Semantic rewrite is a taint-preserving transform: contributors carry over.
        src = self.recall(record_id)
        self.write(
            new_id,
            new_text,
            source_label=src.label,
            source_ids=src.contributors | frozenset({record_id}),
        )


def plan_from_recall(store: ProvenanceStore, record_id: str) -> str:
    rec = store.recall(record_id)
    if rec.label.external:
        raise TaintLaunderingError(
            f"refusing to treat EXTERNAL record {record_id!r} as a system directive"
        )
    return rec.text
