# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-cross-mcp-causal-trace-as-unstitchable-once-a-downstream-server-omits-the-w3c-traceparent-echo-and-how-shou.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-cross-mcp-causal-trace-as-unstitchable-once-a-downstream-server-omits-the-w3c-traceparent-echo-and-how-shou.warrant.json
# Markdown SHA-256:   de0a5aac2887dcc63a0b926c3b7ccde994aff460a0027717c7a97ef33bee79e1
# Code AST SHA-256:   d62afe6c1c173fb5b1b69092fbe391b209e84f048c16d538a1dad04783250ff9
# Verified Classes:   TraceStitchError, Span, IssuedContext, CausalStitcher
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class TraceStitchError(RuntimeError):
    """Raised when a span cannot be causally joined to its parent trace."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    tool_name: str
    session_id: str
    received_ns: int = field(default_factory=time.time_ns)


@dataclass
class IssuedContext:
    """Recorded at the call site: the exact traceparent the agent sent."""
    call_id: str
    tool_name: str
    trace_id: str
    span_id: str
    sent_ns: int


class CausalStitcher:
    def __init__(self) -> None:
        self._issued: dict[str, IssuedContext] = {}
        self._verified: dict[str, list[Span]] = {}
        self._orphans: list[Span] = []

    def record_issued(self, ctx: IssuedContext) -> None:
        self._issued[ctx.call_id] = ctx

    def ingest(self, span: Span) -> str:
        # Echo invariant check: does this span descend from a context we issued?
        parent_ctx = next(
            (c for c in self._issued.values()
             if c.trace_id == span.trace_id and c.span_id == span.parent_span_id),
            None,
        )
        if parent_ctx is not None:
            self._verified.setdefault(span.trace_id, []).append(span)
            return "verified"

        # Known-foreign: trace_id we never issued -> quarantine, never join.
        if not any(c.trace_id == span.trace_id for c in self._issued.values()):
            self._orphans.append(span)
            return "quarantined_known_foreign"

        # Unknown-provenance: trace matches an issued context but parent does not.
        # Session-based fallback is forbidden here; this is the contamination vector.
        raise TraceStitchError(
            f"span {span.span_id} (tool={span.tool_name}) claims trace "
            f"{span.trace_id} but parent {span.parent_span_id} was never issued; "
            f"refusing session-fallback stitch on session={span.session_id}"
        )

    def trace_is_complete(self, trace_id: str) -> bool:
        spans = self._verified.get(trace_id, [])
        if not spans:
            return False
        present = {s.span_id for s in spans}
        return all(
            s.parent_span_id is None or s.parent_span_id in present
            for s in spans
        )
