# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-commit-is-unsafe-under-shared-tool-side-effects.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-commit-is-unsafe-under-shared-tool-side-effects.warrant.json
# Markdown SHA-256:   e57e112cda95e4e9b46b5703f8122a9a49aaa8c1fd11be135ed9dafb03d0bf68
# Code AST SHA-256:   87bd96c05485f801abccd05490b5b2cb6d254b48afcb742a56998ce39ca46f9d
# Verified Classes:   EffectClass, ToolEffect, EffectLedger, UnsafeSpeculativeCommit
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    PURE = "pure"                    # no external effect
    REVERSIBLE = "reversible"        # has an inverse the orchestrator can invoke
    IRREVERSIBLE = "irreversible"    # cannot be undone; must be staged or barred
    OBSERVABLE = "observable"        # visible outside the orchestrator; treat as irreversible


@dataclass
class ToolEffect:
    branch_id: str
    tool: str
    resource_key: str
    effect_class: EffectClass
    compensated: bool = False


@dataclass
class EffectLedger:
    effects: List[ToolEffect] = field(default_factory=list)

    def record(self, effect: ToolEffect) -> None:
        self.effects.append(effect)

    def irreversible_uncompensated(self) -> List[ToolEffect]:
        return [
            e for e in self.effects
            if e.effect_class in (EffectClass.IRREVERSIBLE, EffectClass.OBSERVABLE)
            and not e.compensated
        ]

    def resource_conflicts(self) -> Set[str]:
        seen: Dict[str, str] = {}
        conflicts: Set[str] = set()
        for e in self.effects:
            if e.effect_class in (EffectClass.IRREVERSIBLE, EffectClass.OBSERVABLE):
                if e.resource_key in seen and seen[e.resource_key] != e.branch_id:
                    conflicts.add(e.resource_key)
                seen[e.resource_key] = e.branch_id
        return conflicts


class UnsafeSpeculativeCommit(RuntimeError):
    """Raised when a speculative commit would leave unaccounted physical effects."""
    pass


def audit_before_commit(
    ledger: EffectLedger,
    candidate_branch: str,
    losing_branches: List[str],
) -> None:
    # A losing branch that leaked an irreversible effect invalidates the
    # pristine-world assumption every branch's plan was scored against.
    leaks = [
        e for e in ledger.irreversible_uncompensated()
        if e.branch_id in losing_branches
    ]
    if leaks:
        raise UnsafeSpeculativeCommit(
            f"cannot commit {candidate_branch!r}: losing branches left "
            f"uncompensated irreversible effects "
            f"{[(e.branch_id, e.tool, e.resource_key) for e in leaks]}"
        )

    conflicts = ledger.resource_conflicts()
    if conflicts:
        raise UnsafeSpeculativeCommit(
            f"cannot commit {candidate_branch!r}: overlapping irreversible "
            f"effects on resources {sorted(conflicts)} across branches"
        )

    # Only now may the orchestrator apply the commit and rebase the winner's
    # context onto the actual post-rollback world state.
    return None


def commit_speculative(
    ledger: EffectLedger,
    candidate_branch: str,
    all_branches: List[str],
) -> str:
    losing = [b for b in all_branches if b != candidate_branch]
    audit_before_commit(ledger, candidate_branch, losing)
    return candidate_branch
