# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-artifact-chunk-append-semantics-as-non-commutative-across-a-task-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-v1-0-artifact-chunk-append-semantics-as-non-commutative-across-a-task-resume.warrant.json
# Markdown SHA-256:   99f0456358b030f2e21151700fbbfd845ff72e586e38bf82d9bbd9da4ed079b6
# Code AST SHA-256:   140f2c793a59f83755290c66ad6eb6922bd36fe429c6a7287a322a6d2c27ebac
# Verified Classes:   ArtifactContinuityError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

async def on_artifact(event):
    if event.append:
        buffer[event.artifact_id] += event.part.text
    else:
        buffer[event.artifact_id] = event.part.text

class ArtifactContinuityError(RuntimeError):
    """Raised when a resumed A2A artifact stream cannot prove chunk adjacency."""
    pass


def apply_artifact_chunk(buffer: str, chunk: dict, resume_epoch: int, last_proven_epoch: int) -> str:
    """
    Apply a single TaskArtifactUpdateEvent chunk to the local artifact buffer.

    A2A v1.0 gives us `append` but no per-chunk sequence number. After a
    `tasks/resume`, `append: true` is only sound if the server has proven
    replay continuity (e.g. re-emitted the full artifact with append=False,
    or supplied an explicit resume marker). Otherwise we must fail closed.
    """
    if chunk.get("append") and resume_epoch > last_proven_epoch:
        # We resumed and the server is appending without proving adjacency.
        # The buffer's current contents are not a valid left operand.
        raise ArtifactContinuityError(
            f"append chunk received after resume (epoch {resume_epoch} > "
            f"proven {last_proven_epoch}) without continuity marker; "
            f"refusing to concatenate onto unproven buffer of len={len(buffer)}"
        )
    if chunk.get("append"):
        return buffer + chunk["part"]["text"]
    # append=False is a reset: server is re-emitting from a known point.
    return chunk["part"]["text"]


def resume_task_stream(task_id: str, client, buffer: str, last_proven_epoch: int) -> tuple[str, int]:
    """
    Resume a dropped A2A task and reassemble its artifact safely.
    Returns (artifact, new_epoch). Raises if continuity cannot be established.
    """
    resume = client.tasks_resume(task_id)
    epoch = resume["epoch"]
    if not resume.get("continuity_marker"):
        # No proof of adjacency: discard and re-fetch the full artifact.
        full = client.tasks_get(task_id)
        return full["artifact"]["parts"][0]["text"], epoch
    for chunk in resume["chunks"]:
        buffer = apply_artifact_chunk(buffer, chunk, epoch, last_proven_epoch)
    return buffer, epoch
