# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-abandon-an-a2a-v1-0-stream-correlation-id-after-an-otel-genai-span-parent-rebind-across-org-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-abandon-an-a2a-v1-0-stream-correlation-id-after-an-otel-genai-span-parent-rebind-across-org-boundaries.warrant.json
# Markdown SHA-256:   c564b2b8f5d41266f49717381b0fba5a518ccc2a95f55220a44892d193d47bd5
# Code AST SHA-256:   834daab6aa18639286859c5c220eaf304f7cd7e28aa31ba438ef574aff41c265
# Verified Classes:   CorrelationRebindViolation, StreamEnvelope, StreamConsumer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CorrelationRebindViolation(RuntimeError):
    """Raised when a streaming A2A task's trace_id changes after artifact emission."""


@dataclass
class StreamEnvelope:
    event_type: str          # "TaskStatusUpdateEvent" | "TaskArtifactUpdateEvent"
    state: Optional[str]     # submitted | working | input-required | completed
    trace_id: str
    metadata: dict = field(default_factory=dict)


@dataclass
class StreamConsumer:
    expected_trace_id: str
    artifact_count: int = 0
    rebind_seen: bool = False

    def consume(self, env: StreamEnvelope) -> None:
        # A declared fork on a pre-artifact status event is the only legal rebind.
        if env.metadata.get("correlation_fork") or env.metadata.get("correlation_rebind"):
            if self.artifact_count > 0:
                raise CorrelationRebindViolation(
                    f"rebind declared on {env.event_type} after "
                    f"{self.artifact_count} artifact(s); trace_id frozen"
                )
            if env.event_type != "TaskStatusUpdateEvent" or env.state not in ("working", "input-required"):
                raise CorrelationRebindViolation(
                    f"rebind declared on illegal event {env.event_type}/{env.state}"
                )
            self.expected_trace_id = env.trace_id
            self.rebind_seen = True
            return

        if env.trace_id != self.expected_trace_id:
            if env.event_type == "TaskArtifactUpdateEvent" and self.artifact_count > 0:
                raise CorrelationRebindViolation(
                    f"trace_id diverged on artifact #{self.artifact_count + 1}: "
                    f"expected {self.expected_trace_id}, got {env.trace_id}"
                )
            raise CorrelationRebindViolation(
                f"undeclared trace_id change on {env.event_type}: "
                f"expected {self.expected_trace_id}, got {env.trace_id}"
            )

        if env.event_type == "TaskArtifactUpdateEvent":
            self.artifact_count += 1


def replay_task_stream(events: list[StreamEnvelope], initial_trace_id: str) -> StreamConsumer:
    consumer = StreamConsumer(expected_trace_id=initial_trace_id)
    for env in events:
        consumer.consume(env)
    if consumer.artifact_count == 0:
        raise CorrelationRebindViolation("stream completed with zero artifacts; replay unverifiable")
    return consumer
