# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-speculative-branch-side-effects-before-merging-a-speculative-agent-tree.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reconcile-speculative-branch-side-effects-before-merging-a-speculative-agent-tree.warrant.json
# Markdown SHA-256:   180fb753d1f34d3ac6d51a4e7699736fb6ea9fafbb1f96f879c765311ec7c385
# Code AST SHA-256:   82adeab5d1275accfd3b9f822a13693f96d2dcce69a5cf2b32aa6c706aa0ce4f
# Verified Classes:   UnreconciledBranchEffects, Effect, Branch, MergeDecision
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from collections import defaultdict


class UnreconciledBranchEffects(RuntimeError):
    """Raised when a speculative merge would commit a success state while
    discarded branches have left durable, uncompensated external effects."""
    pass


@dataclass
class Effect:
    branch_id: str
    tool: str
    args: dict
    idempotency_key: str | None
    applied: bool


@dataclass
class Branch:
    branch_id: str
    selected: bool
    assumed_effects: list[Effect] = field(default_factory=list)


@dataclass
class MergeDecision:
    disposition: str          # "reconcile-and-commit" | "commit-without-discard" | "abort-and-escalate"
    net_effects: list[Effect]
    unreconciled: list[Effect]


def reconcile_merge(branches: list[Branch], ledger: list[Effect]) -> MergeDecision:
    """Gate the merge of a speculative branch tree against its effect ledger.

    Invariant: a success commit is permitted only if the union of branch
    effects, deduplicated by idempotency key, equals the effects the selected
    branch assumes were applied.
    """
    if not branches:
        raise UnreconciledBranchEffects("merge invoked with no branches")

    applied = [e for e in ledger if e.applied]

    # Deduplicate by idempotency key; effects without a key are never deduped
    # (they are exactly the non-idempotent calls that cause double-application).
    seen: dict[str, Effect] = {}
    deduped: list[Effect] = []
    for e in applied:
        if e.idempotency_key is not None and e.idempotency_key in seen:
            continue
        if e.idempotency_key is not None:
            seen[e.idempotency_key] = e
        deduped.append(e)

    selected = [b for b in branches if b.selected]
    if len(selected) != 1:
        raise UnreconciledBranchEffects(
            f"expected exactly one selected branch, found {len(selected)}"
        )

    assumed = selected[0].assumed_effects
    assumed_keys = {(e.tool, e.idempotency_key) for e in assumed if e.idempotency_key}
    actual_keys = {(e.tool, e.idempotency_key) for e in deduped if e.idempotency_key}

    # Effects with no idempotency key cannot be matched to the assumption;
    # any such effect from a non-selected branch is unreconciled by definition.
    unreconciled = [
        e for e in deduped
        if e.idempotency_key is None
        and not any(b.selected and b.branch_id == e.branch_id for b in branches)
    ]

    extra = actual_keys - assumed_keys
    missing = assumed_keys - actual_keys

    if extra or missing or unreconciled:
        # Cannot reconstruct a clean net state -> must not report success.
        if all(e.idempotency_key is not None for e in deduped):
            # Deduplicable but divergent: reconcile, do not claim success blindly.
            return MergeDecision(
                disposition="reconcile-and-commit",
                net_effects=deduped,
                unreconciled=unreconciled,
            )
        return MergeDecision(
            disposition="abort-and-escalate",
            net_effects=deduped,
            unreconciled=unreconciled + [e for e in deduped if e.idempotency_key is None],
        )

    return MergeDecision(disposition="commit-without-discard", net_effects=deduped, unreconciled=[])


def commit(decision: MergeDecision) -> str:
    if decision.disposition == "abort-and-escalate":
        raise UnreconciledBranchEffects(
            f"merge aborted: {len(decision.unreconciled)} unreconciled branch effect(s) "
            f"cannot be compensated; escalate to human reconciliation"
        )
    if decision.disposition == "reconcile-and-commit" and decision.unreconciled:
        raise UnreconciledBranchEffects(
            "reconcile path still holds unreconciled effects; refusing success commit"
        )
    return f"committed under disposition={decision.disposition}"
