# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-lossy-context-compaction-without-verifying-the-summary-is-a-fixed-point.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rolls-back-a-lossy-context-compaction-without-verifying-the-summary-is-a-fixed-point.warrant.json
# Markdown SHA-256:   28555ecddd2ad99c6e438f125b1f8f541d5b49bd3a74268c85f2261921f763ae
# Code AST SHA-256:   163a67d8e86c0f00fbf4e09b6573f088d0e7ca40d90fe638a57aa5047f87c618
# Verified Classes:   IrrecoverableCompaction, CompactionCheckpoint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class IrrecoverableCompaction(RuntimeError):
    """Raised when a rollback is requested but only a lossy summary survives."""
    pass


class CompactionCheckpoint:
    def __init__(self, checkpoint_id: str, source_tokens: list[str] | None,
                 summary: str, summarizer_is_idempotent: bool):
        self.checkpoint_id = checkpoint_id
        self.source_tokens = source_tokens          # None => source GC'd
        self.summary = summary
        self.summarizer_is_idempotent = summarizer_is_idempotent

    def has_source(self) -> bool:
        return self.source_tokens is not None

    def is_fixed_point(self) -> bool:
        # A summary is a safe navigation surface only if re-summarizing
        # it is provably a no-op. Otherwise summary-space is lossy.
        return self.summarizer_is_idempotent


def rollback(checkpoint: CompactionCheckpoint,
             fidelity_oracle) -> list[str]:
    """
    Restore pre-compaction transcript. Refuses to reconstruct from summary.
    """
    if not checkpoint.has_source():
        # The dangerous path: source gone, only projection remains.
        # Do NOT attempt to re-expand the summary.
        if checkpoint.is_fixed_point():
            # Summary is self-consistent; treat as canonical index,
            # but still cannot restore exact tokens.
            raise IrrecoverableCompaction(
                f"checkpoint {checkpoint.checkpoint_id}: source GC'd; "
                f"summary is a fixed point but is not a transcript. "
                f"Escalate to external ground truth, do not reconstruct."
            )
        raise IrrecoverableCompaction(
            f"checkpoint {checkpoint.checkpoint_id}: source GC'd and "
            f"summary is not a fixed point (C(S) != S). Reconstruction "
            f"from summary would fabricate state. Refusing rollback."
        )

    restored = list(checkpoint.source_tokens)

    # Fidelity check MUST compare against retained source, never
    # against the summary (the summarizer is under suspicion).
    if not fidelity_oracle(restored, checkpoint.source_tokens):
        raise IrrecoverableCompaction(
            f"checkpoint {checkpoint.checkpoint_id}: restored tokens "
            f"failed fidelity oracle against retained source."
        )

    return restored


def safe_recover(checkpoint: CompactionCheckpoint,
                 fidelity_oracle,
                 external_ground_truth_fn):
    """
    Recovery entrypoint: real rollback if source exists, else escalate
    to external truth. Never synthesize from summary.
    """
    try:
        return rollback(checkpoint, fidelity_oracle)
    except IrrecoverableCompaction as exc:
        # Route to external systems (re-read files, re-query tools)
        # rather than reasoning over the lossy projection.
        return external_ground_truth_fn(checkpoint.checkpoint_id, exc)
