# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pre-execute-a2a-delegated-work-that-its-origin-org-will-never-accept-speculative-execution-against-unratified-slas.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pre-execute-a2a-delegated-work-that-its-origin-org-will-never-accept-speculative-execution-against-unratified-slas.warrant.json
# Markdown SHA-256:   ae4fae85d4da062792d18e25b1439cdf8d99db059c4cf6c23d4d7a951e3dbd26
# Code AST SHA-256:   af387b30d252a83e75f8584360ba0f925eb2357fd86915891a9bb851f7eb5234
# Verified Classes:   UnratifiedSpeculationError, SlaState, SpeculationWarrant, TaskEnvelope, CalleeScheduler
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class UnratifiedSpeculationError(RuntimeError):
    """Raised when a callee attempts to commit speculative work without a ratified SLA or speculation warrant."""
    pass


class SlaState(Enum):
    PROPOSED = "proposed"
    RATIFIED = "ratified"
    REJECTED = "rejected"


@dataclass
class SpeculationWarrant:
    max_cost_units: int
    compensable_only: bool = True


@dataclass
class TaskEnvelope:
    task_id: str
    proposal_hash: str
    sla_state: SlaState
    warrant: Optional[SpeculationWarrant] = None


@dataclass
class CalleeScheduler:
    cost_so_far: int = 0
    committed_effects: list = field(default_factory=list)

    def _effects_compensable(self) -> bool:
        # All committed effects must be staging-scoped and reversible.
        return all(e.startswith("staging/") for e in self.committed_effects)

    def may_speculate(self, env: TaskEnvelope) -> bool:
        if env.sla_state is SlaState.RATIFIED:
            return True
        if env.warrant is None:
            return False
        if self.cost_so_far >= env.warrant.max_cost_units:
            return False
        if env.warrant.compensable_only and not self._effects_compensable():
            return False
        return True

    def begin_speculative_execution(self, env: TaskEnvelope) -> str:
        if env.sla_state is SlaState.REJECTED:
            raise UnratifiedSpeculationError(
                f"task {env.task_id}: SLA rejected; execution forbidden"
            )
        if not self.may_speculate(env):
            # Correct behavior: hold, do not start the latency clock.
            raise UnratifiedSpeculationError(
                f"task {env.task_id}: speculation denied — sla_state={env.sla_state.value}, "
                f"warrant={'none' if env.warrant is None else 'exhausted/incopmensable'}, "
                f"cost_so_far={self.cost_so_far}. Transition to AWAITING_RATIFICATION."
            )
        # Speculation permitted: derive a PROVISIONAL warrant id, staging-scoped effects only.
        provisional = "PROVISIONAL-" + hashlib.sha256(
            (env.task_id + env.proposal_hash).encode()
        ).hexdigest()[:16]
        self.committed_effects.append(f"staging/{env.proposal_hash}/draft")
        return provisional
