# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-retrieval-provenance-when-a-forget-event-audit-discovers-that-the-memory-it-just-cited-was-tombstoned-mid-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-retrieval-provenance-when-a-forget-event-audit-discovers-that-the-memory-it-just-cited-was-tombstoned-mid-generation.warrant.json
# Markdown SHA-256:   cdacaf095fec82689fbb5d6ff6b86a36855fce573ae7aad571dcef2bb92a6462
# Code AST SHA-256:   d7f15950c3a297ff8c6da6e485ccc74348346ee75d41e6674128a0386dfb3447
# Verified Classes:   ProvenanceAuditError, DivergenceClass, RetrievalEvent, Tombstone, ProvenanceChain
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ProvenanceAuditError(RuntimeError):
    """Raised when a provenance chain cannot be classified under the invariant."""


class DivergenceClass(Enum):
    CLEAN = "clean"
    BENIGN_ERASED_AFTER_READ = "benign_erased_after_read"
    STALE_READ_DEFECT = "stale_read_defect"
    STORE_INCONSISTENT = "store_inconsistent"


@dataclass(frozen=True)
class RetrievalEvent:
    generation_id: str
    record_id: str
    snapshot_token: str
    retrieval_seq: int
    retrieved_at: float


@dataclass(frozen=True)
class Tombstone:
    record_id: str
    tombstone_seq: int
    tombstoned_at: float


@dataclass
class ProvenanceChain:
    retrieval: RetrievalEvent
    divergences: list = field(default_factory=list)  # append-only


def classify_citation(
    retrieval: RetrievalEvent,
    tombstone: Optional[Tombstone],
    record_live_now: bool,
) -> DivergenceClass:
    if tombstone is None:
        if not record_live_now:
            # No tombstone but record absent: store inconsistency, not a citation fault.
            return DivergenceClass.STORE_INCONSISTENT
        return DivergenceClass.CLEAN

    if tombstone.tombstone_seq > retrieval.retrieval_seq:
        # Erased after the agent read it: benign, must not alert.
        return DivergenceClass.BENIGN_ERASED_AFTER_READ

    # Tombstone predates the retrieval: the read path served dead memory.
    if not record_live_now:
        return DivergenceClass.STALE_READ_DEFECT

    # Tombstone seq < retrieval seq yet record reports live: contradictory store.
    return DivergenceClass.STORE_INCONSISTENT


def commit_citation(
    chain: ProvenanceChain,
    tombstone: Optional[Tombstone],
    pin_valid: bool,
    output_buffer: list,
    claim: str,
) -> None:
    """Enforce the citation-commit barrier. Never cite silently against a dead pin."""
    if not pin_valid:
        # Pin died mid-generation: annotate rather than cite silently, or omit.
        output_buffer.append(f"{claim} [cited_from_stale_snapshot]")
        chain.divergences.append(
            {"event": "provenance.diverged", "reason": "pin_invalid_at_commit",
             "record_id": chain.retrieval.record_id,
             "at": time.time()}
        )
        return

    klass = classify_citation(chain.retrieval, tombstone, record_live_now=True)
    if klass is DivergenceClass.STALE_READ_DEFECT:
        raise ProvenanceAuditError(
            f"retrieval served tombstoned record {chain.retrieval.record_id} "
            f"(tombstone_seq={tombstone.tombstone_seq} < "
            f"retrieval_seq={chain.retrieval.retrieval_seq}); "
            f"read-path defect, not a generation fault"
        )
    if klass is DivergenceClass.STORE_INCONSISTENT:
        raise ProvenanceAuditError(
            f"store state contradictory for {chain.retrieval.record_id}: "
            f"tombstone and liveness disagree"
        )
    output_buffer.append(claim)


def audit_generation(chain: ProvenanceChain, tombstone: Optional[Tombstone],
                     record_live_now: bool) -> DivergenceClass:
    klass = classify_citation(chain.retrieval, tombstone, record_live_now)
    if klass is DivergenceClass.BENIGN_ERASED_AFTER_READ:
        # Append divergence; do NOT mutate the original citation, do NOT alert.
        chain.divergences.append(
            {"event": "provenance.diverged", "reason": "erased_after_read",
             "record_id": chain.retrieval.record_id,
             "tombstone_seq": tombstone.tombstone_seq,
             "retrieval_seq": chain.retrieval.retrieval_seq}
        )
    return klass
