# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-rehydration-fidelity-invariant-for-lossy-summarization-under-retrieval-augmented-context-recovery.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-compact-the-rehydration-fidelity-invariant-for-lossy-summarization-under-retrieval-augmented-context-recovery.warrant.json
# Markdown SHA-256:   91dae67d3816237676146e627e8556fb0a8860e43306fafe6ebeacc98d96279c
# Code AST SHA-256:   e080d5dfbad22af75c9012973fd4827a10796473aa8ef014d2b9be26f8696929
# Verified Classes:   RehydrationFidelityError, CompactionRefusedError, RawSpan, SummaryManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class RehydrationFidelityError(RuntimeError):
    """Raised when a compacted summary's pinned facts cannot be exactly
    recovered from the raw store (missing span, hash drift, or TTL expiry).
    This is a hard continuity failure, not a benign retrieval miss."""


class CompactionRefusedError(RuntimeError):
    """Raised when pinned facts would not fit in the context budget that
    compaction is meant to free, so lossy projection is unsafe."""


PINNED_CLASSES = ("identifier", "date", "amount", "credential", "tool_arg")


@dataclass
class RawSpan:
    conversation_id: str
    turn_range: tuple[int, int]
    text: str

    def content_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.conversation_id.encode())
        h.update(str(self.turn_range).encode())
        h.update(self.text.encode())
        return h.hexdigest()


@dataclass
class SummaryManifest:
    conversation_id: str
    span_keys: dict[str, str] = field(default_factory=dict)  # span_id -> content_hash
    pinned_facts: dict[str, str] = field(default_factory=dict)  # fact_id -> verbatim value
    elided_fact_ids: list[str] = field(default_factory=list)


def compact(
    spans: list[RawSpan],
    pinned_facts: dict[str, str],
    context_budget_tokens: int,
    pinned_ledger_tokens: int,
) -> SummaryManifest:
    if pinned_ledger_tokens > context_budget_tokens:
        raise CompactionRefusedError(
            f"pinned ledger needs {pinned_ledger_tokens} tokens but compaction "
            f"frees only {context_budget_tokens}; lossy projection would be the "
            f"sole carrier of pinned facts"
        )
    manifest = SummaryManifest(conversation_id=spans[0].conversation_id)
    for i, span in enumerate(spans):
        manifest.span_keys[f"span_{i}"] = span.content_hash()
    manifest.pinned_facts = dict(pinned_facts)
    return manifest


def rehydrate_and_audit(
    manifest: SummaryManifest,
    raw_store: dict[str, RawSpan],
    ttl_expired: bool,
) -> dict[str, str]:
    """Replay the manifest at resume. Any pinned fact whose backing span is
    missing, drifted, or expired raises RehydrationFidelityError."""
    if ttl_expired:
        raise RehydrationFidelityError(
            f"raw store TTL expired for conversation {manifest.conversation_id}; "
            f"summary is now the sole carrier of pinned facts"
        )
    for span_id, expected_hash in manifest.span_keys.items():
        span: Optional[RawSpan] = raw_store.get(span_id)
        if span is None:
            raise RehydrationFidelityError(
                f"span {span_id} missing from raw store; rehydration undefined"
            )
        if span.content_hash() != expected_hash:
            raise RehydrationFidelityError(
                f"span {span_id} hash drift: expected {expected_hash[:12]}, "
                f"got {span.content_hash()[:12]}"
            )
    return dict(manifest.pinned_facts)


def resume_task(
    manifest: SummaryManifest,
    raw_store: dict[str, RawSpan],
    ttl_expired: bool,
    required_fact_id: str,
) -> str:
    facts = rehydrate_and_audit(manifest, raw_store, ttl_expired)
    if required_fact_id not in facts:
        raise RehydrationFidelityError(
            f"fact {required_fact_id} was elided by compaction and is not "
            f"present verbatim in the pinned ledger; refusing to proceed on "
            f"the lossy summary"
        )
    return facts[required_fact_id]
