# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-fork-commit-boundary-when-speculative-branches-share-a-mutable-tool-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-fork-commit-boundary-when-speculative-branches-share-a-mutable-tool-surface.warrant.json
# Markdown SHA-256:   44391a95993f24957ec60f676d92dc08447e6c44805dcab7be33e3584fa2aa58
# Code AST SHA-256:   e1f05dfa632af18cc2f5dd4b1f1c18108688a8ddd983780a20a58b6d26d4dd0d
# Verified Classes:   EffectLatency, Observability, ToolProfile, BranchPlan, SpeculativeForkBoundaryError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectLatency(Enum):
    IMMEDIATE = "immediate"
    DEFERRED = "deferred"


class Observability(Enum):
    BRANCH_SCOPED = "branch_scoped"
    SHARED = "shared"


@dataclass(frozen=True)
class ToolProfile:
    name: str
    latency: EffectLatency
    observability: Observability
    has_lease: bool = False


@dataclass
class BranchPlan:
    branch_id: str
    tool_sequence: list[ToolProfile] = field(default_factory=list)


class SpeculativeForkBoundaryError(RuntimeError):
    """Raised when a branch would cross an immediate-shared tool before verification."""


def first_commit_point(plan: BranchPlan) -> int | None:
    """Index of the earliest call that commits the branch (immediate + shared, no lease)."""
    for i, tool in enumerate(plan.tool_sequence):
        if (
            tool.latency is EffectLatency.IMMEDIATE
            and tool.observability is Observability.SHARED
            and not tool.has_lease
        ):
            return i
    return None


def admit_fork(plan: BranchPlan, verify_index: int) -> None:
    """
    Admit a branch for speculative execution only if its commit point is not
    crossed before the verifier runs. verify_index is the position in the
    sequence at which the verifier will select a winner.
    """
    commit = first_commit_point(plan)
    if commit is None:
        return  # safe: no immediate-shared tool, or all leased
    if commit < verify_index:
        offending = plan.tool_sequence[commit]
        raise SpeculativeForkBoundaryError(
            f"branch {plan.branch_id!r} crosses commit point at index {commit} "
            f"via immediate-shared tool {offending.name!r} before verification "
            f"at index {verify_index}; leaked speculative effect is not "
            f"compensable by rollback — acquire a lease or defer the call"
        )


def reconcile_after_commit(plan: BranchPlan, observer_registry: Callable[[str], list[str]]) -> list[str]:
    """
    For branches already past their commit point, rollback is a fiction.
    Emit reconciliation events to every registered observer instead.
    """
    commit = first_commit_point(plan)
    if commit is None:
        return []
    tool = plan.tool_sequence[commit]
    observers = observer_registry(tool.name)
    if not observers:
        raise SpeculativeForkBoundaryError(
            f"branch {plan.branch_id!r} committed via {tool.name!r} but no "
            f"observers are registered; downstream reactions cannot be "
            f"reconciled and must be treated as permanent"
        )
    return [f"reconcile:{tool.name}->{o}" for o in observers]


# Example trace: two branches race on a shared reservation with no lease.
reserve_no_lease = ToolProfile("inventory.reserve", EffectLatency.IMMEDIATE, Observability.SHARED)
branch_a = BranchPlan("A", [reserve_no_lease])
admit_fork(branch_a, verify_index=1)  # raises: commit at 0 < verify at 1
