# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-its-own-write-audit-ledger-when-forget-provenance-tombstones-and-memory-write-hashes-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-its-own-write-audit-ledger-when-forget-provenance-tombstones-and-memory-write-hashes-disagree.warrant.json
# Markdown SHA-256:   91928ab5528fe4dea944f67965388a832846f2d07c0cf166af09d63689e340c4
# Code AST SHA-256:   f4197715d5df3bdca25f850bf08d40e171ad2b82ac64e7940ef8f7bc8f279c48
# Verified Classes:   UnverifiableTombstoneError, AuditEntry, Tombstone
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class UnverifiableTombstoneError(RuntimeError):
    """Raised when a tombstone cannot be reconciled against the audit ledger
    and lacks a provenance marker to classify the gap. Retrieval must fail
    closed (suppress) rather than serve the indexed value."""
    pass


@dataclass
class AuditEntry:
    key: str
    content_hash: str


@dataclass
class Tombstone:
    key: str
    referenced_hash: str
    reason: str
    # Snapshot of audit state AT FORGET TIME. None means the audit entry was
    # already absent when the tombstone was created (pre-existing gap).
    audit_present_at_forget: Optional[bool]
    provenance_marker: Optional[str]  # e.g. "write_rolled_back", "corroborated_at_forget"


def reconcile(key: str,
              audit: dict[str, AuditEntry],
              tombstone: Optional[Tombstone]) -> bool:
    """Returns True if the memory may be served, False if it must be suppressed.
    Raises UnverifiableTombstoneError if the state is indeterminate."""
    if tombstone is None:
        return True

    live = audit.get(key)

    # Case 1: live audit corroborates the tombstone's referenced hash.
    if live is not None and live.content_hash == tombstone.referenced_hash:
        return False  # legitimately forgotten, suppress

    # Case 2: live audit contradicts the tombstone (different hash).
    # The memory was rewritten after the forget; the new write supersedes.
    if live is not None and live.content_hash != tombstone.referenced_hash:
        return True

    # Case 3: live audit absent. Resolve against the forget-time snapshot.
    if tombstone.audit_present_at_forget is True:
        # Audit was live at forget, now gone => post-hoc ledger corruption.
        # Higher-severity fault; still suppress (fail closed).
        return False

    if tombstone.audit_present_at_forget is False:
        # Gap pre-existed the forget. Classify by provenance marker.
        if tombstone.provenance_marker == "write_rolled_back":
            return True   # speculative write discarded; safe to serve
        if tombstone.provenance_marker == "corroborated_at_forget":
            return False  # inconsistent marker; fail closed
        # No marker: indeterminate.
        raise UnverifiableTombstoneError(
            f"tombstone for {key!r} references {tombstone.referenced_hash!r} "
            f"absent from audit ledger with no provenance marker; "
            f"cannot distinguish rolled-back write from lost audit record"
        )

    # Snapshot itself missing (legacy tombstone): indeterminate.
    raise UnverifiableTombstoneError(
        f"tombstone for {key!r} has no forget-time audit snapshot; "
        f"reconciliation against live ledger is unsound"
    )


def safe_retrieve(key: str,
                  audit: dict[str, AuditEntry],
                  tombstones: dict[str, Tombstone],
                  index: dict[str, str]) -> Optional[str]:
    try:
        if reconcile(key, audit, tombstones.get(key)):
            return index.get(key)
        return None  # suppressed
    except UnverifiableTombstoneError:
        # Fail closed: treat as forgotten regardless of index contents.
        return None
