# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-call-pre-execution-against-commit-time-validation-when-the-sandbox-s-idempotency-key-namespace-is-no.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-speculative-tool-call-pre-execution-against-commit-time-validation-when-the-sandbox-s-idempotency-key-namespace-is-no.warrant.json
# Markdown SHA-256:   796b973b0be9d48f1b3c3f7522df777ed96dbc27d04a0913b3f7e8d69f572f9f
# Code AST SHA-256:   e52ad7ea7446f67086a6170d48d5c0fc20fd7ae5362963590b4594934edee609
# Verified Classes:   KeyNamespaceDivergence, SpeculativeResult, CommitRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class KeyNamespaceDivergence(RuntimeError):
    """Raised when speculative and commit idempotency keys disagree for the same logical call."""
    pass


@dataclass(frozen=True)
class SpeculativeResult:
    call_id: str
    args_hash: str
    sandbox_key: str
    verdict: str


@dataclass(frozen=True)
class CommitRecord:
    call_id: str
    args_hash: str
    ledger_key: str
    attempt_n: int


def derive_sandbox_key(call_id: str, args_hash: str) -> str:
    return hashlib.sha256(f"{call_id}|{args_hash}".encode()).hexdigest()


def derive_ledger_key(call_id: str, args_hash: str, attempt_n: int) -> str:
    # NOTE: attempt_n inclusion is the divergence source; retained for audit.
    return hashlib.sha256(f"{call_id}|{args_hash}|{attempt_n}".encode()).hexdigest()


def reconcile(spec: SpeculativeResult, commit: CommitRecord) -> str:
    if spec.call_id != commit.call_id or spec.args_hash != commit.args_hash:
        raise KeyNamespaceDivergence(
            f"identity mismatch: spec=({spec.call_id},{spec.args_hash}) "
            f"commit=({commit.call_id},{commit.args_hash})"
        )
    if spec.verdict != "ALLOW":
        raise KeyNamespaceDivergence(
            f"speculative verdict {spec.verdict!r} cannot be committed for {spec.call_id}"
        )
    if spec.sandbox_key != commit.ledger_key:
        raise KeyNamespaceDivergence(
            f"idempotency key divergence for call_id={spec.call_id} "
            f"attempt={commit.attempt_n}: sandbox={spec.sandbox_key[:12]} "
            f"ledger={commit.ledger_key[:12]} — quarantine, do not retry"
        )
    return commit.ledger_key


def commit_speculative(spec: SpeculativeResult, attempt_n: int = 0) -> str:
    commit = CommitRecord(
        call_id=spec.call_id,
        args_hash=spec.args_hash,
        ledger_key=derive_ledger_key(spec.call_id, spec.args_hash, attempt_n),
        attempt_n=attempt_n,
    )
    return reconcile(spec, commit)
