# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-an-optimistic-tool-invocation-has-already-committed-side-effects-when-its-speculative-branch-is-rolled-back.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-an-optimistic-tool-invocation-has-already-committed-side-effects-when-its-speculative-branch-is-rolled-back.warrant.json
# Markdown SHA-256:   2ccbc9988d391835df98a68994485d407775dbf0839c2b9f8015a42a7ecb6368
# Code AST SHA-256:   2bcd6de472598483eb699882c2c2882ee79c23d6e0803c6cfe83edc3eab15d8f
# Verified Classes:   OrphanedEffectError, EffectJournal
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class OrphanedEffectError(RuntimeError):
    """Raised when a rolled-back speculative branch left external mutations
    with no surviving attributable record in the reconciliation scope."""
    pass


@dataclass
class EffectJournal:
    # Durable, branch-indexed. Survives branch rollback by design.
    commits: Dict[str, List[str]] = field(default_factory=dict)

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


def reconcile_after_arbitration(
    journal: EffectJournal,
    winning_branch: str,
    declared_effects: Set[str],
    rolled_back_branches: List[str],
) -> None:
    """Verify that no rolled-back branch orphaned an external mutation.

    Invariant: every journaled commit from a rolled-back branch must either
    be compensated or explicitly promoted into the reconciliation scope.
    """
    orphaned: List[str] = []
    for branch in rolled_back_branches:
        for commit_id in journal.commits.get(branch, []):
            if commit_id not in declared_effects:
                orphaned.append(f"{branch}:{commit_id}")

    if orphaned:
        raise OrphanedEffectError(
            "Speculative rollback left unattributed external mutations: "
            f"{orphaned}. Winning branch '{winning_branch}' does not account "
            "for these commits; compensate before finalization."
        )
