# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-compaction-from-silently-invalidating-an-agent-s-own-prior-tool-call-facts.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-compaction-from-silently-invalidating-an-agent-s-own-prior-tool-call-facts.warrant.json
# Markdown SHA-256:   96587f4aa118369a2b7ee7399753f14f7b3e692eab8d61f63371d0984fd6adcd
# Code AST SHA-256:   67342509417eb9c4eeb0bf43e92a36febfb42fab1217af2a5bf8d6165b51283c
# Verified Classes:   CompactionGroundingError, FactStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any

class CompactionGroundingError(RuntimeError):
    """Raised when a compacted artifact is consumed as a source of committed literals."""
    pass

@dataclass
class FactStore:
    facts: dict[str, dict[str, Any]] = field(default_factory=dict)
    superseded: dict[str, str] = field(default_factory=dict)

    def commit(self, handle: str, payload: dict[str, Any]) -> None:
        if handle in self.facts:
            self.superseded[handle] = handle  # explicit supersession chain
        self.facts[handle] = payload

    def resolve(self, handle: str) -> dict[str, Any]:
        if handle not in self.facts:
            raise CompactionGroundingError(
                f"summary references handle {handle!r} absent from fact store; "
                "checkpoint is corrupt or store was not persisted atomically"
            )
        return self.facts[handle]

def construct_tool_arg(store: FactStore, handle: str, field_name: str, proposed: Any) -> Any:
    """Resolve a committed fact for a tool call; reject prose-derived approximations."""
    fact = store.resolve(handle)
    if field_name not in fact:
        raise CompactionGroundingError(f"fact {handle!r} has no field {field_name!r}")
    exact = fact[field_name]
    if proposed != exact:
        # Catch the '~118k -> 118000' corruption: approximate-but-not-exact is a
        # lossy-summary artifact being consumed as a literal.
        raise CompactionGroundingError(
            f"proposed value {proposed!r} for {handle}.{field_name} does not match "
            f"committed literal {exact!r}; value likely re-derived from summary prose"
        )
    return exact

# --- failure trace reproduction ---
store = FactStore()
store.commit("f_12", {"row_count": 118204, "checksum": "9f3a...c1", "schema_version": 7})

# Step 71: agent reconstructs from parent summary "~118k rows" and calls the join.
try:
    construct_tool_arg(store, "f_12", "row_count", 118000)
except CompactionGroundingError as e:
    print(f"BLOCKED (correct): {e}")

# A summary that dropped the handle entirely is a corrupt checkpoint.
try:
    store.resolve("f_12_checksum")  # handle the leaf summarizer never emitted
except CompactionGroundingError as e:
    print(f"FAIL-CLOSED (correct): {e}")
