# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-pre-executes-delegated-tool-calls-speculatively-and-the-a2a-task-warrant-is-revoked-mid-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-pre-executes-delegated-tool-calls-speculatively-and-the-a2a-task-warrant-is-revoked-mid-commit.warrant.json
# Markdown SHA-256:   8ce5618db6b9d2c8423b53923451855da4d9722b7256d3c84f78593b52ab7ed9
# Code AST SHA-256:   58479b83e85843afe22d53c36cb2741e1218d65328b977336b79e807387e1ff8
# Verified Classes:   SpeculativeCommitViolation, Warrant, SpeculativeResult, DelegationEnvelope, Orchestrator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a speculative side effect would be committed or discarded
    without a valid warrant covering that transition, or when a landed
    side effect has no pre-authorized compensating warrant."""
    pass


@dataclass
class Warrant:
    nonce: str
    scope: str
    expires_at: float
    revoked: bool = False
    superseded_epoch: Optional[int] = None


@dataclass
class SpeculativeResult:
    receipt_id: str
    spec_epoch: int
    landed: bool
    state: str = "PENDING"  # PENDING | COMMITTED | ABORTED_COMPENSATED | ORPHANED


@dataclass
class DelegationEnvelope:
    warrant: Warrant
    inverse_warrant: Optional[Warrant]  # pre-provisioned W^-1
    seed_epoch: int


class Orchestrator:
    def __init__(self, current_epoch: int):
        self.current_epoch = current_epoch
        self.pending: dict[str, SpeculativeResult] = {}

    def speculate(self, envelope: DelegationEnvelope, tool_call) -> SpeculativeResult:
        # Dispatch speculatively BEFORE the delegate acks.
        result = tool_call()  # returns (receipt_id, landed)
        receipt_id, landed = result
        spec = SpeculativeResult(
            receipt_id=receipt_id,
            spec_epoch=envelope.seed_epoch,
            landed=landed,
        )
        self.pending[receipt_id] = spec
        return spec

    def observe_warrant_transition(self, envelope: DelegationEnvelope, revoked: bool, new_epoch: int):
        if revoked:
            envelope.warrant.revoked = True
        envelope.warrant.superseded_epoch = new_epoch
        self.current_epoch = new_epoch

    def commit(self, envelope: DelegationEnvelope, spec: SpeculativeResult):
        w = envelope.warrant
        # Fence: commit only if warrant valid AND spec epoch is not stale.
        if w.revoked or time.time() > w.expires_at:
            raise SpeculativeCommitViolation(
                f"commit of {spec.receipt_id} blocked: warrant {w.nonce} revoked/expired"
            )
        if spec.spec_epoch < (w.superseded_epoch or -1):
            raise SpeculativeCommitViolation(
                f"commit of {spec.receipt_id} blocked: spec_epoch {spec.spec_epoch} "
                f"stale vs warrant epoch {w.superseded_epoch}"
            )
        if not spec.landed:
            raise SpeculativeCommitViolation(
                f"commit of {spec.receipt_id} blocked: side effect not landed, nothing to commit"
            )
        spec.state = "COMMITTED"

    def abort_on_revoke(self, envelope: DelegationEnvelope, spec: SpeculativeResult):
        if not spec.landed:
            spec.state = "ABORTED_COMPENSATED"  # nothing landed, safe discard
            return
        # Landed side effect: must compensate, never silently discard.
        if envelope.inverse_warrant is None:
            spec.state = "ORPHANED"
            raise SpeculativeCommitViolation(
                f"landed side effect {spec.receipt_id} has no pre-authorized "
                f"compensating warrant; task must escalate, not discard"
            )
        if envelope.inverse_warrant.revoked or time.time() > envelope.inverse_warrant.expires_at:
            spec.state = "ORPHANED"
            raise SpeculativeCommitViolation(
                f"compensating warrant {envelope.inverse_warrant.nonce} invalid; "
                f"{spec.receipt_id} cannot be rolled back"
            )
        # Invoke inverse tool under W^-1.
        spec.state = "ABORTED_COMPENSATED"
