# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-side-effecting-tool-call-in-a-parallel-branch-and-the-reconciler-must-roll-back-against-a-non-id.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-speculatively-commits-a-side-effecting-tool-call-in-a-parallel-branch-and-the-reconciler-must-roll-back-against-a-non-id.warrant.json
# Markdown SHA-256:   089b9a2ad81cb2c8840eac06df1889e730eac58ccdf747adb4a7c2c02713b129
# Code AST SHA-256:   4a16fd4560fd435ce33d8808a9195642dbcb10bb0f274c9beff89edc3d43b6b7
# Verified Classes:   ReconciliationHalt, EffectRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class ReconciliationHalt(RuntimeError):
    """Raised when the reconciler cannot prove compensation ownership from the effect ledger."""
    pass

@dataclass(frozen=True)
class EffectRecord:
    tool: str
    canonical_args: str
    idempotency_key: str
    branch_id: str
    observed_status: int
    external_handle: Optional[str]  # None or "UNKNOWN" => never observed

def reconcile_losing_branch(
    branch_id: str,
    declared_effects: list[EffectRecord],
    ledger: dict[tuple[str, str], list[EffectRecord]],
    winner_handles: set[str],
) -> list[str]:
    """
    Return compensating actions for a losing branch, or raise ReconciliationHalt.
    Compensation is only emitted for handles the losing branch actually observed
    AND that no winner owns.
    """
    compensations: list[str] = []

    for declared in declared_effects:
        key = (declared.tool, declared.canonical_args)
        observed = [r for r in ledger.get(key, []) if r.branch_id == branch_id]

        if not observed:
            # Branch declared a mutation the transport never recorded.
            # State is unknown; do not assume applied, do not assume absent.
            raise ReconciliationHalt(
                f"branch {branch_id} declared {declared.tool}({declared.canonical_args}) "
                f"but ledger has no entry; mutation state unknown"
            )

        for rec in observed:
            if rec.external_handle in (None, "UNKNOWN"):
                # Synthesized success from a retry-exhaustion path.
                # Cannot compensate what we cannot address.
                raise ReconciliationHalt(
                    f"branch {branch_id} has UNKNOWN handle for "
                    f"{rec.tool}({rec.canonical_args}); refusing compensation"
                )
            if rec.external_handle in winner_handles:
                # Handle collision: resource is shared with a committed winner.
                # Deduplicate, never delete.
                continue
            compensations.append(f"undo:{rec.tool}:{rec.external_handle}")

    return compensations
