# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-speculative-tool-call-pre-execution-whose-predicted-effect-diverges-from-the-dry-run-receipt-at-commit-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-speculative-tool-call-pre-execution-whose-predicted-effect-diverges-from-the-dry-run-receipt-at-commit-time.warrant.json
# Markdown SHA-256:   cbf28240d44fb3ef41ac5047d4feecd428d10492b1e2692b703f59314ece60d5
# Code AST SHA-256:   17c42aa54117a0bd7cae620137f3985a20950db51e81de21b772528cf8d51139
# Verified Classes:   SpeculativeCommitDivergence, Receipt, Buffer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SpeculativeCommitDivergence(RuntimeError):
    """Raised when a buffered speculative effect diverges from its dry-run receipt."""
    pass


@dataclass(frozen=True)
class Receipt:
    effect_hash: str
    world_state_hash: str
    tool_contract_hash: str


@dataclass(frozen=True)
class Buffer:
    effect_hash: str
    world_state_hash: str
    tool_contract_hash: str


def commit_gate(buffer: Buffer, receipt: Receipt) -> str:
    """
    Returns 'commit', 'resimulate', or raises SpeculativeCommitDivergence.

    Invariant: commit requires effect identity, state identity, AND contract
    identity. State-hash equality alone is never sufficient.
    """
    state_match = buffer.world_state_hash == receipt.world_state_hash
    effect_match = buffer.effect_hash == receipt.effect_hash
    contract_match = buffer.tool_contract_hash == receipt.tool_contract_hash

    if state_match and effect_match and contract_match:
        return "commit"

    if not state_match and contract_match:
        # Staleness: world advanced, tool unchanged. Safe to resimulate.
        return "resimulate"

    if state_match and not effect_match:
        # Divergence: same state, same contract, different effect.
        # The tool violated its determinism contract at commit time.
        raise SpeculativeCommitDivergence(
            f"effect divergence at identical world state: "
            f"buffer={buffer.effect_hash} receipt={receipt.effect_hash}"
        )

    if not contract_match:
        # Tool contract changed under the receipt. Cannot certify effect.
        raise SpeculativeCommitDivergence(
            f"tool contract changed under receipt: "
            f"buffer={buffer.tool_contract_hash} receipt={receipt.tool_contract_hash}"
        )

    raise SpeculativeCommitDivergence("unclassified commit-gate state")


def derive_contract_hash(tool_descriptor: dict) -> str:
    # Contract hash must cover effect-derivation logic, not just wire schema.
    material = repr(sorted(tool_descriptor.items())).encode()
    return hashlib.sha256(material).hexdigest()


def flush_speculative(buffer: Buffer, receipt: Receipt) -> None:
    decision = commit_gate(buffer, receipt)
    if decision == "resimulate":
        # Caller must re-reserve against a fresh receipt; buffer is discarded.
        return
    # decision == "commit": apply buffered effect to the ledger.
    apply_effect(buffer.effect_hash)


def apply_effect(effect_hash: str) -> None:
    # Ledger application is out of scope; divergence is caught upstream.
    pass
