# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-tool-call-lineage-from-surviving-across-asynchronous-agent-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-tool-call-lineage-from-surviving-across-asynchronous-agent-boundaries.warrant.json
# Markdown SHA-256:   5f1d07040a2356429f91e24e5b492b1727efb6a9eca5a086047a9d3d1498e90b
# Code AST SHA-256:   1a1a9ca552f5cb9bd7ec931b7121ac96c39b2cb1bd787f4b4aa99e2eb45c7752
# Verified Classes:   ToolLineageInvariantError, SpanContext, ToolInvocation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass


class ToolLineageInvariantError(RuntimeError):
    """Raised when a tool-result span would violate invocation/result lineage."""


@dataclass(frozen=True)
class SpanContext:
    trace_id: str
    span_id: str


@dataclass(frozen=True)
class ToolInvocation:
    call_id: str
    tool_name: str
    span_context: SpanContext          # context of the invocation span itself
    propagated: SpanContext            # context captured in the enqueue payload


def emit_result_span(
    invocation: ToolInvocation,
    extracted: SpanContext,
    seen_call_ids: set[str],
    *,
    attempt: int = 0,
) -> SpanContext:
    """Validate I1/I2/I3 before emitting a tool-result span.

    Returns the parent context the result span must use. Raises
    ToolLineageInvariantError (fail-closed) rather than silently re-parenting.
    """
    # I1: the worker must extract the invocation's own context, not an ancestor's.
    if extracted != invocation.span_context:
        raise ToolLineageInvariantError(
            f"I1 violated for call_id={invocation.call_id!r}: "
            f"extracted span_id={extracted.span_id!r} != invocation "
            f"span_id={invocation.span_context.span_id!r}; result would be "
            f"orphaned under the wrong parent."
        )

    # I2: call_id must be trace-scoped unique, not process-local.
    if invocation.call_id in seen_call_ids:
        raise ToolLineageInvariantError(
            f"I2 violated: call_id={invocation.call_id!r} already emitted in "
            f"trace {invocation.span_context.trace_id!r}; per-worker counters "
            f"do not satisfy trace-scoped uniqueness."
        )

    # I3: retries must not reuse the id without an explicit link.
    if attempt > 0:
        raise ToolLineageInvariantError(
            f"I3 violated: attempt={attempt} for call_id={invocation.call_id!r} "
            f"must use a fresh call_id and a span link to the prior attempt, "
            f"not a re-emit under the same id."
        )

    seen_call_ids.add(invocation.call_id)
    return invocation.span_context
