# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-before-its-hedge-sibling-s-side-effects-are-quiesced.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-before-its-hedge-sibling-s-side-effects-are-quiesced.warrant.json
# Markdown SHA-256:   daa66b9abab627fddee4379b329a03f1e8777601cf2de8ef0fa2ceb43f9bfaa6
# Code AST SHA-256:   de8c199a809d52417e6b6be2a3dca786809e7185fcb39c7b5d0275c3d1937523
# Verified Classes:   SpeculationRollbackError, EffectClass, InFlightCall, SpeculativeBranch, Orchestrator
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum


class SpeculationRollbackError(RuntimeError):
    """Raised when a speculative branch is pruned while it still owns
    un-quiesced effectful tool calls, or when a late response arrives
    for a branch whose correlation ID was dropped instead of tombstoned."""


class EffectClass(Enum):
    PURE = "pure"
    IDEMPOTENT_KEYED = "idempotent_keyed"
    EFFECTFUL = "effectful"


@dataclass
class InFlightCall:
    correlation_id: str
    effect_class: EffectClass
    dispatched_at: float
    acknowledged_cancel: bool = False


@dataclass
class SpeculativeBranch:
    branch_id: str
    in_flight: dict = field(default_factory=dict)
    pruned: bool = False


@dataclass
class Orchestrator:
    max_tool_latency_s: float
    tombstones: dict = field(default_factory=dict)  # corr_id -> pruned branch_id

    def prune(self, branch: SpeculativeBranch, now: float) -> None:
        for corr_id, call in branch.in_flight.items():
            if call.effect_class is EffectClass.EFFECTFUL and not call.acknowledged_cancel:
                raise SpeculationRollbackError(
                    f"branch {branch.branch_id} owns un-quiesced EFFECTFUL call "
                    f"{corr_id}; cannot prune by rollback, require cancel-and-confirm"
                )
        branch.pruned = True
        # tombstone, do NOT drop, every outstanding correlation id
        for corr_id in branch.in_flight:
            self.tombstones[corr_id] = branch.branch_id

    def on_late_response(self, corr_id: str, now: float) -> str:
        if corr_id not in self.tombstones:
            raise SpeculationRollbackError(
                f"late response for unknown correlation id {corr_id}; "
                f"branch was dropped, not tombstoned — silent state fork"
            )
        branch_id = self.tombstones[corr_id]
        # reconcile: compensating action or dedupe by branch key
        return f"reconciled late effect from pruned branch {branch_id}"

    def commit_sibling(self, branch: SpeculativeBranch, concurrent: list) -> None:
        for other in concurrent:
            for corr_id, call in other.in_flight.items():
                if corr_id not in self.tombstones and not call.acknowledged_cancel:
                    raise SpeculationRollbackError(
                        f"cannot commit {branch.branch_id}: concurrent branch "
                        f"{other.branch_id} has un-quiesced call {corr_id}"
                    )
        branch.committed = True
