# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference) # Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-causal-trace-stitching-across-prompt-completion-and-tool-spans-breaks-under-parent-id-reassignment.md # Remnant Warrant: https://corpusfetch.com/c/what-structural-signals-indicate-when-causal-trace-stitching-across-prompt-completion-and-tool-spans-breaks-under-parent-id-reassignment.warrant.json # Markdown SHA-256: a8c69080f95c808d568a9d4a1711c88409ae2c8cf5cc06e022747db490c69536 # Code AST SHA-256: 498fef152c7a5008dfa5520a669170df10c8817bbfd7e60af6943e958e344d09 # Verified Classes: TraceStitchError, Span # Defensive Guards: 2 fail-closed invariants (zero external deps) # Governance: Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com) from dataclasses import dataclass from typing import Optional class TraceStitchError(RuntimeError): """Raised when causal parentage cannot be established without fabrication.""" @dataclass class Span: span_id: str parent_span_id: Optional[str] trace_id: str kind: str # "prompt" | "completion" | "tool" start_time: float end_time: float def stitch_trace(spans: list[Span]) -> dict[str, str]: by_id = {s.span_id: s for s in spans} completions = [s for s in spans if s.kind == "completion"] tools = [s for s in spans if s.kind == "tool"] orphaned = [t for t in tools if t.parent_span_id not in by_id] inversions = [ t for t in tools if t.parent_span_id in by_id and by_id[t.parent_span_id].start_time > t.start_time ] dup_roots = len({c.span_id for c in completions}) > 1 and bool(tools) reassignment = bool(orphaned) and bool(inversions) and dup_roots if reassignment: edges: dict[str, str] = {} for t in tools: containers = [ c for c in completions if c.start_time <= t.start_time and c.end_time >= t.end_time ] if len(containers) != 1: raise TraceStitchError( f"ambiguous causal parent for tool span {t.span_id}: " f"{len(containers)} containing completions in trace {t.trace_id}" ) edges[t.span_id] = containers[0].span_id return edges if orphaned and not inversions: # sampling loss: preserve emitted parentage, do not re-derive return {t.span_id: t.parent_span_id for t in tools if t.parent_span_id} if inversions and not orphaned: raise TraceStitchError( "temporal inversion without orphan: clock skew suspected, refusing to stitch" ) return {t.span_id: t.parent_span_id for t in tools if t.parent_span_id}