# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-swarm-branch-and-the-rollback-journal-diverges-from-peer-observed-tool-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-forks-a-swarm-branch-and-the-rollback-journal-diverges-from-peer-observed-tool-effects.warrant.json
# Markdown SHA-256:   50ce769217794a7411cb3bcbe428f7ccb82e2ee2554768291d98a961914905c2
# Code AST SHA-256:   1dd72b238f5ebbb819b6d4b26a10fbbb95bd9fbcdef7738a26b704860dce1da7
# Verified Classes:   SpeculativeRollbackError, ToolCapability, Effect, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class SpeculativeRollbackError(RuntimeError):
    """Raised when a speculative fork/rollback would leak un-attributed effects."""


@dataclass
class ToolCapability:
    name: str
    idempotent: bool
    attributable: bool  # supports (branch_id, idempotency_key) scoping


@dataclass
class Effect:
    branch_id: str
    tool: str
    resource_id: str
    idempotency_key: str | None


@dataclass
class Branch:
    branch_id: str
    ledger: list[Effect] = field(default_factory=list)
    score: float = 0.0


def audit_fork_safety(tools: list[ToolCapability]) -> None:
    """Must run BEFORE forking. Refuses forks that cannot be rolled back safely."""
    unsafe = [t.name for t in tools if not t.idempotent and not t.attributable]
    if unsafe:
        raise SpeculativeRollbackError(
            f"cannot speculatively fork: tools {unsafe} are non-idempotent and "
            f"un-attributable; effect rollback is not guaranteed"
        )


def reconcile(
    branches: list[Branch],
    winner_id: str,
    compensations: dict[tuple[str, str], Callable[[], None]],
) -> list[Effect]:
    """Discard losers, but first sweep their ledgers for un-compensated effects."""
    winner = next(b for b in branches if b.branch_id == winner_id)
    compensated = {(e.tool, e.resource_id) for e in winner.ledger}
    orphans: list[Effect] = []

    for b in branches:
        if b.branch_id == winner_id:
            continue
        for e in b.ledger:
            key = (e.tool, e.resource_id)
            if key in compensated:
                continue  # effect is owned by the committed plan
            comp = compensations.get(key)
            if comp is None:
                orphans.append(e)  # leaked: created by a loser, unmanaged by winner
                continue
            comp()  # execute compensating action, then treat as rolled back

    if orphans:
        raise SpeculativeRollbackError(
            f"rollback of branches "
            f"{[b.branch_id for b in branches if b.branch_id != winner_id]} "
            f"leaked {len(orphans)} un-compensated effects: "
            f"{[(o.tool, o.resource_id, o.branch_id) for o in orphans]}"
        )
    return orphans


# Example: B1 created r-42, B2 "won" by observing B1's 409, no compensation registered.
tools = [
    ToolCapability("provision_resource", idempotent=False, attributable=True),
]
audit_fork_safety(tools)  # passes: attributable, so we may fork with keys

branches = [
    Branch("B1", ledger=[Effect("B1", "provision_resource", "r-42", "k-b1")], score=0.4),
    Branch("B2", ledger=[], score=0.9),  # won by contamination
    Branch("B3", ledger=[], score=0.1),
]
reconcile(branches, winner_id="B2", compensations={})
# raises SpeculativeRollbackError: r-42 is an orphan owned by discarded B1
