# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-through-a-stale-provenance-index-after-a-forget-then-relearn-cycle.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-resurrect-deleted-memory-through-a-stale-provenance-index-after-a-forget-then-relearn-cycle.warrant.json
# Markdown SHA-256:   f15f38e256398bdcedab34abcd5c57b1878e1debd485373c0f0dc1ee70bfd22f
# Code AST SHA-256:   5eeb96b20e1e371cdba7569066db70ef361a52f0046ed223b96487d314dabe78
# Verified Classes:   ProvenanceCollisionError, ProvenanceRecord, Tombstone, ProvenanceIndex
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceCollisionError(RuntimeError):
    """Raised when a write would reuse a provenance address that carries a
    tombstone newer than the write's birth epoch, or when a read resolves to
    a provenance record whose lineage predates a tombstone at the same address."""


@dataclass
class ProvenanceRecord:
    address: str
    birth_epoch: float
    source: str
    session: str
    ttl_horizon: Optional[float] = None


@dataclass
class Tombstone:
    address: str
    death_epoch: float
    audit_id: str


@dataclass
class ProvenanceIndex:
    records: dict = field(default_factory=dict)
    tombstones: dict = field(default_factory=dict)  # address -> Tombstone

    def write(self, address: str, source: str, session: str,
              ttl_horizon: Optional[float] = None) -> ProvenanceRecord:
        birth = time.time()
        tomb = self.tombstones.get(address)
        if tomb is not None and tomb.death_epoch >= birth:
            # A tombstone at this address is newer than or equal to this write.
            # Reusing the slot would resurrect deleted lineage. Fail closed.
            raise ProvenanceCollisionError(
                f"address {address!r} carries tombstone {tomb.audit_id} "
                f"with death_epoch {tomb.death_epoch} >= birth_epoch {birth}; "
                f"allocate a nonce-suffixed address instead"
            )
        rec = ProvenanceRecord(address, birth, source, session, ttl_horizon)
        self.records[address] = rec
        return rec

    def forget(self, address: str, audit_id: str) -> Tombstone:
        death = time.time()
        tomb = Tombstone(address, death, audit_id)
        # Tombstone is durable BEFORE content removal; it dominates any
        # subsequent birth at this address.
        self.tombstones[address] = tomb
        self.records.pop(address, None)
        return tomb

    def resolve(self, address: str) -> ProvenanceRecord:
        rec = self.records.get(address)
        tomb = self.tombstones.get(address)
        if rec is None:
            raise ProvenanceCollisionError(
                f"no live provenance at {address!r}"
            )
        if tomb is not None and tomb.death_epoch >= rec.birth_epoch:
            # Address collision across a delete/reinsert boundary: the
            # record's lineage predates a tombstone at the same address.
            # Do not serve it as authoritative.
            raise ProvenanceCollisionError(
                f"provenance at {address!r} (birth {rec.birth_epoch}) "
                f"is dominated by tombstone {tomb.audit_id} "
                f"(death {tomb.death_epoch}); lineage unresolved"
            )
        return rec


def read_memory_with_provenance(index: ProvenanceIndex, address: str) -> ProvenanceRecord:
    """Resolve provenance for a read. Fails closed on collision rather than
    returning a lineage that may belong to a deleted prior memory."""
    try:
        return index.resolve(address)
    except ProvenanceCollisionError:
        # Caller may still use content, but must treat lineage as unverified
        # and must not cite or make erasure decisions on it.
        raise ProvenanceCollisionError(
            f"refusing to serve provenance for {address!r}: "
            f"unverified lineage; content usable, lineage not authoritative"
        )
