# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-merge-when-a-peer-s-verification-warrant-arrives-with-a-stale-causal-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-a-speculative-branch-merge-when-a-peer-s-verification-warrant-arrives-with-a-stale-causal-epoch.warrant.json
# Markdown SHA-256:   1799fc926b666f8f387f5dd1a2c6b7c5dd4abfd158675e86cdaa507414ff06af
# Code AST SHA-256:   54de898f0b495067b2b0847f869ecd3f910700b6351141af51110c538fd42e46
# Verified Classes:   StaleWarrantError, Warrant, LedgerView
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, Iterable


class StaleWarrantError(RuntimeError):
    """Raised when a merge set contains a warrant whose causal epoch
    predates the commit-time ledger epoch and the branch is epoch-dependent."""


@dataclass(frozen=True)
class Warrant:
    branch_id: str
    payload_hash: str
    epoch: int
    auditor_sig: str
    epoch_dependent: bool  # declared by the executor, not inferred by coordinator


@dataclass(frozen=True)
class LedgerView:
    epoch: int


def verify_signature(w: Warrant) -> bool:
    # Placeholder for real auditor signature verification.
    return bool(w.auditor_sig)


def re_verify(branch_id: str, target_epoch: int) -> bool:
    # Placeholder for an auditor round-trip against target_epoch.
    return True


def merge_speculative_branches(
    warrants: Iterable[Warrant],
    ledger: LedgerView,
    commit_epoch: int,
    re_verify_budget: int,
) -> list[str]:
    """Merge speculative branches only if every warrant is currency-valid
    against the commit-time epoch. Aborts the merge (does not silently drop)
    when a stale, epoch-dependent warrant cannot be re-verified in budget."""
    warrants = list(warrants)
    merged: list[str] = []
    reverified = 0

    for w in warrants:
        if not verify_signature(w):
            raise StaleWarrantError(
                f"branch {w.branch_id}: signature invalid, refusing merge"
            )

        if w.epoch == commit_epoch:
            merged.append(w.branch_id)
            continue

        if w.epoch > commit_epoch:
            # A warrant from the future is a causal-ordering violation,
            # never a benign lag. Refuse outright.
            raise StaleWarrantError(
                f"branch {w.branch_id}: warrant epoch {w.epoch} ahead of "
                f"commit epoch {commit_epoch}; causal order violated"
            )

        # w.epoch < commit_epoch: stale warrant.
        if not w.epoch_dependent:
            # Payload does not read shared state; safe to merge as-is.
            merged.append(w.branch_id)
            continue

        if reverified >= re_verify_budget:
            raise StaleWarrantError(
                f"branch {w.branch_id}: stale warrant (epoch {w.epoch} < "
                f"{commit_epoch}) and re-verification budget exhausted; "
                f"aborting merge rather than applying unverified state"
            )

        if not re_verify(w.branch_id, commit_epoch):
            raise StaleWarrantError(
                f"branch {w.branch_id}: re-verification against epoch "
                f"{commit_epoch} failed; refusing merge"
            )
        reverified += 1
        merged.append(w.branch_id)

    # Final atomicity guard: the epoch must not have advanced during the merge.
    if ledger.epoch != commit_epoch:
        raise StaleWarrantError(
            f"commit epoch {commit_epoch} no longer current (ledger at "
            f"{ledger.epoch}); merge is advisory, not enforcing"
        )

    return merged
