# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-rollback-will-strand-committed-side-effects-in-multi-agent-draft-and-verify-pipelines.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-speculative-branch-rollback-will-strand-committed-side-effects-in-multi-agent-draft-and-verify-pipelines.warrant.json
# Markdown SHA-256:   4d95d0b20c9610109d26d78783de064119d71414dcad3c2cbcc9ee69da815360
# Code AST SHA-256:   680454f0be0e803595be7ebad7d03f9f7c8da2fc8e3ca3877b7d7dcc3a67b35b
# Verified Classes:   EffectClass, SpeculativeCommitError, EffectRecord, CommitGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EffectClass(Enum):
    BUFFERED = "buffered"
    COMPENSABLE = "compensable"
    IRREVOCABLE = "irrevocable"
    UNKNOWN_HOLD = "unknown_hold"  # default for unregistered tools


class SpeculativeCommitError(RuntimeError):
    """Raised when a speculative commit would strand or duplicate a side effect."""


@dataclass
class EffectRecord:
    branch_id: str
    tool: str
    target: str
    buffer_id: Optional[str]  # None means the effect was NOT intercepted
    effect_class: EffectClass


@dataclass
class CommitGate:
    effect_registry: Dict[str, EffectClass]
    branch_journals: Dict[str, List[EffectRecord]] = field(default_factory=dict)

    def classify(self, tool: str) -> EffectClass:
        # Unknown tools are treated as IRREVOCABLE, never REVERSIBLE.
        return self.effect_registry.get(tool, EffectClass.UNKNOWN_HOLD)

    def record(self, rec: EffectRecord) -> None:
        if rec.effect_class is EffectClass.UNKNOWN_HOLD:
            # An unknown tool reached a draft; it cannot be assumed buffered.
            if rec.buffer_id is not None:
                raise SpeculativeCommitError(
                    f"tool {rec.tool!r} classified UNKNOWN_HOLD but claims buffer "
                    f"{rec.buffer_id!r}; registry out of sync with sandbox"
                )
        self.branch_journals.setdefault(rec.branch_id, []).append(rec)

    def commit(self, committed_branch: str, discarded_branches: List[str]) -> List[EffectRecord]:
        committed = self.branch_journals.get(committed_branch, [])
        committed_targets = {(e.tool, e.target) for e in committed}

        # Signal 1: journal asymmetry — un-buffered effect outside committed branch.
        for bid in discarded_branches:
            for e in self.branch_journals.get(bid, []):
                if e.buffer_id is None and e.effect_class in (
                    EffectClass.IRREVOCABLE,
                    EffectClass.UNKNOWN_HOLD,
                ):
                    raise SpeculativeCommitError(
                        f"discarded branch {bid!r} leaked un-buffered "
                        f"{e.effect_class.value} effect {e.tool!r}->{e.target!r}; "
                        f"commit would strand an irreversible side effect"
                    )

        # Signal 2: duplication — committed branch re-issues a discarded branch's
        # effect against the same target with no compensating entry.
        for bid in discarded_branches:
            for e in self.branch_journals.get(bid, []):
                if (e.tool, e.target) in committed_targets and e.buffer_id is None:
                    raise SpeculativeCommitError(
                        f"duplication risk: committed branch {committed_branch!r} "
                        f"re-issues {e.tool!r}->{e.target!r} already emitted "
                        f"un-buffered by discarded branch {bid!r}"
                    )

        # Signal 3: committed journal must be superset of discarded buffered
        # journals on shared targets (conflict not adjudicated otherwise).
        for bid in discarded_branches:
            for e in self.branch_journals.get(bid, []):
                if e.buffer_id is not None and (e.tool, e.target) in committed_targets:
                    if not any(
                        c.tool == e.tool and c.target == e.target and c.buffer_id is not None
                        for c in committed
                    ):
                        raise SpeculativeCommitError(
                            f"unadjudicated conflict on {e.tool!r}->{e.target!r}: "
                            f"discarded branch {bid!r} buffered an effect the "
                            f"committed branch does not replay"
                        )

        # Replay only the committed branch's buffered journal.
        return [e for e in committed if e.buffer_id is not None]


# --- reproduction of the observed incident ---
registry = {
    "read_ledger": EffectClass.BUFFERED,
    "update_ledger": EffectClass.BUFFERED,
    # "notify" was added to the manifest but never registered:
    # classify() returns UNKNOWN_HOLD.
}
gate = CommitGate(effect_registry=registry)

gate.record(EffectRecord("B", "update_ledger", "cust_42", "buf_b1", EffectClass.BUFFERED))
gate.record(EffectRecord("B", "notify", "cust_42", None, gate.classify("notify")))
gate.record(EffectRecord("C", "update_ledger", "cust_42", "buf_c1", EffectClass.BUFFERED))
gate.record(EffectRecord("C", "notify", "cust_42", None, gate.classify("notify")))

try:
    gate.commit(committed_branch="C", discarded_branches=["A", "B"])
except SpeculativeCommitError as exc:
    print(f"commit held: {exc}")
    # Expected: discarded branch 'B' leaked un-buffered unknown_hold effect
    # 'notify'->'cust_42'; commit would strand an irreversible side effect.
