# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-a2a-streaming-artifact-exchange-from-a-peer-supplied-partial-result-checkpoint-that-was-truncated-mid-artifac.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resumes-an-a2a-streaming-artifact-exchange-from-a-peer-supplied-partial-result-checkpoint-that-was-truncated-mid-artifac.warrant.json
# Markdown SHA-256:   ebb2bd4868c998f4d3ff7bb1cfd23397fb3456a717aee2a191ecdd31c38a6b25
# Code AST SHA-256:   8bc464e62a121abdb7e5e87e5bab96e91fd17c29960d8790060bd1cb9de2b893
# Verified Classes:   ContinuityViolation, Checkpoint, ProducerAttestation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ContinuityViolation(RuntimeError):
    """Raised when a resumed A2A artifact exchange cannot prove prefix continuity."""
    pass


@dataclass(frozen=True)
class Checkpoint:
    artifact_id: str
    last_sequence: int
    partial_bytes: bytes
    producer_instance_id: Optional[str]   # None => no continuity token
    sealed_through: Optional[int]
    checkpoint_digest: Optional[str]


@dataclass(frozen=True)
class ProducerAttestation:
    producer_instance_id: str
    sealed_through: int
    digest: str


def resume_exchange(
    checkpoint: Checkpoint,
    attestation: Optional[ProducerAttestation],
) -> str:
    """
    Decide whether to resume from the local prefix or replay from zero.
    Returns "resume" or "replay". Raises ContinuityViolation if the
    checkpoint claims continuity it cannot prove.
    """
    # No token at all: cannot prove anything. Replay is the only safe move.
    if checkpoint.producer_instance_id is None:
        return "replay"

    # Token present but producer refused to attest (restart, unknown instance).
    if attestation is None:
        return "replay"

    # Producer restarted: instance id changed. Prefix is from a dead execution.
    if attestation.producer_instance_id != checkpoint.producer_instance_id:
        return "replay"

    # Producer attests it will not re-emit <= sealed_through with new content.
    # If our checkpoint is beyond the seal, our prefix contains unsealed bytes.
    if checkpoint.last_sequence > attestation.sealed_through:
        raise ContinuityViolation(
            f"checkpoint at seq {checkpoint.last_sequence} exceeds producer "
            f"seal {attestation.sealed_through} for artifact "
            f"{checkpoint.artifact_id}; prefix contains unsealed bytes and "
            f"cannot be resumed"
        )

    # Digest must bind the exact bytes we hold.
    actual = hashlib.sha256(checkpoint.partial_bytes).hexdigest()
    if checkpoint.checkpoint_digest != actual:
        raise ContinuityViolation(
            f"checkpoint digest mismatch for {checkpoint.artifact_id}: "
            f"stored={checkpoint.checkpoint_digest} actual={actual}"
        )

    return "resume"


def seal_and_derive(checkpoint: Checkpoint, final_bytes: bytes) -> str:
    """
    Gate downstream derivation on a verified seal. Deriving from an
    unsealed prefix is how a detectable corruption becomes undetectable.
    """
    if checkpoint.producer_instance_id is None:
        raise ContinuityViolation(
            f"cannot derive downstream artifact from unsealed prefix of "
            f"{checkpoint.artifact_id}"
        )
    return hashlib.sha256(final_bytes).hexdigest()
