# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-checkpoints-as-lossy-but-recoverable-rather-than-lossless-snapshots.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-auto-compaction-checkpoints-as-lossy-but-recoverable-rather-than-lossless-snapshots.warrant.json
# Markdown SHA-256:   437505cec33f1988b8015c83382b0c0ea3218f6838f0fab88364723491cb4aea
# Code AST SHA-256:   aa9b31bf627ef582062f39f0b17355296f7ffd6617140e36c9a36cfbed1c5c50
# Verified Classes:   CompactionResumeError, FactKind, CheckpointFact, LiveSource
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class CompactionResumeError(RuntimeError):
    """Raised when a checkpointed fact cannot be safely trusted or re-verified."""
    pass


class FactKind(Enum):
    VERBATIM = "verbatim"
    DERIVED = "derived"


@dataclass
class CheckpointFact:
    key: str
    value: str
    kind: FactKind
    provenance_token: Optional[str]  # tool call id / source URI / log offset
    as_of: float                     # checkpoint watermark, epoch seconds


@dataclass
class LiveSource:
    value: str
    modified_at: float
    reachable: bool = True


def resolve_fact(fact: CheckpointFact, sources: dict[str, LiveSource]) -> str:
    """
    Decide whether to trust, re-verify, or halt on a checkpointed fact.
    Returns the value the instance may act on.
    """
    if fact.kind is FactKind.VERBATIM:
        src = sources.get(fact.provenance_token or "")
        if src is None or not src.reachable:
            raise CompactionResumeError(
                f"verbatim fact {fact.key!r} has no reachable source; "
                f"cannot confirm it survived compaction"
            )
        return fact.value

    # DERIVED: must re-verify against live provenance.
    if not fact.provenance_token:
        raise CompactionResumeError(
            f"derived fact {fact.key!r} has no provenance token; "
            f"prose reconstruction is forbidden (confabulation risk)"
        )
    src = sources.get(fact.provenance_token)
    if src is None or not src.reachable:
        raise CompactionResumeError(
            f"derived fact {fact.key!r} provenance {fact.provenance_token!r} "
            f"unreachable; halt and re-plan rather than reconstruct"
        )

    if src.value == fact.value:
        return fact.value

    # Disagreement: live source is authoritative iff modified after checkpoint.
    if src.modified_at > fact.as_of:
        # Supersession event — log it so a later compaction cannot re-collapse.
        log_supersession(fact.key, fact.value, src.value, src.modified_at)
        return src.value

    # Source changed *before* the checkpoint but disagrees: the checkpoint
    # itself was already stale. Do not trust either silently.
    raise CompactionResumeError(
        f"derived fact {fact.key!r} disagreed with source modified before "
        f"checkpoint watermark; checkpoint was stale at write time"
    )


def log_supersession(key: str, old: str, new: str, at: float) -> None:
    # Durable append-only log; must survive subsequent compactions verbatim.
    ...
