# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-poisoned-memory-and-a-legitimately-revised-one-the-provenance-monotonicity-invariant-for-persistent-age.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-line-between-a-poisoned-memory-and-a-legitimately-revised-one-the-provenance-monotonicity-invariant-for-persistent-age.warrant.json
# Markdown SHA-256:   420c8e05ca4986dc1a474758f427e2f58f36800b029029b7cd86039f0242d35f
# Code AST SHA-256:   f886926234b551ae5a9ab11e321dd1046d5092e30584a203628ed85367fd126e
# Verified Classes:   ProvenanceViolation, Record, ProvenanceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class ProvenanceViolation(RuntimeError):
    """Raised when a write severs lineage or supersedes uncited records."""
    pass


@dataclass
class Record:
    id: str
    content: str
    source_instance: str
    derived_from: List[str] = field(default_factory=list)
    superseded_by: List[str] = field(default_factory=list)
    provenance_unverified: bool = False


class ProvenanceStore:
    def __init__(self, max_depth: int = 32):
        self.records: Dict[str, Record] = {}
        self.max_depth = max_depth

    def _closure(self, ids: List[str], depth: int = 0) -> Set[str]:
        if depth > self.max_depth:
            raise ProvenanceViolation(
                f"lineage depth exceeded {self.max_depth} at {ids}"
            )
        seen: Set[str] = set()
        for rid in ids:
            if rid in seen:
                continue
            seen.add(rid)
            rec = self.records.get(rid)
            if rec is None:
                continue  # GC'd; caller decides quarantine vs reject
            seen |= self._closure(rec.derived_from, depth + 1)
        return seen

    def commit(self, new: Record, declares_supersession: List[str]) -> Record:
        # Store derives supersession from declared lineage, never trusts both.
        closure = self._closure(new.derived_from)

        missing = [r for r in new.derived_from if r not in self.records]
        if missing:
            new.provenance_unverified = True
            self.records[new.id] = new
            return new  # quarantined, not promoted to corroborating evidence

        uncited = [r for r in declares_supersession if r not in closure]
        if uncited:
            raise ProvenanceViolation(
                f"write {new.id} supersedes {uncited} but cites no lineage to them"
            )

        if declares_supersession and not new.derived_from:
            raise ProvenanceViolation(
                f"write {new.id} supersedes records with empty derived_from"
            )

        for rid in declares_supersession:
            self.records[rid].superseded_by.append(new.id)
        self.records[new.id] = new
        return new

    def count_as_independent_evidence(self, rid: str) -> bool:
        rec = self.records.get(rid)
        if rec is None or rec.provenance_unverified:
            return False
        return not any(
            self.records[s].provenance_unverified
            for s in self._closure(rec.derived_from)
            if s in self.records
        )
