# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-phantom-side-effects-during-speculative-branch-rollback-before-merge-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-phantom-side-effects-during-speculative-branch-rollback-before-merge-reconciliation.warrant.json
# Markdown SHA-256:   e9e802ca4f3e0626e62f0dc2e82bc576f5eee53f293f3dc1b3168dd8790aeea0
# Code AST SHA-256:   d58c31875866eb0d90827a26a32de169ce8146ddf5befffb4e948c408bbcac27
# Verified Classes:   EffectClass, PhantomEffectError, EffectRecord, Branch
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class EffectClass(Enum):
    READONLY = "readonly"
    FENCED = "fenced"
    INVERTIBLE = "invertible"
    IRREVERSIBLE = "irreversible"


class PhantomEffectError(RuntimeError):
    """Raised when merge reconciliation finds an uncompensated effect
    emitted by a losing branch that the system believes never ran."""


@dataclass
class EffectRecord:
    branch_id: str
    effect_seq: int
    tool: str
    effect_class: EffectClass
    undo_descriptor: Optional[str]  # None means "no inverse available"
    compensated: bool = False


@dataclass
class Branch:
    branch_id: str
    tools: list[str]
    effects: list[EffectRecord] = field(default_factory=list)


def plan_speculation(branch: Branch, tool_registry: dict[str, EffectClass]) -> bool:
    """Return True iff the branch may be speculated in parallel.

    An instance must NOT speculate a branch whose tool set contains any
    IRREVERSIBLE tool, regardless of branch confidence or trace length.
    """
    for tool in branch.tools:
        cls = tool_registry.get(tool)
        if cls is None:
            raise PhantomEffectError(
                f"tool {tool!r} in branch {branch.branch_id!r} has no "
                f"declared effect_class; cannot reason about rollback safety"
            )
        if cls is EffectClass.IRREVERSIBLE:
            return False
    return True


def reconcile_effects(
    branches: list[Branch],
    winner_id: str,
) -> None:
    """Effect reconciliation gate. Must run between 'merge decided' and
    'merge committed'. Raises if the union-minus-winner effect set is
    non-empty and not fully compensated.
    """
    winner_effects = {
        (e.branch_id, e.effect_seq)
        for b in branches
        if b.branch_id == winner_id
        for e in b.effects
    }
    orphans: list[EffectRecord] = []
    for b in branches:
        if b.branch_id == winner_id:
            continue
        for e in b.effects:
            if (e.branch_id, e.effect_seq) in winner_effects:
                continue
            if not e.compensated:
                orphans.append(e)

    if orphans:
        detail = ", ".join(
            f"{e.branch_id}#{e.effect_seq}:{e.tool}({e.effect_class.value})"
            for e in orphans
        )
        raise PhantomEffectError(
            f"merge of winner {winner_id!r} would discard "
            f"{len(orphans)} uncompensated effect(s): {detail}. "
            f"Rollback is causally incomplete; abort merge and escalate."
        )
