# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-argument-fidelity-when-a-lossy-compaction-summary-is-rehydrated-from-retrieval-backed-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-tool-call-argument-fidelity-when-a-lossy-compaction-summary-is-rehydrated-from-retrieval-backed-reconstruction.warrant.json
# Markdown SHA-256:   2743140784c2524ca84d5c10704255e57e0747ebab89b331daa67e239bd8ab29
# Code AST SHA-256:   8fdcf2dbc8a85bd1525c73ec790e095152ebb85c68f2a54eb7478f198e960b2f
# Verified Classes:   StaleDerivationError, DerivedValue, ContextLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class StaleDerivationError(RuntimeError):
    """Raised when a derived value is used after its source span was superseded."""
    pass


@dataclass(frozen=True)
class DerivedValue:
    name: str
    value: float
    derived_from: FrozenSet[str]
    provenance: str  # "verbatim" | "summarized"
    stale: bool = False


@dataclass
class ContextLedger:
    derived: dict[str, DerivedValue] = field(default_factory=dict)
    superseded_spans: set[str] = field(default_factory=set)

    def add_derived(self, dv: DerivedValue) -> None:
        self.derived[dv.name] = dv

    def reconstruct(self, span_id: str) -> None:
        # Reconstruction is a supersession event, not an addition.
        self.superseded_spans.add(span_id)
        for name, dv in list(self.derived.items()):
            if span_id in dv.derived_from:
                self.derived[name] = DerivedValue(
                    name=dv.name,
                    value=dv.value,
                    derived_from=dv.derived_from,
                    provenance=dv.provenance,
                    stale=True,
                )

    def use(self, name: str) -> float:
        dv = self.derived.get(name)
        if dv is None:
            raise StaleDerivationError(f"unknown derived value: {name}")
        if dv.stale:
            raise StaleDerivationError(
                f"derived value {name!r} is stale: source span superseded by "
                f"reconstruction; recompute before use"
            )
        if dv.provenance == "summarized" and dv.derived_from & self.superseded_spans:
            raise StaleDerivationError(
                f"derived value {name!r} rests on summarized provenance with "
                f"superseded source; unverified, cannot be used as tool argument"
            )
        return dv.value


def compute_headroom(ledger: ContextLedger, quota_name: str, cap: float) -> float:
    try:
        quota = ledger.use(quota_name)
    except StaleDerivationError as exc:
        raise StaleDerivationError(
            f"cannot compute headroom: {exc}"
        ) from exc
    return cap - quota


# Failure trace reproduction:
ledger = ContextLedger()
ledger.add_derived(
    DerivedValue(
        name="quota_estimate",
        value=50.0,
        derived_from=frozenset({"span_provision_001"}),
        provenance="summarized",
    )
)
ledger.add_derived(
    DerivedValue(
        name="headroom",
        value=64.0 - 50.0,
        derived_from=frozenset({"quota_estimate"}),
        provenance="summarized",
    )
)
# Reconstruction of the verbatim span supersedes the summary-derived estimate.
ledger.reconstruct("span_provision_001")
# The following raises, correctly halting before a bad resize tool call.
compute_headroom(ledger, "quota_estimate", cap=64.0)
