# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-transcript-compaction-as-a-replay-fidelity-hazard-rather-than-a-context-budget-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-transcript-compaction-as-a-replay-fidelity-hazard-rather-than-a-context-budget-optimization.warrant.json
# Markdown SHA-256:   20c28a5c617ac6f6546e72aacb1996b48cf4c1cb9e68be45dfe5fa65e75c3ba6
# Code AST SHA-256:   fa04c1983be7d01792833711536c159be47db1b5719a15de412752fd7752db8a
# Verified Classes:   CompactionFidelityError, CompactedState
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionFidelityError(RuntimeError):
    """Raised when a compacted transcript is promoted to authoritative state
    without satisfying replay-fidelity invariants."""


@dataclass
class CompactedState:
    summary_text: str
    depth: int                      # 0 = raw, 1 = single-generation summary
    provenance: dict[str, int]      # fact_id -> raw turn index
    artifact_hash: Optional[str]    # recorded bytes hash, None if re-derived
    facts: list[str] = field(default_factory=list)


MAX_DEPTH = 1


def assert_resumable(state: CompactedState, cited_facts: list[str],
                     raw_turns: dict[int, str]) -> None:
    if state.depth > MAX_DEPTH:
        raise CompactionFidelityError(
            f"summary depth {state.depth} exceeds cap {MAX_DEPTH}: "
            "granularity collapse is expected beyond depth 1"
        )
    if state.artifact_hash is None:
        raise CompactionFidelityError(
            "compacted state was re-derived rather than loaded from a recorded "
            "artifact; replay is non-deterministic and this is not the same state"
        )
    for fact in cited_facts:
        turn = state.provenance.get(fact)
        if turn is None:
            raise CompactionFidelityError(
                f"cited fact {fact!r} has no provenance pointer to the raw "
                "transcript; lossy projection is masquerading as state"
            )
        if turn not in raw_turns:
            raise CompactionFidelityError(
                f"provenance for {fact!r} points to missing turn {turn}"
            )
        if fact not in raw_turns[turn]:
            raise CompactionFidelityError(
                f"provenance mismatch: {fact!r} is not entailed by turn {turn}; "
                "likely granularity collapse across generations"
            )


def resume_from_compaction(state: CompactedState, cited_facts: list[str],
                           raw_turns: dict[int, str]) -> str:
    try:
        assert_resumable(state, cited_facts, raw_turns)
    except CompactionFidelityError:
        # Fall back to full-fidelity re-expansion from the retained transcript.
        raise
    return state.summary_text
