# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-divergence-from-committing-irreversible-side-effects-across-optimistic-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-tool-call-divergence-from-committing-irreversible-side-effects-across-optimistic-multi-agent-execution.warrant.json
# Markdown SHA-256:   7e0bcdb026cc22ed09eb76aad1229669e9d67519e7ea0bcd3831e4dbf734853b
# Code AST SHA-256:   f32febe61bd7562d06aa5d97dbb68b67cc28cacac97dc5adf4d53bfaa599a5d4
# Verified Classes:   EffectClass, SpeculationRefused, DivergenceLeaseExpired, ToolSpec, CommitRecord, CommitLedger
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Optional


class EffectClass(Enum):
    REVERSIBLE = "reversible"
    COMPENSABLE = "compensable"
    IRREVERSIBLE = "irreversible"


class SpeculationRefused(RuntimeError):
    """Raised when a speculative tool call violates the effect-class /
    read-independence / inverse-totality conjunction."""
    pass


class DivergenceLeaseExpired(RuntimeError):
    """Raised when an Auditor divergence arrives after the speculation
    lease closed and the effect can no longer be auto-compensated."""
    pass


@dataclass
class ToolSpec:
    name: str
    effect_class: EffectClass
    inverse: Optional[Callable[[dict], None]] = None
    inverse_is_total: bool = False
    # coarse keys (e.g. (recipient, template_id)) collapse corrections;
    # content hash keeps corrections distinct from duplicates.
    dedup_key_fields: tuple = ("content_hash",)


@dataclass
class CommitRecord:
    intent_id: str
    tool: str
    payload: dict
    verifier_witness: int
    intent_witness: int
    lease_expiry: float
    inverse_ref: Optional[Callable[[dict], None]]
    committed: bool = False


@dataclass
class CommitLedger:
    records: dict = field(default_factory=dict)

    def record(self, rec: CommitRecord) -> None:
        self.records[rec.intent_id] = rec

    def on_divergence(self, intent_id: str, now: float) -> None:
        rec = self.records.get(intent_id)
        if rec is None:
            raise SpeculationRefused(f"no ledger entry for {intent_id}")
        if rec.committed:
            # effect already treated as final; cannot auto-compensate
            raise DivergenceLeaseExpired(
                f"divergence for {intent_id} arrived after commit; escalate to human"
            )
        if now >= rec.lease_expiry:
            raise DivergenceLeaseExpired(
                f"divergence for {intent_id} arrived at {now} >= lease {rec.lease_expiry}"
            )
        if rec.inverse_ref is None:
            raise SpeculationRefused(
                f"compensable effect {intent_id} has no registered inverse"
            )
        rec.inverse_ref(rec.payload)
        rec.committed = True


def speculate(
    tool: ToolSpec,
    payload: dict,
    intent_witness: int,
    verifier_witness: int,
    lease_seconds: float,
    ledger: CommitLedger,
    intent_id: str,
    now: Optional[float] = None,
) -> CommitRecord:
    now = time.monotonic() if now is None else now

    # Invariant 1: irreversible effects must never be speculated.
    if tool.effect_class is EffectClass.IRREVERSIBLE:
        raise SpeculationRefused(
            f"tool {tool.name} is IRREVERSIBLE; must block on verifier confirmation"
        )

    # Invariant 2: verifier read must be causally downstream of intent.
    if verifier_witness <= intent_witness:
        raise SpeculationRefused(
            f"verifier witness {verifier_witness} not strictly newer than "
            f"intent witness {intent_witness}; read-independence unproven"
        )

    # Invariant 3: compensable effects require a total inverse.
    if tool.effect_class is EffectClass.COMPENSABLE:
        if tool.inverse is None or not tool.inverse_is_total:
            raise SpeculationRefused(
                f"compensable tool {tool.name} lacks a total registered inverse"
            )

    rec = CommitRecord(
        intent_id=intent_id,
        tool=tool.name,
        payload=payload,
        verifier_witness=verifier_witness,
        intent_witness=intent_witness,
        lease_expiry=now + lease_seconds,
        inverse_ref=tool.inverse if tool.effect_class is EffectClass.COMPENSABLE else None,
    )
    ledger.record(rec)
    return rec
