# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-parallel-agent-branches-from-committing-divergent-world-state-after-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-parallel-agent-branches-from-committing-divergent-world-state-after-rollback.warrant.json
# Markdown SHA-256:   45609168ab084f879e977fb482c3f91b9d7ef1e83e65cea19093e569ca5503cb
# Code AST SHA-256:   591b07519b7d0d740e4f1ba3b7416d52d4706d211e24362fa4fee529769f0962
# Verified Classes:   SpeculationDivergenceError, EffectLedger, SpeculativeOrchestrator
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculationDivergenceError(RuntimeError):
    """Raised when a speculative branch produces an effect rollback cannot invert,
    or when a winner's preconditions are invalidated by a loser's uncompensated effect."""
    pass


class EffectLedger:
    def __init__(self):
        self._entries = []  # (branch_id, effect, compensator)

    def record_before_fire(self, branch_id, effect, compensator):
        # Write-ahead: record MUST precede the effect. Compensator must be total.
        if compensator is None:
            raise SpeculationDivergenceError(
                f"branch {branch_id} attempted effect {effect!r} with no total compensator; "
                f"tool must be commit-only and gated behind winner selection"
            )
        self._entries.append((branch_id, effect, compensator))

    def rollback(self, losing_branches):
        for branch_id, effect, compensator in reversed(self._entries):
            if branch_id in losing_branches:
                compensator(effect)  # must be idempotent and a true inverse


class SpeculativeOrchestrator:
    def __init__(self, ledger, safe_tools, commit_only_tools):
        self.ledger = ledger
        self.safe_tools = safe_tools
        self.commit_only_tools = commit_only_tools

    def grant_for(self, branch_id, phase):
        if phase == "speculative":
            return set(self.safe_tools)  # commit-only tools withheld
        return set(self.safe_tools) | set(self.commit_only_tools)

    def reconcile(self, branches, winner_id, preconditions):
        losers = {b.id for b in branches if b.id != winner_id}
        self.ledger.rollback(losers)
        # Re-check winner preconditions against post-rollback world-state.
        for pre in preconditions:
            if not pre.holds():
                raise SpeculationDivergenceError(
                    f"winner {winner_id} precondition {pre.name!r} invalidated by "
                    f"uncompensated loser effect or shared-resource depletion; re-plan required"
                )
        winner = next(b for b in branches if b.id == winner_id)
        for intent in winner.deferred_intents:
            intent.execute()  # commit-only effects fire only here, post-selection
