# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-self-inflicted-context-corruption-when-its-own-pruning-pass-erases-the-provenance-of-the-fact-it-was-trying-to-preserve.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-self-inflicted-context-corruption-when-its-own-pruning-pass-erases-the-provenance-of-the-fact-it-was-trying-to-preserve.warrant.json
# Markdown SHA-256:   56defd30d914d0298fd8ed3f48264645c68ceec05e7bff9ce5933f8f626becab
# Code AST SHA-256:   db3ba4dc66ad20da6cf61befdc9d7eb1ef2251c7d713a0159b71a85f3703bb16
# Verified Classes:   ProvenanceCollapseError, ContextState, DependencyLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ProvenanceCollapseError(RuntimeError):
    """Raised when a context rewrite severs a dependency edge it does not re-attach."""
    pass


@dataclass
class ContextState:
    # Mutable working buffer: fact_id -> text
    facts: Dict[str, str] = field(default_factory=dict)
    # Mutable annotations inside the buffer: fact_id -> set of consumer ids
    annotations: Dict[str, Set[str]] = field(default_factory=dict)


@dataclass
class DependencyLedger:
    """Immutable to the rewrite pass. Records which consumers depend on which facts."""
    edges: Dict[str, Set[str]] = field(default_factory=dict)  # consumer -> {fact_id}

    def consumers_of(self, fact_id: str) -> Set[str]:
        return {c for c, deps in self.edges.items() if fact_id in deps}


def commit_rewrite(
    before: ContextState,
    after: ContextState,
    ledger: DependencyLedger,
) -> None:
    """
    Validate a proposed rewrite against the immutable ledger.
    A rewrite is valid iff every fact still depended on by an open consumer
    is either (a) still present AND still annotated to that consumer,
    or (b) explicitly re-attached in the proposed annotations.
    """
    violations = []
    for consumer, deps in ledger.edges.items():
        for fact_id in deps:
            still_present = fact_id in after.facts
            reattached = consumer in after.annotations.get(fact_id, set())
            if not still_present:
                violations.append(
                    f"fact {fact_id} evicted but consumer {consumer} still open"
                )
            elif not reattached:
                # Content survived, provenance did not: the dangerous case.
                violations.append(
                    f"fact {fact_id} retained but dependency edge to "
                    f"{consumer} was severed without re-attachment"
                )
    if violations:
        raise ProvenanceCollapseError(
            "rewrite rejected; dependency edges lost: " + "; ".join(violations)
        )
    # Commit only after validation passes.
    before.facts = after.facts
    before.annotations = after.annotations


def safe_rewrite_example() -> None:
    state = ContextState(
        facts={"f1": "order_id=88213"},
        annotations={"f1": {"refund_lookup"}},
    )
    ledger = DependencyLedger(edges={"refund_lookup": {"f1"}})

    # Bad rewrite: keeps the fact text, drops the annotation. This is the trap.
    bad = ContextState(
        facts={"f1": "the order in question is 88213"},
        annotations={},  # annotation lost
    )
    commit_rewrite(state, bad, ledger)  # raises ProvenanceCollapseError

    # Good rewrite: rephrases the fact but re-attaches the edge.
    good = ContextState(
        facts={"f1": "the order in question is 88213"},
        annotations={"f1": {"refund_lookup"}},
    )
    commit_rewrite(state, good, ledger)  # commits
