# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-multi-agent-rollback-reconciliation-as-a-two-phase-commit-against-a-non-idempotent-world.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-speculative-multi-agent-rollback-reconciliation-as-a-two-phase-commit-against-a-non-idempotent-world.warrant.json
# Markdown SHA-256:   471e2bf49d32d24a9ee8969e7892342917a7107d9c45b3a13e4d1117d782adba
# Code AST SHA-256:   783fc99e75609dce622696f08f5b7e702518137494f363f96b2468d3591dab4f
# Verified Classes:   EffectClass, RollbackReconciliationError, SpeculativeWrite, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class EffectClass(Enum):
    STAGED = "staged"
    COMPENSABLE = "compensable"
    IDEMPOTENT = "idempotent"
    UNSAFE = "unsafe"


class RollbackReconciliationError(RuntimeError):
    """Raised when a speculative rollback leaves world mutations that the
    committed branch's read set will observe, with no staged overlay or
    verified compensator to absorb them."""


@dataclass
class SpeculativeWrite:
    branch_id: str
    target: str          # world region: path, table, channel
    effect_class: EffectClass
    compensated: bool = False   # verified, not merely enqueued


@dataclass
class Branch:
    branch_id: str
    writes: list[SpeculativeWrite] = field(default_factory=list)


def reconcile_rollback(
    committed: Branch,
    discarded: list[Branch],
    committed_read_set: set[str],
) -> list[str]:
    """Return surviving ghosts that intersect the committed read set.

    Raises if any intersecting ghost is UNSAFE or an unverified compensable.
    """
    ghosts: list[str] = []
    for branch in discarded:
        if branch.branch_id == committed.branch_id:
            continue
        for w in branch.writes:
            if w.target not in committed_read_set:
                continue  # ghost survives but is unobservable: safe
            if w.effect_class is EffectClass.STAGED:
                continue  # overlay discarded with the branch
            if w.effect_class is EffectClass.COMPENSABLE and w.compensated:
                continue
            if w.effect_class is EffectClass.IDEMPOTENT:
                continue
            # Intersecting, surviving, un-absorbed world mutation.
            ghosts.append(f"{branch.branch_id}:{w.target}:{w.effect_class.value}")
    if ghosts:
        raise RollbackReconciliationError(
            "speculative rollback left world ghosts in committed read set: "
            + ", ".join(ghosts)
            + "; commit blocked pending reconciliation"
        )
    return ghosts


def commit(committed: Branch, discarded: list[Branch], read_set: set[str]) -> None:
    # Barrier: world epoch at commit must equal spawn epoch, or all
    # intersecting writes must be staged/compensated/idempotent.
    reconcile_rollback(committed, discarded, read_set)
    # ... promote staged overlays, dispatch, advance world epoch ...
