# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-stale-speculative-branches-during-cross-org-latency-hiding-the-speculative-commit-hazard-at-the-consistency-check-barrier.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-stale-speculative-branches-during-cross-org-latency-hiding-the-speculative-commit-hazard-at-the-consistency-check-barrier.warrant.json
# Markdown SHA-256:   37478c95d331903346824646bc67bf65c825f3fff4c7953a0da1e363706daa00
# Code AST SHA-256:   b9c6a0c9eeba6b262473cfada368aef404c13ec6e0817ff3fb978a9ba3a6fa2d
# Verified Classes:   SpeculativeCommitViolation, SpecWarrant, Rollback
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class SpeculativeCommitViolation(RuntimeError):
    """Raised when a downstream agent would commit a speculative branch
    against an epoch that is not provably >= the coordinator's last
    validation epoch for that branch."""


@dataclass(frozen=True)
class SpecWarrant:
    spec_id: str
    base_epoch: int
    valid_until_ms: int
    successor_spec_id: Optional[str] = None


@dataclass(frozen=True)
class Rollback:
    spec_id: str
    invalidated_at_epoch: int
    successor_spec_id: Optional[str] = None


def commit_speculative_branch(
    warrant: SpecWarrant,
    observed_epoch: int,
    rollbacks_seen: list[Rollback],
    now_ms: int,
) -> str:
    """Decide whether to commit, re-anchor, or abort a speculative branch.

    Returns the spec_id that was actually committed (which may be a
    successor if a SUPERSEDED rollback was observed).
    """
    if now_ms > warrant.valid_until_ms:
        raise SpeculativeCommitViolation(
            f"spec {warrant.spec_id} expired at {warrant.valid_until_ms}ms, "
            f"now {now_ms}ms; must re-dispatch, not commit"
        )

    # V2: causation tagging. A rollback naming a successor means we must
    # commit the successor, not the branch it replaced.
    for rb in rollbacks_seen:
        if rb.spec_id == warrant.spec_id and rb.successor_spec_id is not None:
            if rb.successor_spec_id == warrant.spec_id:
                raise SpeculativeCommitViolation(
                    f"rollback for {warrant.spec_id} names itself as successor; "
                    f"malformed causation tag"
                )
            # Re-anchor against the successor warrant would be required here;
            # committing the original after a SUPERSEDED rollback is the
            # observed failure mode.
            raise SpeculativeCommitViolation(
                f"spec {warrant.spec_id} superseded by {rb.successor_spec_id}; "
                f"refusing to commit stale branch"
            )

    # V1: epoch monotonicity. The observed epoch must be >= the max
    # invalidation epoch we have seen for this branch, otherwise our
    # consistency check is anchored to a version the coordinator has
    # already moved past.
    max_invalidation = max(
        (rb.invalidated_at_epoch for rb in rollbacks_seen
         if rb.spec_id == warrant.spec_id),
        default=-1,
    )
    if observed_epoch < max_invalidation:
        raise SpeculativeCommitViolation(
            f"spec {warrant.spec_id}: observed_epoch={observed_epoch} < "
            f"invalidation_epoch={max_invalidation}; check is stale, must re-anchor"
        )

    if observed_epoch < warrant.base_epoch:
        raise SpeculativeCommitViolation(
            f"spec {warrant.spec_id}: observed_epoch={observed_epoch} < "
            f"base_epoch={warrant.base_epoch}; originator has regressed"
        )

    return warrant.spec_id
