# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-rollback-depth-versus-reconciliation-authority-in-speculative-multi-agent-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-a-speculative-branch-rollback-depth-versus-reconciliation-authority-in-speculative-multi-agent-execution.warrant.json
# Markdown SHA-256:   630cb324b2a3baffdd19cb0493017e7cf81a14925d81a19f30e0f63358590f09
# Code AST SHA-256:   fa4877ccd0da5e03db9f108773c3a1478a6ca61e5654ddabc6e654b24117b14b
# Verified Classes:   ReconciliationError, EffectClass, Effect, Branch, Ledger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ReconciliationError(RuntimeError):
    """Raised when reconciliation would accept a branch against a corrupted or unattributable world state."""
    pass


class EffectClass(Enum):
    REVERSIBLE = "reversible"      # ledgered, deep-rollbackable
    IRREVERSIBLE = "irreversible"  # consumed external resource; rollback forbidden


@dataclass
class Effect:
    branch_id: str
    key: str
    cls: EffectClass
    seq: int


@dataclass
class Branch:
    branch_id: str
    declared_output: str
    read_set: Set[str] = field(default_factory=set)
    effects: list = field(default_factory=list)

    @property
    def committed_depth(self) -> int:
        return max((e.seq for e in self.effects), default=-1)

    @property
    def has_irreversible(self) -> bool:
        return any(e.cls is EffectClass.IRREVERSIBLE for e in self.effects)


class Ledger:
    """Single source of truth for commit/rollback depth. Never garbage-collect tombstones."""

    def __init__(self):
        self._seq = 0
        self.store: Dict[str, Effect] = {}
        self.tombstones: Dict[str, list] = {}

    def commit(self, branch: Branch, key: str, cls: EffectClass) -> None:
        self._seq += 1
        eff = Effect(branch.branch_id, key, cls, self._seq)
        branch.effects.append(eff)
        self.store[key] = eff

    def rollback(self, branch: Branch) -> int:
        """Roll back only to the depth of the shallowest committed effect actually in the store.
        Refuses if the branch holds an irreversible effect (must be promoted, not rolled back)."""
        if branch.has_irreversible:
            raise ReconciliationError(
                f"branch {branch.branch_id} holds an irreversible effect; "
                f"it is committed, not speculative, and cannot be rolled back"
            )
        depth = branch.committed_depth
        removed = [k for k, e in list(self.store.items())
                   if e.branch_id == branch.branch_id and e.seq <= depth]
        for k in removed:
            del self.store[k]
        self.tombstones[branch.branch_id] = list(branch.effects)  # retain for attribution
        return depth


def reconcile(ledger: Ledger, survivors: list, rolled_back: list) -> list:
    """Reconciler MUST hold the ledger. Refuses to accept against orphaned or unreadable state."""
    accepted = []
    for b in survivors:
        # clause 1: no orphaned residue from rolled-back branches
        orphaned = {k for k, e in ledger.store.items()
                    if any(e.branch_id == rb.branch_id for rb in rolled_back)}
        if orphaned:
            raise ReconciliationError(
                f"orphaned effects {sorted(orphaned)} survive rollback; "
                f"shallow rollback detected, refusing to reconcile"
            )
        # clause 3: branch read a fact that is now removed -> tainted premise
        removed_keys = {e.key for rb in rolled_back for e in ledger.tombstones.get(rb.branch_id, [])}
        tainted = b.read_set & removed_keys
        if tainted:
            raise ReconciliationError(
                f"branch {b.branch_id} read {sorted(tainted)} which a rolled-back branch authored; "
                f"premise no longer valid, re-derive required"
            )
        accepted.append(b)
    return accepted
