# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-reconciliation-rather-than-attempt-to-merge-it.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-abort-a-speculative-branch-before-reconciliation-rather-than-attempt-to-merge-it.warrant.json
# Markdown SHA-256:   7129c1305a8b320df3197db3e39ca092bce04409ddd5a0a921358b8121c47053
# Code AST SHA-256:   2ace236910c1c8d3d652630e97e6e3c8ac212a7455b64f4f4fb7c9e941c5a30c
# Verified Classes:   SpeculativeMergeError, MergeDecision, EffectRecord, Branch
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class SpeculativeMergeError(RuntimeError):
    """Raised when a branch that crossed the effect boundary is about to be merged."""


class MergeDecision(Enum):
    MERGE = "merge"
    SERIALIZE = "serialize"
    ABORT = "abort"


@dataclass(frozen=True)
class EffectRecord:
    tool: str
    target: str
    effect_key: str          # identity of the EFFECT, not the request
    idempotency_asserted: bool
    compensation: Optional[str] = None


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


def classify(branch: Branch) -> MergeDecision:
    """A branch with any un-compensable non-idempotent effect is a committed writer."""
    for e in branch.effects:
        if not e.idempotency_asserted and e.compensation is None:
            return MergeDecision.ABORT
    if branch.effects:
        return MergeDecision.SERIALIZE
    return MergeDecision.MERGE


def reconcile(a: Branch, b: Branch) -> MergeDecision:
    da, db = classify(a), classify(b)
    if MergeDecision.ABORT in (da, db):
        raise SpeculativeMergeError(
            f"branch {a.branch_id if da is MergeDecision.ABORT else b.branch_id} "
            f"crossed the effect boundary with no registered compensation; "
            f"merge forbidden regardless of diff compatibility"
        )

    # Effect intersection on (target, effect_key) — the real merge gate.
    key_a = {(e.target, e.effect_key) for e in a.effects if not e.idempotency_asserted}
    key_b = {(e.target, e.effect_key) for e in b.effects if not e.idempotency_asserted}
    shared_targets = {t for t, _ in key_a} & {t for t, _ in key_b}
    for t in shared_targets:
        ka = {k for tt, k in key_a if tt == t}
        kb = {k for tt, k in key_b if tt == t}
        if ka != kb:
            # divergent non-idempotent effects on same target, distinct keys
            return MergeDecision.SERIALIZE
    return MergeDecision.MERGE


# The duplicate-refund trace: two branches, distinct agent-minted request ids,
# identical diffs. classify() must force ABORT, not MERGE.
branch_a = Branch("A", [EffectRecord("refund.create", "order:8821",
                                     "refund:8821:req-a1", idempotency_asserted=False)])
branch_b = Branch("B", [EffectRecord("refund.create", "order:8821",
                                     "refund:8821:req-b7", idempotency_asserted=False)])

decision = reconcile(branch_a, branch_b)  # raises SpeculativeMergeError
