# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-context-compaction-as-a-falsifiable-contract-rather-than-a-best-effort-optimization.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-lossy-context-compaction-as-a-falsifiable-contract-rather-than-a-best-effort-optimization.warrant.json
# Markdown SHA-256:   3907cd2cb7dd464d0f5160b3859b478398a05825be89f3b7ed8956f0ecff2d4f
# Code AST SHA-256:   03b21d26145df23f24197fcbbcac477d68c02ca9e2727cbd2260e1fc1013f052
# Verified Classes:   CompactionContractViolation, Fact, CompactionRequest, RetrievalIndex
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CompactionContractViolation(RuntimeError):
    """Raised when a compaction step would violate the sufficiency contract."""
    pass


@dataclass
class Fact:
    key: str
    value: str
    version: int
    chunk_id: str


@dataclass
class CompactionRequest:
    evicted_span_id: str
    summary: str
    pinned_keys: set[str]
    in_flight_tool_calls: int
    open_world: bool
    co_location_verified: bool


@dataclass
class RetrievalIndex:
    facts: list[Fact] = field(default_factory=list)

    def latest_for_key(self, key: str) -> Optional[Fact]:
        matches = [f for f in self.facts if f.key == key]
        if not matches:
            return None
        return max(matches, key=lambda f: f.version)


def gate_compaction(req: CompactionRequest, index: RetrievalIndex) -> None:
    # C2: quiescence at the boundary.
    if req.in_flight_tool_calls > 0:
        raise CompactionContractViolation(
            f"compaction of {req.evicted_span_id} attempted with "
            f"{req.in_flight_tool_calls} in-flight tool call(s); "
            "response may be torn across the eviction frontier"
        )

    # Open-world subgoal: compaction is a bet on retrieval; require C1 + C3.
    if req.open_world:
        if not req.co_location_verified:
            raise CompactionContractViolation(
                f"open-world compaction of {req.evicted_span_id} without "
                "key-value co-location guarantee (C1); spill instead of summarize"
            )
        for key in req.pinned_keys:
            fact = index.latest_for_key(key)
            if fact is None:
                raise CompactionContractViolation(
                    f"pinned key {key!r} not resolvable in retrieval index; "
                    "summary cannot be trusted to cover it"
                )


def replay_post_compaction(
    referenced_keys: list[str], index: RetrievalIndex
) -> dict[str, Fact]:
    resolved: dict[str, Fact] = {}
    for key in referenced_keys:
        fact = index.latest_for_key(key)
        if fact is None:
            raise CompactionContractViolation(
                f"replay failed: referenced key {key!r} unresolved after compaction"
            )
        resolved[key] = fact
    return resolved


if __name__ == "__main__":
    idx = RetrievalIndex(facts=[
        Fact("order:A19-4471", "refund approved", 1, "c1"),
        Fact("order:A19-4471:addr", "address mismatch", 1, "c2"),
        Fact("timeout", "30", 1, "c3"),
        Fact("timeout", "45", 3, "c5"),
    ])
    req = CompactionRequest(
        evicted_span_id="span-77",
        summary="refund approved for order 4471; timeout configured",
        pinned_keys={"order:A19-4471:addr", "timeout"},
        in_flight_tool_calls=0,
        open_world=True,
        co_location_verified=True,
    )
    gate_compaction(req, idx)
    resolved = replay_post_compaction(["order:A19-4471:addr", "timeout"], idx)
    assert resolved["timeout"].value == "45", "retrieval returned stale version"
