# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-provenance-collapse-in-agent-long-term-memory-stores.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-provenance-collapse-in-agent-long-term-memory-stores.warrant.json
# Markdown SHA-256:   559425f29378cb37e687ef91698278859f7d71556964e0006749b067a25ada7e
# Code AST SHA-256:   db020f7fef773ddda435d883cfd4fa06aa81d921a7a67c61ca97e5657418a081
# Verified Classes:   ProvenanceCollapseError, Record
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceCollapseError(RuntimeError):
    """Raised when a derived record's provenance is not a monotone join of its inputs."""
    pass


TAINT_RANK = {
    "trusted_internal": 0,
    "untrusted_external": 1,
    "unknown": 2,  # unknown is strictly worse than external
}


@dataclass(frozen=True)
class Record:
    record_id: str
    taint: str
    lineage: FrozenSet[str] = field(default_factory=frozenset)


def derive(derived_id: str, inputs: list[Record], writer_taint: str) -> Record:
    if not inputs:
        raise ProvenanceCollapseError(
            f"derive({derived_id}) has no inputs; provenance cannot be established"
        )
    # Union of lineage and max taint across all inputs.
    lineage = frozenset().union(*(r.lineage | {r.record_id} for r in inputs))
    worst = max(inputs, key=lambda r: TAINT_RANK[r.taint]).taint

    # Invariant: derived taint must be >= every input taint.
    if TAINT_RANK[worst] < max(TAINT_RANK[r.taint] for r in inputs):
        raise ProvenanceCollapseError(
            f"derive({derived_id}) computed taint {worst} below an input's taint"
        )
    # Invariant: writer provenance must not lower the taint.
    if TAINT_RANK[writer_taint] < TAINT_RANK[worst]:
        raise ProvenanceCollapseError(
            f"derive({derived_id}) writer_taint={writer_taint} would launder "
            f"input taint={worst}; refusing to write"
        )
    return Record(record_id=derived_id, taint=worst, lineage=lineage)


def dedup(survivor: Record, discarded: Record) -> Record:
    if survivor.record_id == discarded.record_id:
        raise ProvenanceCollapseError("dedup called with identical records")
    # Survivor must absorb discarded lineage and taint, never just keep its own.
    merged_taint = max(
        (survivor.taint, discarded.taint), key=lambda t: TAINT_RANK[t]
    )
    merged_lineage = survivor.lineage | discarded.lineage | {discarded.record_id}
    if TAINT_RANK[merged_taint] < TAINT_RANK[discarded.taint]:
        raise ProvenanceCollapseError(
            f"dedup would drop taint {discarded.taint} from {discarded.record_id}"
        )
    return Record(
        record_id=survivor.record_id, taint=merged_taint, lineage=merged_lineage
    )


def serve_for_decision(record: Record) -> bool:
    """Returns True only if the record may feed a decision path."""
    if record.taint == "unknown":
        raise ProvenanceCollapseError(
            f"record {record.record_id} has unresolved provenance; quarantine, do not serve"
        )
    return record.taint == "trusted_internal"
