# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-after-its-parent-s-reconciliation-epoch-has-already-advanced.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-a-speculative-branch-after-its-parent-s-reconciliation-epoch-has-already-advanced.warrant.json
# Markdown SHA-256:   88f2c8b04e69315714f65f01dddfe768071b44d5b64296a8d3a0b405762d4b7e
# Code AST SHA-256:   4819f07dbbd07845bb9cce21e70700594f93546a6a79c037abb365b87356d659
# Verified Classes:   StaleDerivationCommitError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StaleDerivationCommitError(RuntimeError):
    """Raised when a speculative branch commits with a derivation provenance
    that predates the parent's current reconciliation epoch."""
    pass


MAX_REBASE_INTERVAL = 3


def validate_speculative_commit(branch, parent, reconciliation_log):
    derived = branch.derived_from_epoch
    parent_epoch = parent.current_epoch

    if derived == parent_epoch:
        return True

    interval = parent_epoch - derived
    if interval < 0:
        raise StaleDerivationCommitError(
            f"branch {branch.id} derives from future epoch {derived} "
            f"but parent is at {parent_epoch}"
        )

    if interval > MAX_REBASE_INTERVAL:
        raise StaleDerivationCommitError(
            f"branch {branch.id} derivation interval {interval} exceeds "
            f"bound {MAX_REBASE_INTERVAL}; reject and re-draft"
        )

    touched = branch.touched_slots()
    for epoch in range(derived + 1, parent_epoch + 1):
        entry = reconciliation_log.get(epoch)
        if entry is None:
            raise StaleDerivationCommitError(
                f"missing reconciliation log for epoch {epoch}; "
                f"cannot validate branch {branch.id}"
            )
        if entry.affected_slots & touched:
            raise StaleDerivationCommitError(
                f"branch {branch.id} derived at epoch {derived} touches slots "
                f"{entry.affected_slots & touched} reconciled at epoch {epoch}; "
                f"provenance invalid, re-draft required"
            )

    return True
