# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-draft-agent-branches-from-committing-phantom-side-effects-during-optimistic-rollback-reconciliation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-draft-agent-branches-from-committing-phantom-side-effects-during-optimistic-rollback-reconciliation.warrant.json
# Markdown SHA-256:   b48444af75ec5dca3c5daa257a416c8d9b6dca6024e78992c6358f4540c30daa
# Code AST SHA-256:   92cf7f3ccc3c24af493f21249c68ac8c1ba7697abcb2b6cf04b85507af28f845
# Verified Classes:   PhantomEffectError, EffectState, EffectRecord, AuthoritativeLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class PhantomEffectError(RuntimeError):
    """Raised when a branch would be marked rolled back while an effect is unaccounted for."""


class EffectState(Enum):
    PENDING = "pending"
    APPLIED = "applied"
    REVERTED = "reverted"
    NEVER_EMITTED = "never_emitted"
    COMPENSATING = "compensating"
    UNKNOWN = "unknown"


@dataclass
class EffectRecord:
    branch_id: str
    idempotency_key: str
    state: EffectState
    compensator_handle: Optional[str] = None


@dataclass
class AuthoritativeLedger:
    records: dict[str, EffectRecord] = field(default_factory=dict)

    def effects_for(self, branch_id: str) -> list[EffectRecord]:
        return [r for r in self.records.values() if r.branch_id == branch_id]


def reconcile_rollback(ledger: AuthoritativeLedger, branch_id: str) -> str:
    """
    Transition a branch to rolled_back ONLY if every effect is accounted for.
    Returns 'rolled_back' or raises PhantomEffectError to escalate.
    """
    effects = ledger.effects_for(branch_id)
    for eff in effects:
        if eff.state in (EffectState.PENDING, EffectState.UNKNOWN):
            raise PhantomEffectError(
                f"branch {branch_id} has unaccounted effect {eff.idempotency_key} "
                f"in state {eff.state.value}; refusing to mark rolled_back"
            )
        if eff.state == EffectState.COMPENSATING and eff.compensator_handle is None:
            raise PhantomEffectError(
                f"branch {branch_id} effect {eff.idempotency_key} is compensating "
                f"without a live handle; escalation required"
            )
    # All effects are reverted / never_emitted / compensable-with-handle.
    return "rolled_back"
