# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-summary-budget-exhaustion-as-a-fidelity-boundary-rather-than-a-context-window-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-summary-budget-exhaustion-as-a-fidelity-boundary-rather-than-a-context-window-boundary.warrant.json
# Markdown SHA-256:   94ca9175e5dd3583315f42a0b7c15cce7043395b7a0f421fe4cea36101e4829d
# Code AST SHA-256:   64743c9c24c05cb30e357f6909edb25a3563bdfc95cfde265a1d95de6ba367e3
# Verified Classes:   FidelityBoundaryError, FidelityUnrecoverableError, ProvenanceManifest, CompactionState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class FidelityBoundaryError(RuntimeError):
    """Raised when a query needs a field the summary dropped but the window has room."""
    pass


class FidelityUnrecoverableError(RuntimeError):
    """Raised when the field was dropped and the source is no longer dereferenceable."""
    pass


@dataclass
class ProvenanceManifest:
    # span_id -> set of field classes dropped during compaction of that span
    dropped: dict[str, set[str]] = field(default_factory=dict)

    def fields_dropped(self, span_id: str) -> set[str]:
        return self.dropped.get(span_id, set())


@dataclass
class CompactionState:
    live_tokens: int
    window_cap: int
    summary_tokens: int
    summary_budget_floor: int
    manifest: ProvenanceManifest
    source_available: dict[str, bool]  # span_id -> can we still dereference it?


def answer_from_history(
    state: CompactionState,
    span_id: str,
    required_field: str,
    summary_contains_field: bool,
) -> str:
    at_fidelity_boundary = (
        state.live_tokens < state.window_cap
        and state.summary_tokens <= state.summary_budget_floor
        and required_field in state.manifest.fields_dropped(span_id)
    )

    if not at_fidelity_boundary:
        # Normal path: summary is authoritative or window is genuinely saturated.
        if summary_contains_field:
            return "answered_from_summary"
        raise FidelityBoundaryError(
            f"field {required_field!r} for span {span_id!r} absent from summary "
            f"but not flagged as dropped; manifest is stale"
        )

    # Fidelity boundary: window has room, summary budget is floored,
    # and the field was dropped. Must dereference, never re-summarize.
    if not state.source_available.get(span_id, False):
        raise FidelityUnrecoverableError(
            f"field {required_field!r} for span {span_id!r} was dropped at "
            f"compaction and source is no longer dereferenceable; "
            f"refusing to reconstruct from summary residue"
        )
    return f"dereferenced_source:{span_id}:{required_field}"
