# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-forget-provenance-tracked-retention-tombstones-and-the-dangling-derivation-boundary-in-read-write-forget-memory-tool-a.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-forget-provenance-tracked-retention-tombstones-and-the-dangling-derivation-boundary-in-read-write-forget-memory-tool-a.warrant.json
# Markdown SHA-256:   9fd2211473b5caa4290c9bf3420d1e24629065f5962c271d0b3a7b676287f614
# Code AST SHA-256:   f7ab82cec8ca7787def54b16cc3d7ad2d6200da51ef4e135ffb8090fe68c4eb5
# Verified Classes:   DanglingProvenanceError, ProvenanceStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DanglingProvenanceError(RuntimeError):
    """Raised when a forget would strand a live dependent on a bare absence,
    or when a write attempts to revive a burned tombstone ID."""
    pass


class ProvenanceStore:
    def __init__(self):
        self.records = {}       # id -> {provenance, retention, hash}
        self.tombstones = {}    # id -> {reason, former_hash, retention_class}
        self.reverse = {}       # parent_id -> set(child_id)
        self._retention_rank = {"ephemeral": 0, "session": 1, "durable": 2}

    def write(self, rid, provenance, retention, content_hash):
        if rid in self.tombstones:
            raise DanglingProvenanceError(
                f"write to burned tombstone id {rid!r}; "
                f"former evidence cannot be reconstructed by re-derivation"
            )
        self.records[rid] = {"provenance": list(provenance),
                             "retention": retention, "hash": content_hash}
        for p in provenance:
            self.reverse.setdefault(p, set()).add(rid)

    def forget(self, rid, reason):
        if rid not in self.records:
            raise DanglingProvenanceError(f"forget of unknown record {rid!r}")
        rec = self.records[rid]
        live_deps = [c for c in self.reverse.get(rid, ())
                     if c in self.records]
        # Backward retention propagation: a surviving dependent whose
        # retention outranks this record forbids hard deletion.
        must_tombstone = any(
            self._retention_rank[self.records[c]["retention"]]
            > self._retention_rank[rec["retention"]]
            for c in live_deps
        )
        if live_deps and must_tombstone:
            self.tombstones[rid] = {"reason": reason,
                                    "former_hash": rec["hash"],
                                    "retention_class": rec["retention"]}
            del self.records[rid]
            return {"forgotten": False, "tombstoned": True,
                    "dependents": len(live_deps)}
        if live_deps:
            # Cascade: dependents share or under-rank retention; forget them first.
            for c in live_deps:
                self.forget(c, reason=f"cascade_of:{rid}")
        del self.records[rid]
        return {"forgotten": True, "tombstoned": False}

    def read(self, rid):
        if rid in self.tombstones:
            return {"tombstoned": True, **self.tombstones[rid]}
        if rid in self.records:
            return {"found": True, **self.records[rid]}
        raise DanglingProvenanceError(
            f"{rid!r} is neither live nor tombstoned — a bare absence the "
            f"agent cannot distinguish from hallucinated provenance"
        )
