# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-causality-linkage-when-a-genai-semantic-convention-exporter-batches-spans-across-an-agent-s-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-causality-linkage-when-a-genai-semantic-convention-exporter-batches-spans-across-an-agent-s-tool-call-boundary.warrant.json
# Markdown SHA-256:   9bb6af6e14a36cbd6a4ff09810c22af09b1d6ddd4b853765f398fa9c4e0bbcb0
# Code AST SHA-256:   543618ac5cbfdc5bf675771ebde1182e0289237692e8962d672cdb7710348403
# Verified Classes:   CausalityLinkError, Span, CausalityAwareBatcher
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalityLinkError(RuntimeError):
    """Raised when a span batch would split a causality link group across a flush boundary."""


@dataclass
class Span:
    span_id: str
    operation: str
    causality_link_id: str
    tool_call_id: Optional[str] = None
    parent_call_id: Optional[str] = None
    start_ns: int = 0


@dataclass
class CausalityAwareBatcher:
    max_batch: int
    deferral_budget: int = 2
    pending: list = field(default_factory=list)
    emitted_call_ids: dict = field(default_factory=dict)

    def emit(self, span: Span) -> None:
        # Retry idempotency: reuse the original span id for a re-entered tool call.
        if span.tool_call_id is not None:
            if span.tool_call_id in self.emitted_call_ids:
                span.span_id = self.emitted_call_ids[span.tool_call_id]
                span.operation = span.operation + ".retry"
            else:
                self.emitted_call_ids[span.tool_call_id] = span.span_id
        self.pending.append(span)

    def flush(self) -> list:
        if not self.pending:
            return []
        # Partition by causality link group.
        groups: dict = {}
        for s in self.pending:
            groups.setdefault(s.causality_link_id, []).append(s)

        ready, deferred = [], []
        for link_id, spans in groups.items():
            if len(spans) <= self.max_batch:
                ready.extend(spans)
            else:
                # Link group exceeds batch size: cannot flush atomically.
                # Emit explicit incompleteness marker rather than split silently.
                if self.deferral_budget <= 0:
                    for s in spans:
                        s.operation = s.operation + ".incomplete"
                    raise CausalityLinkError(
                        f"causality link {link_id} has {len(spans)} spans "
                        f"exceeding max_batch={self.max_batch}; "
                        f"deferral budget exhausted, marking incomplete"
                    )
                self.deferral_budget -= 1
                deferred.extend(spans)

        if ready:
            # Enforce producer-before-consumer within the flushed set.
            ready.sort(key=lambda s: (s.parent_call_id is not None, s.start_ns))
        self.pending = deferred
        return ready
