# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-halt-rather-than-re-attest-when-its-aaif-warrant-is-revoked-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-halt-rather-than-re-attest-when-its-aaif-warrant-is-revoked-mid-handoff.warrant.json
# Markdown SHA-256:   53fe3c720c68eb194d472e92b1e59e1f218cb5de283fbf8254ca4e369ba3dfd9
# Code AST SHA-256:   a2c5f9fbd6740a31370b68717ffa6d8faee6d78d8fa235c0b2f2dc9cf3b02e7a
# Verified Classes:   WarrantRevokedMidHandoff
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class WarrantRevokedMidHandoff(RuntimeError):
    """Raised when a warrant is revoked while a handoff transaction is in flight
    and the instance attempts to continue under a re-attested warrant."""
    pass


REVOCATION_GRACE = 0  # no grace: revocation is terminal for the transaction


def commit_handoff(offer: dict, new_warrant: dict, revocation_record: dict | None) -> dict:
    """
    offer:         the envelope accepted by the peer in phase one, carrying
                   {'warrant_id', 'warrant_epoch', 'nonce', 'principal_id'}
    new_warrant:   the warrant the instance intends to commit under, carrying
                   {'id', 'epoch', 'issued_at', 'principal_id', 'predecessor'}
    revocation_record: {'warrant_id', 'revoked_at'} or None
    """
    if revocation_record and revocation_record["warrant_id"] == offer["warrant_id"]:
        # The offer's warrant was revoked. Any re-attestation is a laundering
        # attempt unless the principal explicitly re-opened the transaction.
        if new_warrant["id"] != offer["warrant_id"]:
            raise WarrantRevokedMidHandoff(
                f"warrant {offer['warrant_id']} revoked at "
                f"{revocation_record['revoked_at']}; refusing to commit under "
                f"re-attested warrant {new_warrant['id']} in the same transaction"
            )
        # Same warrant, but revoked: halt regardless.
        raise WarrantRevokedMidHandoff(
            f"warrant {offer['warrant_id']} revoked; in-flight handoff aborted"
        )

    # Epoch monotonicity guard: the commit must not bump the warrant epoch
    # relative to the accepted offer, even for a legitimate rotation.
    if new_warrant["epoch"] > offer["warrant_epoch"]:
        raise WarrantRevokedMidHandoff(
            f"epoch bump {offer['warrant_epoch']} -> {new_warrant['epoch']} "
            f"rejected: commit must bind to the offer's warrant epoch"
        )

    if new_warrant.get("predecessor") != offer["warrant_id"] and \
       new_warrant["id"] != offer["warrant_id"]:
        raise WarrantRevokedMidHandoff(
            "new warrant does not name the offer's warrant as predecessor; "
            "possible re-parenting"
        )

    return {"committed": True, "nonce": offer["nonce"], "warrant": new_warrant["id"]}
