# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-proof-of-possession-refresh-races-its-own-credential-expiry-during-a-live-agent-to-agent-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-proof-of-possession-refresh-races-its-own-credential-expiry-during-a-live-agent-to-agent-handoff.warrant.json
# Markdown SHA-256:   1b2d6438fcb2d43e555cc6a6dfe80451f89ea35885a0ee24f8d14ab926f6db7c
# Code AST SHA-256:   f0d63168e7715a61a18fad761c2f6483889636cdb311e0dfb99e290a2d0fc848
# Verified Classes:   BindingGenerationMismatch, Credential, PopAssertion
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class BindingGenerationMismatch(RuntimeError):
    """Raised when a PoP assertion and its presented credential disagree on generation."""
    pass


@dataclass(frozen=True)
class Credential:
    subject: str
    jkt: str          # holder key thumbprint bound into the VC
    gen: int          # shared generation counter with the PoP key
    exp: int          # unix seconds


@dataclass(frozen=True)
class PopAssertion:
    subject: str
    signer_jkt: str
    gen: int
    nonce: str
    now: int


def verify_binding(vc: Credential, pop: PopAssertion, last_accepted_gen: int) -> None:
    # Atomic composite predicate: every component must agree, no lenient fallback.
    if pop.subject != vc.subject:
        raise BindingGenerationMismatch(
            f"subject mismatch: vc={vc.subject} pop={pop.subject}"
        )
    if pop.signer_jkt != vc.jkt:
        raise BindingGenerationMismatch(
            f"holder-binding decohered: vc.jkt={vc.jkt} signer={pop.signer_jkt}"
        )
    if pop.gen != vc.gen:
        raise BindingGenerationMismatch(
            f"generation race: vc.gen={vc.gen} pop.gen={pop.gen}"
        )
    if pop.gen < last_accepted_gen:
        raise BindingGenerationMismatch(
            f"generation rollback: pop.gen={pop.gen} < accepted={last_accepted_gen}"
        )
    if pop.now >= vc.exp:
        raise BindingGenerationMismatch(
            f"credential expired: now={pop.now} exp={vc.exp}"
        )


def handle_handoff_frame(
    vc: Credential,
    pop: PopAssertion,
    cache: dict,  # keyed on (subject, jkt, gen) -- never on subject alone
) -> None:
    key = (vc.subject, vc.jkt, vc.gen)
    last = cache.get(key, -1)
    verify_binding(vc, pop, last_accepted_gen=last)
    cache[key] = pop.gen
