# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-parallel-branch-mid-lease-rather-than-reconcile-it.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-parallel-branch-mid-lease-rather-than-reconcile-it.warrant.json
# Markdown SHA-256:   9f2f2629cb14135ef75edcbd0c082f5c5301e75469bb1f032c6b4223e8ff111e
# Code AST SHA-256:   64416e5623ab8b05b95eca57834ef8b1d8ff84cae999ec76eb18dc377abc7d3e
# Verified Classes:   SpeculativeRollbackError, Provenance, Branch, AuthoritativeState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class SpeculativeRollbackError(RuntimeError):
    """Raised when a speculative branch cannot be safely reconciled or aborted."""


@dataclass
class Provenance:
    resource_version: int
    lease_id: str
    tool_ledger: list = field(default_factory=list)


@dataclass
class Branch:
    name: str
    provenance: Provenance
    partial_commit: dict
    checkpoint: Optional[dict] = None


@dataclass
class AuthoritativeState:
    version: int
    data: dict


def reconcile(branches: list[Branch], authoritative: AuthoritativeState,
              rollback_quota_available: bool) -> dict:
    # Provenance gate precedes any content comparison.
    stale = [b for b in branches if b.provenance.resource_version != authoritative.version]

    if stale:
        # Attempt quarantine-and-abort, not field-level merge.
        for b in stale:
            if b.checkpoint is None:
                # Cannot replay: no input snapshot retained.
                raise SpeculativeRollbackError(
                    f"branch {b.name} lapsed on version "
                    f"{b.provenance.resource_version} (authoritative "
                    f"{authoritative.version}) with no checkpoint; "
                    f"abort path is non-idempotent"
                )
            if not rollback_quota_available:
                raise SpeculativeRollbackError(
                    f"branch {b.name} requires replay but rollback quota is "
                    f"exhausted; escalating to task-level halt"
                )
        # Quarantine stale branches; re-dispatch from authoritative version.
        return {"status": "quarantined", "stale": [b.name for b in stale],
                "merged": {}}

    # All provenances current: safe to content-merge.
    merged: dict = {}
    for b in branches:
        merged.update(b.partial_commit)
    return {"status": "merged", "stale": [], "merged": merged}
