# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-branch-commit-when-rollback-reconciliation-detects-divergent-side-effect-ledgers-across-paralle.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abandon-speculative-branch-commit-when-rollback-reconciliation-detects-divergent-side-effect-ledgers-across-paralle.warrant.json
# Markdown SHA-256:   6e737c1b236d1e62399b61f9cfc3d13bc3477f8d12793a32d0c055807c4044c5
# Code AST SHA-256:   4a9c5ab6686610b6c7717a856c21d423a6af5c395d5d34335b50c302011e8497
# Verified Classes:   MutationClass, OutcomeDeterminism, LedgerEntry, SpeculativeCommitUnsound
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class MutationClass(Enum):
    READ_ONLY = "read_only"
    PARTITION_ISOLATED = "partition_isolated"
    SHARED_MUTABLE = "shared_mutable"


class OutcomeDeterminism(Enum):
    DETERMINISTIC = "deterministic"
    AMBIGUOUS = "ambiguous"  # timeouts, empty bodies, 5xx-no-body


@dataclass
class LedgerEntry:
    branch_id: str
    logical_step: int
    tool: str
    mutation_class: MutationClass
    idempotency_key: str
    dispatched: bool = True
    compensation_handle: str | None = None  # None => unknown, cannot roll back
    outcome: OutcomeDeterminism = OutcomeDeterminism.DETERMINISTIC


class SpeculativeCommitUnsound(RuntimeError):
    pass


def assert_speculative_commit_sound(entries: list[LedgerEntry]) -> None:
    """Raise if rollback reconciliation cannot be trusted for this fork set."""
    # Invariant 1: no shared-mutable mutation may be speculatively committed
    # unless every dispatched call has a determinable compensation handle.
    shared = [e for e in entries if e.mutation_class is MutationClass.SHARED_MUTABLE]
    if shared:
        unknown = [e for e in shared if e.compensation_handle is None]
        if unknown:
            raise SpeculativeCommitUnsound(
                f"cannot roll back {len(unknown)} shared-mutable call(s) with "
                f"unknown compensation handle; branch contexts cannot substitute "
                f"for a write-ahead ledger: "
                f"{[(e.branch_id, e.tool, e.logical_step) for e in unknown]}"
            )
        # Invariant 2: distinct branches on a shared resource must not rely on
        # per-branch idempotency keys for isolation -- the resource aggregates.
        keys_by_step: dict[int, set[str]] = {}
        for e in shared:
            keys_by_step.setdefault(e.logical_step, set()).add(e.idempotency_key)
        for step, keys in keys_by_step.items():
            if len(keys) > 1:
                raise SpeculativeCommitUnsound(
                    f"step {step} dispatched {len(keys)} distinct idempotency keys "
                    f"against a shared-mutable resource; per-branch keys do not "
                    f"isolate aggregated state (overcommit risk)"
                )
    # Invariant 3: ambiguous outcomes on shared state require world-audit,
    # never silent rollback.
    ambiguous = [
        e for e in shared if e.outcome is OutcomeDeterminism.AMBIGUOUS
    ]
    if ambiguous:
        raise SpeculativeCommitUnsound(
            f"{len(ambiguous)} dispatched call(s) had ambiguous outcomes; "
            f"rollback must be replaced by an out-of-band world audit: "
            f"{[(e.branch_id, e.tool) for e in ambiguous]}"
        )


def reconcile_fork_set(entries: list[LedgerEntry], chosen_branch: str) -> list[LedgerEntry]:
    """Attempt rollback of non-chosen branches; refuse if unsound."""
    assert_speculative_commit_sound(entries)
    to_compensate = [
        e for e in entries
        if e.branch_id != chosen_branch and e.dispatched
    ]
    # Only reachable when every entry is partition-isolated or has a handle.
    return to_compensate
