# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fork-speculative-branches-that-silently-diverge-in-their-reconciliation-epoch-and-how-do-we-bound-it.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fork-speculative-branches-that-silently-diverge-in-their-reconciliation-epoch-and-how-do-we-bound-it.warrant.json
# Markdown SHA-256:   83801e8e61be565b1fc9f8d532f692f82f5bfc6814f7a1b08eef50079ec4672a
# Code AST SHA-256:   6d593e35cb879600921505adf708f216422d674b8362beda8b1558111c222ccb
# Verified Classes:   StaleBranchCommitError, Branch, CommitDecision
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleBranchCommitError(RuntimeError):
    """Raised when a speculative branch's fork epoch does not match commit epoch
    and the branch cannot be safely rebased within the staleness budget."""
    pass


@dataclass(frozen=True)
class Branch:
    branch_id: str
    fork_epoch: int
    effect_set: frozenset  # identifiers of state the branch read/wrote


@dataclass(frozen=True)
class CommitDecision:
    action: str  # "commit" | "rebase" | "discard"
    reason: str


def decide_commit(
    branch: Branch,
    commit_epoch: int,
    delta_touched: frozenset,
    staleness_budget: int = 2,
) -> CommitDecision:
    lag = commit_epoch - branch.fork_epoch

    if lag < 0:
        # Branch forked from a future epoch: checkpoint corruption, never commit.
        raise StaleBranchCommitError(
            f"branch {branch.branch_id} fork_epoch={branch.fork_epoch} "
            f"is ahead of commit_epoch={commit_epoch}; checkpoint is inconsistent"
        )

    if lag == 0:
        return CommitDecision("commit", "fork epoch equals commit epoch")

    if lag > staleness_budget:
        return CommitDecision(
            "discard",
            f"lag={lag} exceeds staleness_budget={staleness_budget}; "
            "world advanced faster than branch could converge",
        )

    # Rebase is only safe if the delta covers everything the branch touched.
    uncovered = branch.effect_set - delta_touched
    if uncovered:
        raise StaleBranchCommitError(
            f"branch {branch.branch_id} touched {sorted(uncovered)} "
            f"which is not reconstructable from delta at epoch {commit_epoch}; "
            "cannot rebase without replaying against unknown state"
        )

    return CommitDecision(
        "rebase",
        f"lag={lag} within budget; re-validate {sorted(branch.effect_set)} against delta",
    )


def commit_with_epoch_guard(
    branch: Branch,
    ledger,
    delta_touched: frozenset,
    staleness_budget: int = 2,
) -> CommitDecision:
    commit_epoch = ledger.current_epoch()
    decision = decide_commit(branch, commit_epoch, delta_touched, staleness_budget)

    if decision.action == "commit":
        # Compare-and-swap: only accept if epoch has not moved since the check.
        ledger.apply(branch.effect_set, expect_epoch=branch.fork_epoch)
    elif decision.action == "rebase":
        ledger.rebase(branch.effect_set, from_epoch=branch.fork_epoch, to_epoch=commit_epoch)
    # discard: no write, caller re-forks

    return decision
