# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-lossy-compaction-to-preserve-rehydration-fidelity-across-a-long-horizon-context.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-lossy-compaction-to-preserve-rehydration-fidelity-across-a-long-horizon-context.warrant.json
# Markdown SHA-256:   f5859bc84989e34b620d5be2624f1ecbbf1e3934da634a1774ddb8e0fa9a9371
# Code AST SHA-256:   b4003b5aef4af6ab12f74358fc73066b38706958ee5be8706097c0fd80c58e7a
# Verified Classes:   CompactionFidelityError, CompactedSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionFidelityError(RuntimeError):
    """Raised when a rehydrated span cannot support the decision consuming it."""
    pass


@dataclass
class CompactedSpan:
    span_id: str
    summary: str
    source_ref: Optional[str]          # content hash / external store key
    reconstructible: bool              # summarizer proved summary is sufficient
    source_fields_dropped: list[str] = field(default_factory=list)


def rehydrate_for_decision(span: CompactedSpan, decision: str, fetch_source) -> str:
    """
    Enforce the invariant: a non-reconstructible summary may not be consumed
    as ground truth. Either re-fetch source bytes or abstain.
    """
    if span.reconstructible:
        return span.summary

    # Summary is a pointer, not a memory. Attempt source re-fetch.
    if span.source_ref is None:
        raise CompactionFidelityError(
            f"span {span.span_id} marked non-reconstructible but has no "
            f"source_ref; decision '{decision}' cannot be verified and must abstain"
        )

    source = fetch_source(span.source_ref)
    if source is None:
        raise CompactionFidelityError(
            f"span {span.span_id} source {span.source_ref} unavailable; "
            f"refusing to substitute lossy summary for decision '{decision}'"
        )

    # Verify the summary did not drop a field the decision depends on.
    for dropped in span.source_fields_dropped:
        if dropped in decision.lower():
            raise CompactionFidelityError(
                f"decision '{decision}' depends on field '{dropped}' that "
                f"compaction dropped from span {span.span_id}; re-derivation required"
            )

    return source


def compact(raw_span: str, summarize, in_flight_decisions: list[str]) -> CompactedSpan:
    """Boundary-aware compaction: refuse to summarize spans with pending consumers."""
    if in_flight_decisions:
        raise CompactionFidelityError(
            f"cannot summarize span with {len(in_flight_decisions)} in-flight "
            f"decisions pending; index instead of summarize"
        )
    summary, dropped = summarize(raw_span)
    return CompactedSpan(
        span_id="s1",
        summary=summary,
        source_ref="hash:s1",
        reconstructible=len(dropped) == 0,
        source_fields_dropped=dropped,
    )
