# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-a2a-handoff-has-silently-desynchronized-its-artifact-checkpoint-from-the-receiver-s-committed-cursor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-resumable-a2a-handoff-has-silently-desynchronized-its-artifact-checkpoint-from-the-receiver-s-committed-cursor.warrant.json
# Markdown SHA-256:   20c54c7cc3376e3d34f392b787f01a00555484c4cb19e02c4805caf74e8d7b5e
# Code AST SHA-256:   b2994cce9cbc08176a92913e92f503fe0a4f667e309333e0eda059335540673e
# Verified Classes:   CheckpointDesyncError, Chunk
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class CheckpointDesyncError(RuntimeError):
    """Raised when a resume's replay-origin overlaps the committed cursor
    but a replayed chunk does not match the receiver's committed copy."""
    pass


@dataclass
class Chunk:
    seq: int
    payload: bytes

    @property
    def content_hash(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


def reconcile_resume(
    committed: dict[int, str],
    cursor: int,
    replayed_from: int,
    replayed: list[Chunk],
) -> int:
    """Validate a resumable A2A resume handshake.

    committed: seq -> content_hash for every chunk durably written through cursor.
    Returns the new cursor after accepting the replay, or raises.
    """
    if not (0 <= replayed_from <= cursor):
        raise CheckpointDesyncError(
            f"replay origin {replayed_from} is ahead of committed cursor "
            f"{cursor}: unbridgeable gap, receiver is missing chunks"
        )

    # Overlap window is the dangerous region: producer is replaying chunks the
    # receiver already committed. Every one must be bit-identical.
    for chunk in replayed:
        if chunk.seq > cursor:
            break
        expected = committed.get(chunk.seq)
        if expected is None:
            raise CheckpointDesyncError(
                f"replayed chunk {chunk.seq} lies in overlap window but "
                f"receiver has no committed copy to compare against"
            )
        if chunk.content_hash != expected:
            raise CheckpointDesyncError(
                f"lineage fork at seq={chunk.seq}: replayed hash "
                f"{chunk.content_hash[:12]} != committed {expected[:12]}; "
                f"producer replay pointer desynced from its durable log"
            )

    new_cursor = cursor
    for chunk in replayed:
        if chunk.seq <= cursor:
            continue  # verified overlap, already committed
        if chunk.seq != new_cursor + 1:
            raise CheckpointDesyncError(
                f"non-contiguous chunk {chunk.seq} after cursor {new_cursor}"
            )
        committed[chunk.seq] = chunk.content_hash
        new_cursor = chunk.seq

    return new_cursor
