# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-between-speculative-branches-and-the-committed-tool-effect-log.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-divergence-between-speculative-branches-and-the-committed-tool-effect-log.warrant.json
# Markdown SHA-256:   3f21f59ff6bae5e642f6bd10b44d2279995926eb7e81b6044988045af2b4c50d
# Code AST SHA-256:   59511ffd2b753369943ac93f28b276f0de689f96f344806f7856c1a0676f3faa
# Verified Classes:   EffectDispositionError, EffectClass, EffectTarget, BranchEffectLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class EffectDispositionError(RuntimeError):
    """Raised when a speculative branch would produce an effect it cannot dispose of."""
    pass


class EffectClass(Enum):
    READ_ONLY = "read_only"
    COMPENSABLE = "compensable"
    ADOPTABLE = "adoptable"
    IRREVERSIBLE = "irreversible"


@dataclass(frozen=True)
class EffectTarget:
    tool: str
    resource: str          # concrete resource id, e.g. "order:8812"
    intent_key: str        # semantic idempotency key, NOT branch-scoped


@dataclass
class BranchEffectLedger:
    branch_id: str
    fired: list = field(default_factory=list)
    staged: list = field(default_factory=list)

    def record_fired(self, target: EffectTarget) -> None:
        self.fired.append(target)

    def record_staged(self, target: EffectTarget) -> None:
        self.staged.append(target)


def authorize_optimistic_dispatch(
    branch: BranchEffectLedger,
    target: EffectTarget,
    effect_class: EffectClass,
    compensator_is_order_independent: bool,
    sibling_targets: list,
) -> Optional[str]:
    """
    Returns None if the branch may fire the effect optimistically.
    Returns "staged" if the effect must be held until commit.
    Raises EffectDispositionError if speculation is unsafe for this (tool, resource).
    """
    if effect_class is EffectClass.READ_ONLY:
        return None

    if effect_class is EffectClass.IRREVERSIBLE:
        branch.record_staged(target)
        return "staged"

    if effect_class is EffectClass.COMPENSABLE and not compensator_is_order_independent:
        branch.record_staged(target)
        return "staged"

    # Non-commutative sibling effects on the same resource: refuse to fork.
    for sib in sibling_targets:
        if sib.resource == target.resource and sib.tool == target.tool:
            raise EffectDispositionError(
                f"branch {branch.branch_id}: non-commutative speculative effect on "
                f"{target.resource} via {target.tool}; serialize or partition instead of forking"
            )

    # Intent-scoped idempotency precondition.
    if target.intent_key.startswith("branch:"):
        raise EffectDispositionError(
            f"branch {branch.branch_id}: intent_key {target.intent_key!r} is branch-scoped; "
            "sibling duplicates will not be deduplicated"
        )

    branch.record_fired(target)
    return None


def rollback_branch(
    branch: BranchEffectLedger,
    compensators: dict,
) -> None:
    """Dispose of a non-committed branch's effect set. Must account for every fired effect."""
    for target in reversed(branch.fired):
        comp = compensators.get(target.tool)
        if comp is None:
            raise EffectDispositionError(
                f"branch {branch.branch_id}: fired {target.tool} on {target.resource} "
                "with no registered compensator; effect is now an orphan requiring reconciliation"
            )
        comp(target)
    branch.fired.clear()
    branch.staged.clear()
