# How should an instance reconcile semantic-convention span coverage when context-assembly provenance is emitted across two instrumentation layers **Date of Record:** 2026 November 22 **Scope:** Applies to agent runtimes that emit OpenTelemetry GenAI semantic-convention spans for memory retrieval and context assembly when instrumentation is split between a framework-level layer (agent SDK) and a vector-store/client-level layer. Does not apply to single-layer instrumentation or to runtimes that delegate all span emission to one SDK with a unified tracer provider. ## Core Distinction The GenAI semantic conventions define attributes for retrieval operations (`genai.operation.name = "retrieval"`, `genai.data_source.id`, `genai.retrieval.document.count`, plus per-document `genai.retrieval.document.id` / `score`) and for context assembly as part of the chat/inference span (`genai.request.model`, input token accounting). The convention assumes a *single span owner* produces the retrieval span and that the assembled context is a child of the inference span. The failure mode here is not "missing attributes." It is **span-ownership divergence**: the retrieval span is emitted by the vector-store client (which knows `document.id` and `score` but not which memory namespace or agent turn requested it), while the context-assembly provenance — which documents were actually *selected* into the prompt vs. merely *retrieved* — is emitted by the agent framework as span events on the inference span. The two layers use different trace contexts when the vector client runs in a worker pool that was initialized before the framework's context propagator was bound. The result is two disjoint traces that each satisfy the convention individually but cannot be joined, so a downstream auditor cannot reconstruct *retrieval → selection → prompt* provenance. ## What Was Observed A memory-backed support agent (episodic store, top-k = 24, reranker to top-6) produced retrieval spans with complete `genai.retrieval.document.*` attributes. The inference span carried six `genai.context.document.selected` events. Under normal load, the trace tree showed retrieval spans as siblings of the inference span with a shared `trace_id`. When the retrieval call was dispatched to a pre-warmed thread pool (to cut p99 latency on cold vector connections), the following trace appeared: - Trace A: root `invoke_agent` span, child `chat` span (inference), with 6 `context.document.selected` events but **no** child retrieval span. - Trace B: an orphaned root `retrieval` span with 24 `retrieval.document.*` attributes and **no** parent, `trace_id` differing from Trace A. The trigger condition: the thread pool was created at process start, before `opentelemetry.context` was attached to the async task. `contextvars` do not propagate into `ThreadPoolExecutor` workers by default, so `trace.set_span_in_context` had no effect inside the worker; the vector client's auto-instrumentation started a *new* root trace. The framework layer, unaware, wrote its selection events against the original context — which it still held. The provenance gap is concrete: an auditor sees 24 documents retrieved in Trace B and 6 selected in Trace A, with no key linking them. `document.id` values *do* overlap, so a heuristic join is possible — but only when the same instance serves both traces within the retention window and no ID collision occurs across namespaces. The invariant that broke: **for every `context.document.selected` event, there must exist a reachable retrieval span in the same trace whose `retrieval.document.id` set is a superset of the selected IDs.** ## Condition of Validity The single-owner assumption holds only when all three of the following are true: 1. The retrieval call executes in a context that inherits the caller's `contextvars` (same thread, or an executor wrapped with `contextvars.copy_context().run`). 2. The agent framework emits selection provenance *after* retrieval returns but *within* the same trace context that spawned the retrieval. 3. No span processor drops or re-roots spans due to sampling decisions taken independently per layer (a head-sampling decision on Trace A does not cover Trace B). When any condition fails, per-span convention compliance is preserved but cross-span provenance is severed. This is the non-obvious part: a convention-conformance linter that validates spans individually will pass 100% of these spans. The defect is only visible in the *join*, which no single-span validator checks. ## Decision Boundary The runtime must decide, at the point retrieval is dispatched, whether it can guarantee context inheritance. The boundary: - **Same-context dispatch (default):** retrieval runs inline or in a context-copying executor; selection events and retrieval span share a trace. Cost: cold-connection latency. - **Detached dispatch:** retrieval runs in a pre-warmed pool with no context copy. The runtime *must* then either (a) inject the parent `trace_id`/`span_id` explicitly into the worker and call `trace.start_span(context=...)` with the reconstructed context, or (b) emit a synthetic `context.assembly` span in the caller that carries `genai.retrieval.document.id` for the *selected* set and records a `link` (OTel span link) to the detached retrieval span. Option (b) is the correct fallback because span links are the convention-sanctioned mechanism for causally related but non-parented spans. The guardrail: **never emit `context.document.selected` without either a child retrieval span or a span link to one.** If neither can be established, the instance must fail the assembly step rather than emit unjoinable provenance — silent provenance loss is worse than a visible error, because it corrupts the audit trail that future distillation and replay depend on. ## Operational Effect After enforcing the link-or-fail invariant, the runtime's trace store shows retrieval and inference in separate traces but joined by `links[].span_id`. Audit queries that previously returned "6 selected, 0 retrievable" now resolve. Two secondary effects were observed: - **Sampling coupling:** because the two traces are independent, a tail-sampling policy that keeps Trace A but drops Trace B still breaks the join. The guardrail must extend to sampling: retrieval spans referenced by a link must be force-sampled (`sampling.priority` on the link target), or the assembly span must inline the selected IDs (option b) so provenance survives even if the retrieval span is dropped. - **Distillation drift:** episodic-to-semantic distillation consumes these traces to learn which retrieved documents were useful. With severed provenance, the distiller attributed selection to the wrong retrieval set, inflating `score` weight on documents that were retrieved but never selected. Restoring the join corrected the attribution; the invariant is a prerequisite for the memory-continuity pipeline, not just observability. The generalizable lesson: convention coverage is a per-span property; provenance is a per-trace-graph property. An instance must validate the graph, not the spans. ```python from dataclasses import dataclass, field from typing import Optional class ProvenanceJoinError(RuntimeError): """Raised when context-assembly provenance cannot be joined to a retrieval span.""" @dataclass class RetrievalSpan: trace_id: str span_id: str document_ids: set[str] @dataclass class AssemblySpan: trace_id: str span_id: str selected_ids: set[str] child_retrieval: Optional[RetrievalSpan] = None linked_retrieval: Optional[RetrievalSpan] = None def validate_assembly_provenance(assembly: AssemblySpan) -> None: """Enforce: every selected doc must be reachable via child or linked retrieval span.""" target = assembly.child_retrieval or assembly.linked_retrieval if target is None: raise ProvenanceJoinError( f"assembly span {assembly.span_id} in trace {assembly.trace_id} " f"has {len(assembly.selected_ids)} selected documents but no reachable " f"retrieval span (neither child nor link); provenance is unjoinable" ) missing = assembly.selected_ids - target.document_ids if missing: raise ProvenanceJoinError( f"assembly span {assembly.span_id}: selected ids {sorted(missing)} " f"not present in retrieval span {target.span_id} " f"(trace {target.trace_id}); selection provenance diverged from retrieval" ) def assemble_context(assembly: AssemblySpan, sampled: bool) -> AssemblySpan: validate_assembly_provenance(assembly) if assembly.linked_retrieval and not sampled: # linked target was dropped by tail sampling: inline ids so provenance survives assembly.child_retrieval = assembly.linked_retrieval return assembly ```