# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-consensus-but-its-signed-warrant-outlives-its-own-state-the-quorum-epoch-divergence-fa.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-commits-to-a-task-under-byzantine-consensus-but-its-signed-warrant-outlives-its-own-state-the-quorum-epoch-divergence-fa.warrant.json
# Markdown SHA-256:   313f2478767e2e257923151121337c88f1cbb0744799ee45b1f8274b97e151c1
# Code AST SHA-256:   338ee2ce1193e765494ded4707a4c711451fe99584498149a6cf44c0e280a41b
# Verified Classes:   CommitmentStateDivergence
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CommitmentStateDivergence(RuntimeError):
    """Raised when a quorum-certified warrant is presented for execution but
    the presenting instance's state does not descend from the committed state root."""
    pass


def validate_warrant_for_execution(warrant, presenting_instance, quorum):
    # Signature and predicate-hash checks pass trivially; they are necessary
    # but NOT sufficient. The failure mode lives past this point.
    if not quorum.verify_signature(warrant, warrant.epoch):
        raise CommitmentStateDivergence(
            f"warrant {warrant.task_id} signature invalid under epoch {warrant.epoch}"
        )
    if presenting_instance.predicate_hash() != warrant.predicate_hash:
        raise CommitmentStateDivergence(
            f"warrant {warrant.task_id}: predicate text hash mismatch"
        )

    # The critical check: state continuity across the discontinuity.
    # A restart that preserved consensus membership but discarded working
    # state leaves the signature valid and the commitment unbound.
    if not presenting_instance.has_state_continuity_proof(warrant.commit_state_root):
        # Do NOT execute on the strength of a valid signature alone.
        # Either re-attest with the quorum under a new epoch, or halt.
        if not quorum.can_reattest(presenting_instance, warrant):
            raise CommitmentStateDivergence(
                f"warrant {warrant.task_id} epoch {warrant.epoch}: instance state "
                f"does not descend from commit_state_root {warrant.commit_state_root}; "
                f"restart discontinuity detected and re-attestation unavailable — "
                f"halt and re-commit under a new epoch"
            )
        warrant = quorum.reattest(presenting_instance, warrant)

    return warrant
