# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-otlp-trace-correlation-breaks-between-a-prompt-span-and-its-memory-write-child-span.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-otlp-trace-correlation-breaks-between-a-prompt-span-and-its-memory-write-child-span.warrant.json
# Markdown SHA-256:   2924dc7c98c0d32a1a3842338d8e61e26684535219e8190ccef3d8b3b25195d9
# Code AST SHA-256:   5dd3984eb0681c25758e0c606ffd13e74c65bc01ff32af1d430c795cd5b8ab23
# Verified Classes:   TraceCorrelationError, SpanRef
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceCorrelationError(RuntimeError):
    """Raised when an OTLP span's causal parentage is inconsistent with the
    operation it represents (e.g. a memory.write mis-parented to the next
    prompt after a context switch)."""


@dataclass(frozen=True)
class SpanRef:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    links: tuple = ()


def validate_memory_lineage(spans: list[SpanRef]) -> None:
    """Enforce: every memory.write span must be parented to (or linked to)
    a tool_call span in the same trace. Ambient-context emission violates
    this when the write-behind queue fires after the parent context popped."""
    by_id = {s.span_id: s for s in spans}

    for span in spans:
        if not span.name.startswith("agent.memory.write"):
            continue

        parent = by_id.get(span.parent_span_id) if span.parent_span_id else None
        linked = [by_id.get(l) for l in span.links if l in by_id]

        def is_tool_call(s: Optional[SpanRef]) -> bool:
            return s is not None and s.name.startswith("agent.tool_call")

        if parent is not None and parent.trace_id != span.trace_id:
            raise TraceCorrelationError(
                f"memory.write {span.span_id} in trace {span.trace_id} "
                f"parented across trace boundary to {parent.trace_id}"
            )

        if is_tool_call(parent) or any(is_tool_call(l) for l in linked):
            continue

        # Mis-parented to a later prompt, or orphaned with no link.
        raise TraceCorrelationError(
            f"memory.write {span.span_id} (trace {span.trace_id}) has no "
            f"tool_call ancestor or link; parent={span.parent_span_id!r}, "
            f"links={span.links!r}. Deferred emission lost originating "
            f"SpanContext — quarantine from episodic ingestion."
        )
