# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-pre-execution-that-violates-idempotency-key-scope-during-a-compensating-transaction-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-speculative-tool-call-pre-execution-that-violates-idempotency-key-scope-during-a-compensating-transaction-rollback.warrant.json
# Markdown SHA-256:   282e6fea189203860e5b5f863f48f01afa0bd33070c98f8ba7dcb62505e5fedd
# Code AST SHA-256:   74a65bd734428d15607608aba3db0708a44c8250dfe8c33e19dd4a149fb4b85a
# Verified Classes:   IdempotencyScopeViolation, CompensatingLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class IdempotencyScopeViolation(RuntimeError):
    """Raised when a tool result is applied against a generation whose
    compensating fence has already closed, indicating silent ledger divergence."""
    pass


class CompensatingLedger:
    def __init__(self) -> None:
        self._fences: dict[str, str] = {}       # key -> generation closed
        self._applied: dict[tuple[str, str], int] = {}

    def compensate(self, key: str, generation: str) -> None:
        self._fences[key] = generation

    def apply_result(self, key: str, generation: str, delta: int) -> None:
        fenced_gen = self._fences.get(key)
        if fenced_gen is not None and fenced_gen == generation:
            # Same generation already compensated: this is a true duplicate.
            return
        if fenced_gen is not None and fenced_gen != generation:
            raise IdempotencyScopeViolation(
                f"result for key={key!r} generation={generation!r} "
                f"arrives after fence closed generation={fenced_gen!r}; "
                f"applying it would diverge belief from ledger"
            )
        self._applied[(key, generation)] = self._applied.get((key, generation), 0) + delta


def reconcile_before_commit(
    ledger: CompensatingLedger,
    key: str,
    belief_generation: str,
    result_generation: str,
    delta: int,
) -> None:
    if belief_generation != result_generation:
        raise IdempotencyScopeViolation(
            f"belief generation {belief_generation!r} != result generation "
            f"{result_generation!r} for key {key!r}; halt and escalate"
        )
    ledger.apply_result(key, result_generation, delta)
