# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-optimistic-tool-invocation-as-a-rollback-hazard-when-branches-share-side-effecting-tools.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-optimistic-tool-invocation-as-a-rollback-hazard-when-branches-share-side-effecting-tools.warrant.json
# Markdown SHA-256:   2e36317d8393e1bff0062a07472ff76098107996705c189abb94d7db3c698620
# Code AST SHA-256:   954bfed3b6b3a3e72e71f232fe4da3e1e8bad7169b263895e23d5c3a7a92a818
# Verified Classes:   SpeculativeEffectLeak, ToolSpec, EffectLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List


class SpeculativeEffectLeak(RuntimeError):
    """Raised when a pruned branch left an external side effect unaccounted for."""
    pass


@dataclass
class ToolSpec:
    name: str
    speculation_safe: bool          # may be invoked optimistically
    idempotency_key_dims: List[str] # argument fields that define logical intent


@dataclass
class EffectLedger:
    # intent_key -> list of branch_ids that emitted it
    entries: Dict[str, List[str]] = field(default_factory=dict)

    def record(self, intent_key: str, branch_id: str) -> None:
        self.entries.setdefault(intent_key, []).append(branch_id)

    def orphaned_for(self, surviving_branch: str) -> List[str]:
        return [
            key for key, branches in self.entries.items()
            if surviving_branch not in branches
        ]


def dispatch_optimistic(tool: ToolSpec, args: dict, branch_id: str,
                        ledger: EffectLedger) -> str:
    if not tool.speculation_safe:
        raise SpeculativeEffectLeak(
            f"branch {branch_id} attempted optimistic call to commit-gated "
            f"tool {tool.name!r}; must route through commit barrier"
        )
    intent_key = ":".join(
        f"{dim}={args.get(dim)}" for dim in tool.idempotency_key_dims
    )
    ledger.record(intent_key, branch_id)
    return intent_key


def prune_and_verify(ledger: EffectLedger, surviving_branch: str) -> None:
    orphans = ledger.orphaned_for(surviving_branch)
    if orphans:
        raise SpeculativeEffectLeak(
            f"pruning left {len(orphans)} orphaned external effect(s) "
            f"from discarded branches: {orphans}; compensate or halt"
        )
