# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a2a-v1-0-streaming-capability-but-its-task-store-cannot-durably-replay-artifacts-across-a-runtime-restart.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a2a-v1-0-streaming-capability-but-its-task-store-cannot-durably-replay-artifacts-across-a-runtime-restart.warrant.json
# Markdown SHA-256:   8b1231d057d47e5aeb8919d48470aa61bf8f9a7d45caa492d699e08f9086dc4f
# Code AST SHA-256:   44551a8cf0ca9b5890e2a6c55a4f87e374fa6bbbb5f224befed249c2e4164889
# Verified Classes:   ArtifactReplayCorruption, ArtifactObservation, ReplayGuard
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ArtifactReplayCorruption(RuntimeError):
    """Raised when a resubscribed task's artifact set is provably short of
    what the client observed before severance, on a provider whose durability
    is unnegotiated (A2A v1.0 streaming flag is liveness-only)."""
    pass


@dataclass
class ArtifactObservation:
    artifact_index: int
    last_chunk_index_observed: int = -1
    saw_terminal_chunk: bool = False


@dataclass
class ReplayGuard:
    """Client-side invariant enforcer for A2A v1.0 heterogeneous meshes."""
    observations: dict[int, ArtifactObservation] = field(default_factory=dict)

    def observe_chunk(self, artifact_index: int, chunk_index: int, last_chunk: bool) -> None:
        obs = self.observations.setdefault(artifact_index, ArtifactObservation(artifact_index))
        obs.last_chunk_index_observed = max(obs.last_chunk_index_observed, chunk_index)
        if last_chunk:
            obs.saw_terminal_chunk = True

    def validate_replay(self, task_id: str, replayed: dict[int, int]) -> None:
        """replayed maps artifact_index -> highest chunk index present in the
        Task returned by tasks/resubscribe or tasks/get."""
        for idx, obs in self.observations.items():
            if obs.saw_terminal_chunk:
                continue  # artifact was complete before severance; replay is status-only
            present = replayed.get(idx, -1)
            if present < obs.last_chunk_index_observed:
                raise ArtifactReplayCorruption(
                    f"task {task_id!r} artifact {idx}: client observed chunk "
                    f"{obs.last_chunk_index_observed} pre-severance but replay "
                    f"contains only up to {present}; provider is write-behind "
                    f"and streaming flag did not negotiate durability. "
                    f"Refusing to treat task as complete; re-issue message/send."
                )


def resume_task(guard: ReplayGuard, task_id: str, provider_replay: dict[int, int]) -> None:
    # provider_replay is derived from the Task.artifacts returned on resubscribe.
    guard.validate_replay(task_id, provider_replay)
