This prompt is for observability engineers and SRE teams who need to reconstruct broken distributed trace contexts programmatically. The job-to-be-done is generating a precise trace propagation instruction when a service receives a request with a missing, malformed, or truncated traceparent or tracestate header. The ideal user is building an AI-assisted middleware or diagnostic agent that must decide how to inject a new correlation ID, reconcile orphaned spans to a parent, and forward downstream headers without breaking sampling decisions or vendor-specific trace flags. You should use this prompt when your system has partial trace context—such as a valid trace ID but a missing parent span ID—and you need a deterministic recovery plan that a downstream proxy, sidecar, or service mesh can execute.
Prompt
Distributed Trace Correlation ID Recovery Prompt Template

When to Use This Prompt
Define the job, reader, and constraints for the Distributed Trace Correlation ID Recovery Prompt Template.
Do not use this prompt for generating human-readable incident summaries or for root cause analysis of why a trace was broken. It is not designed for log correlation, metric stitching, or alert enrichment. The prompt assumes you already have the raw, broken header fragments and the service's trace configuration (e.g., W3C Trace Context compliance, sampling rates, and vendor flags). It is also inappropriate for systems that do not use distributed tracing or for simple retry logic on HTTP errors—use the API Rate Limit 429 or HTTP 5xx retry playbooks for those cases. The output is a machine-actionable instruction set, not a narrative explanation.
Before using this prompt, ensure you have captured the exact incoming header values, the service's expected trace configuration, and any sampling decision flags that must be preserved. The prompt's value is in its ability to produce a structured recovery instruction that prevents trace fragmentation and maintains end-to-end observability. After generating the instruction, you must validate it against your tracing SDK's header generation logic in a test harness before deploying it to a production middleware path. A malformed recovery can create trace loops or break sampling, so always include a unit test that verifies the output header against a known-good trace context.
Use Case Fit
Where the Distributed Trace Correlation ID Recovery Prompt works, where it fails, and the operational preconditions required before wiring it into a production harness.
Good Fit: Broken Trace Context Propagation
Use when: an upstream service drops or malforms traceparent or tracestate headers, and you need the model to reconstruct the trace context from logs, timestamps, and service topology metadata. Guardrail: always provide the raw incoming headers and the expected downstream propagation format as explicit input fields.
Bad Fit: Real-Time Latency-Sensitive Paths
Avoid when: the recovery decision must complete in under 50ms on a hot request path. An LLM call adds unacceptable latency. Guardrail: use this prompt in async, out-of-band trace repair pipelines or dead-letter handlers, never inline on the critical serving path.
Required Input: Service Topology and Raw Headers
What to watch: the model cannot guess which service generated a span or what the parent-child relationship should be. Guardrail: the prompt template requires [RAW_HEADERS], [SERVICE_MAP], [TIMESTAMP], and [SAMPLING_DECISION] as mandatory inputs. Missing fields must cause the harness to abort before calling the model.
Operational Risk: Sampling Decision Drift
Risk: the reconstructed trace context uses a different sampling flag than the original request, causing the trace to be dropped or over-collected downstream. Guardrail: include the original sampling decision as a non-negotiable constraint in the prompt, and validate the output's sampled flag against the input before propagation.
Operational Risk: Span ID Collision
Risk: the model generates a span ID that collides with an existing span in the trace, corrupting the trace graph. Guardrail: the harness must validate that the generated span_id is not already present in the provided [EXISTING_SPAN_IDS] list. On collision, retry with a different random seed injected into the prompt.
Escalation Trigger: Unrecoverable Context Gaps
Risk: the model produces a low-confidence reconstruction because critical parent span information is entirely missing from logs. Guardrail: define a confidence threshold in the output schema. If the model's self-reported confidence is below the threshold, route to a human on-call engineer instead of injecting the reconstructed header.
Copy-Ready Prompt Template
A reusable prompt template for reconstructing broken distributed trace contexts with correlation ID injection and span parent reconciliation.
This prompt template instructs the model to analyze a broken or incomplete trace context and produce a recovery instruction set. The template is designed to be wired into an observability pipeline where trace propagation has failed—due to header stripping, service mesh misconfiguration, or incomplete context forwarding—and the system needs a structured recovery plan before replaying or continuing the request. The placeholders allow you to inject the specific broken trace state, downstream service requirements, and operational constraints that shape the recovery decision.
textYou are a distributed tracing recovery specialist. Your task is to analyze a broken or incomplete trace context and produce a recovery instruction set that restores trace continuity. [BROKEN_TRACE_CONTEXT] [DOWNSTREAM_SERVICE_REQUIREMENTS] [OPERATIONAL_CONSTRAINTS] Analyze the broken trace context and produce a recovery plan using the following structure: 1. TRACE DIAGNOSIS - Identify which trace fields are missing, malformed, or inconsistent (trace ID, span ID, parent span ID, trace flags, tracestate). - Classify the breakage type: missing trace ID, broken parent-child relationship, sampling decision mismatch, or header propagation gap. - Note any partial information that can be salvaged. 2. CORRELATION ID INJECTION - If the trace ID is missing or invalid, generate a new trace ID following [TRACE_ID_FORMAT] conventions. - Preserve any existing correlation IDs from [CORRELATION_ID_SOURCES] if they are valid. - Document the relationship between the new trace ID and any business-level correlation IDs (request ID, session ID, transaction ID). 3. SPAN PARENT RECONCILIATION - Determine the correct parent span ID based on [UPSTREAM_SERVICE_CONTEXT]. - If the parent span is unknown, decide whether to create a new root span or link to a synthetic parent. - Specify the span kind (CLIENT, SERVER, INTERNAL) for the recovery span. 4. DOWNSTREAM HEADER FORWARDING - Produce the exact trace context headers to forward to [DOWNSTREAM_SERVICES]. - Include traceparent, tracestate, and any vendor-specific headers required by [VENDOR_HEADER_REQUIREMENTS]. - Preserve the sampling decision from [SAMPLING_DECISION_CONTEXT] or apply the default sampling rule from [SAMPLING_POLICY]. 5. RECOVERY VALIDATION CHECKS - Verify trace ID format compliance with [TRACE_ID_FORMAT]. - Confirm parent-child span relationships are acyclic. - Validate that sampling flags are consistent across the recovered context. - Check that all required downstream headers are present. 6. FALLBACK INSTRUCTIONS - If recovery is impossible with available information, specify the escalation path to [ESCALATION_DESTINATION]. - Include the reason for escalation and what additional information would enable recovery. Output your response as a JSON object with the following schema: { "diagnosis": { "breakage_type": "string", "missing_fields": ["string"], "salvageable_fields": ["string"], "severity": "recoverable|degraded|unrecoverable" }, "recovery_plan": { "trace_id": "string", "span_id": "string", "parent_span_id": "string | null", "span_kind": "CLIENT|SERVER|INTERNAL", "correlation_ids": { "trace_id": "string", "request_id": "string | null", "session_id": "string | null" }, "downstream_headers": { "traceparent": "string", "tracestate": "string | null" }, "sampling_decision": "sampled|not_sampled", "validation_results": [ {"check": "string", "passed": true, "detail": "string"} ] }, "escalation": { "required": true, "reason": "string", "destination": "string", "missing_information": ["string"] } | null } [CONSTRAINTS] - Never fabricate trace IDs that could collide with existing traces in [TRACE_ID_NAMESPACE]. - Preserve the original sampling decision unless [SAMPLING_OVERRIDE_POLICY] explicitly permits changes. - Do not forward headers to services outside [ALLOWED_DOWNSTREAM_SERVICES]. - If the broken context contains PII in custom headers, redact according to [PII_REDACTION_POLICY].
Adaptation guidance: Replace each square-bracket placeholder with the actual data, policies, and constraints from your observability pipeline. The [BROKEN_TRACE_CONTEXT] should contain the raw headers or trace state that failed propagation. The [DOWNSTREAM_SERVICE_REQUIREMENTS] should list the exact header formats and propagation expectations of each downstream service. The [OPERATIONAL_CONSTRAINTS] should capture latency budgets, retry limits, and escalation paths. The output schema is designed to be machine-readable so your harness can parse the recovery plan and apply it programmatically. For high-severity breakage where the model returns "severity": "unrecoverable", route to the escalation path immediately without attempting automated recovery. Validate the output JSON against the schema before applying any header injection—malformed recovery plans can corrupt traces further.
Prompt Variables
Required inputs for the Distributed Trace Correlation ID Recovery Prompt Template. Each placeholder must be populated before the prompt is assembled and sent to the model. Missing or malformed variables will cause the recovery instruction to fail silently or produce invalid trace propagation headers.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TRACE_CONTEXT] | The partial or broken trace context object containing available span IDs, trace IDs, and sampling flags | {"traceId": "abc123", "spanId": null, "sampled": true} | Must be valid JSON. Check for null or empty traceId. If traceId is missing, escalate to manual recovery. |
[ERROR_SIGNAL] | The error message, status code, or infrastructure signal that indicates the trace context was lost or corrupted | "Connection reset by peer during span export" | Must be a non-empty string. Parse for known error codes (e.g., 503, DeadlineExceeded). If null, prompt should request manual inspection. |
[SERVICE_BOUNDARY] | The service name or identifier where the trace break occurred, used to determine parent-child span relationships | "payment-gateway-v2" | Must match a known service in the registry. Validate against service catalog. If unknown, set to "unknown-service" and flag for review. |
[DOWNSTREAM_HEADERS] | The set of headers that must be forwarded to downstream services to propagate the recovered correlation ID | ["x-request-id", "x-b3-traceid", "x-b3-spanid"] | Must be a JSON array of header names. Check for duplicates. If empty, default to ["x-correlation-id"]. Validate header name format (lowercase, hyphenated). |
[SAMPLING_POLICY] | The sampling decision that was in effect before the trace break, used to preserve sampling consistency | {"strategy": "probabilistic", "rate": 0.1, "decision": "sampled"} | Must include decision field with value "sampled" or "not_sampled". If missing, default to "not_sampled" to avoid over-sampling. Validate strategy against known values. |
[RETRY_BUDGET] | The remaining retry budget for trace recovery attempts, used to decide whether to inject a new correlation ID or escalate | {"remaining": 2, "max": 3, "escalation_threshold": 0} | Must be a JSON object with integer remaining and max fields. If remaining <= escalation_threshold, prompt must generate escalation instruction instead of retry. Validate remaining <= max. |
[PARENT_SPAN_ID] | The parent span ID to reconcile the broken span against, if known from upstream propagation | "4bf92f3577b34da6" | Must be a 16-character hex string or null. If null, prompt must generate a new root span. Validate hex format and length. If malformed, treat as null. |
Implementation Harness Notes
How to wire the trace correlation ID recovery prompt into an observability pipeline with validation, retries, and sampling decision preservation.
The Distributed Trace Correlation ID Recovery prompt is designed to be called by an observability middleware or sidecar process when a trace context is broken—typically due to a missing traceparent header, a malformed tracestate entry, or a span that has lost its parent reference. The harness should invoke this prompt only after standard W3C Trace Context propagation has failed, not as a primary injection mechanism. The prompt expects structured input containing the partial trace context, the downstream service's expected propagation headers, and the observed breakage point. The output is a corrected set of propagation instructions that the harness must validate before forwarding to the next hop.
Wire the prompt into your request pipeline as a recovery step within an OpenTelemetry SpanProcessor or a custom HTTP middleware. When a span creation fails due to a missing or invalid parent context, serialize the available context—including any partial traceparent, tracestate members, incoming headers, and the target service's expected propagation format—into the [PARTIAL_TRACE_CONTEXT] placeholder. The model will return a JSON object containing a reconstructed traceparent header, a sanitized tracestate list, and a sampling_decision_preserved boolean. Before applying the output, validate that the returned trace-id matches the original if one existed, that the span-id is a valid 16-character hex string, and that the trace-flags byte preserves the sampled bit from the incoming context. If validation fails, increment a trace_recovery_failure metric and fall back to generating a new trace context rather than injecting a malformed one.
Implement a single retry with exponential backoff (1s base, 3s max) if the model call fails or returns unparseable JSON. Do not retry on validation failures—those indicate a semantic error that retrying won't fix. Log every recovery attempt with the original broken context, the model's output, and the validation result to a structured logging sink keyed by the original trace ID (if available) so operators can audit recovery accuracy. For high-throughput services, consider caching recovery decisions by a hash of the partial context input to avoid redundant model calls for identical breakage patterns. Never bypass the sampling decision preservation check: if the model's output flips the sampled flag, discard the recovery and generate a fresh trace context to avoid distorting your tracing sample rate.
Expected Output Contract
Fields, format, and validation rules for the trace propagation instruction produced by the Distributed Trace Correlation ID Recovery Prompt Template. Use this contract to validate the model output before forwarding headers downstream.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
trace_id | string (hex, 32 chars) | Must match regex ^[a-f0-9]{32}$. Reject if length != 32 or contains non-hex characters. | |
span_id | string (hex, 16 chars) | Must match regex ^[a-f0-9]{16}$. Reject if identical to trace_id or parent_span_id. | |
parent_span_id | string (hex, 16 chars) or null | If null, span is root. If set, must match regex ^[a-f0-9]{16}$ and differ from span_id. | |
trace_flags | string (hex, 2 chars) | Must match regex ^[0-9a-f]{2}$. Bit 0 (least significant) indicates sampling decision; reject if sampling bit is set but trace_state omits sampled flag. | |
trace_state | string (W3C tracestate format) or null | If present, must be comma-separated list of vendor=value pairs. Each value must be URL-encoded printable ASCII. Reject if contains unescaped commas in values. | |
propagation_headers | object (key-value map) | Must contain at least traceparent key. tracestate key required if trace_state field is non-null. Header names must be lowercase. Reject if traceparent value does not encode trace_id, span_id, and trace_flags from above fields. | |
recovery_action | string (enum) | Must be one of: inject, propagate, regenerate, escalate. If regenerate, trace_id must be newly generated (not from input). If escalate, propagation_headers must be empty and escalation_reason required. | |
escalation_reason | string or null | Required if recovery_action is escalate. Must be non-empty and describe why trace context cannot be recovered. Reject if present when recovery_action is not escalate. |
Common Failure Modes
Distributed trace recovery prompts fail in predictable ways. These cards cover the most common failure modes and the guardrails that prevent them.
Incomplete Trace Context Reconstruction
What to watch: The model reconstructs a traceparent or tracestate header but omits critical fields like trace-flags or drops the parent span ID, breaking the trace DAG. Guardrail: Validate the output against the W3C Trace Context specification before injection. Require all mandatory fields (trace-id, span-id, trace-flags) and reject partial headers.
Sampling Decision Corruption
What to watch: The recovery prompt overwrites the original sampling flag (sampled vs. not-sampled) or propagates an incorrect tracestate vendor value, causing spans to be dropped by collectors or incurring unexpected ingest costs. Guardrail: Extract and preserve the original trace-flags byte and any vendor-specific tracestate entries from upstream headers. Diff the recovered output against the original before propagation.
Span Parent Reconciliation Mismatch
What to watch: The model assigns the wrong parent span ID when multiple concurrent spans are in flight, creating orphaned spans or incorrect waterfall visualizations in observability tools. Guardrail: Provide the model with the exact parent span ID and operation name from the interrupted request context. Include a validation step that checks parent-child duration nesting sanity before committing the trace.
Downstream Header Forwarding Omission
What to watch: The recovery prompt correctly reconstructs the trace context but fails to include secondary propagation headers like baggage, request-id, or custom tenant identifiers, breaking distributed context in downstream services. Guardrail: Explicitly enumerate all required propagation headers in the prompt template. Validate the output header set against a known allowlist before forwarding.
Trace ID Format and Length Violation
What to watch: The model generates a trace ID with incorrect hex length (not 32 characters), non-hex characters, or an all-zero trace ID, which backends reject silently. Guardrail: Apply a strict regex validator (^[0-9a-f]{32}$) to the generated trace ID. Reject and retry with explicit format constraints if validation fails.
Stale Context Injection from Previous Retries
What to watch: The recovery prompt reuses a trace context from a prior failed retry attempt instead of the original interrupted request, creating duplicate span entries or incorrect timing data. Guardrail: Always anchor recovery to the original root trace context, not the most recent failed attempt. Include the original trace ID and timestamp in the prompt as immutable reference fields.
Evaluation Rubric
Criteria for testing the quality and correctness of a Distributed Trace Correlation ID Recovery Prompt before shipping it in a production harness.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Correlation ID Injection | Output contains a valid traceparent or equivalent header with a new or propagated [TRACE_ID] and [SPAN_ID]. | Missing traceparent header, malformed trace ID, or zero-length span ID. | Regex validation against W3C trace context format; assert header key exists in output. |
Span Parent Reconciliation | The generated span correctly references the incoming [PARENT_SPAN_ID] as its parent. | Parent span ID is missing, set to null incorrectly, or references a different span. | Parse output for parentSpanId field; assert equality with input [PARENT_SPAN_ID]. |
Downstream Header Forwarding | Output includes a complete set of headers (e.g., traceparent, tracestate) for downstream propagation. | tracestate header is dropped, or vendor-specific flags are stripped. | Schema check for required header keys; assert tracestate key-value pairs are preserved from input [TRACESTATE]. |
Sampling Decision Preservation | The sampled flag in the output matches the input [SAMPLED_FLAG] exactly. | Sampled flag is flipped from true to false or vice versa, or is missing. | Bitwise comparison of the sampled flag in the generated traceparent header against the input. |
Trace Completeness | The output contains all required fields: traceId, spanId, parentSpanId, and a valid timestamp. | Missing spanId, null traceId, or timestamp is in the future or epoch zero. | JSON schema validation; assert all required fields are present and non-null; timestamp within a 5-second skew of current time. |
Error Context Handling | When [ERROR_CONTEXT] is provided, the output includes a span event or attribute describing the failure. | Error context is ignored; span is generated without any error status or event. | Parse output for status.code or events array; assert an error event exists when [ERROR_CONTEXT] is not null. |
Retry Budget Awareness | Output includes a retry count or a flag indicating this is a recovery span when [RETRY_COUNT] > 0. | Recovery span is indistinguishable from a root span; no retry metadata is present. | Assert a retry attribute or link to a prior span exists in the output when [RETRY_COUNT] > 0. |
Idempotency Key Handling | If [IDEMPOTENCY_KEY] is provided, it is embedded as a span attribute to prevent duplicate trace creation. | Idempotency key is ignored, leading to potential duplicate spans on replay. | Parse span attributes; assert key 'idempotency.key' exists with the value of [IDEMPOTENCY_KEY] when the input is not null. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single trace context and lighter validation. Drop strict schema enforcement in favor of a free-text instruction that asks the model to propose a trace propagation header block. Accept a plain text or JSON response without field-level checks.
Prompt snippet:
codeYou are an observability assistant. Given a broken trace context [TRACE_FRAGMENT], propose a W3C traceparent header and tracestate entries that restore parent-child linkage. Explain your reasoning.
Watch for
- Missing sampling flag preservation (
sampledbit in trace-flags) - Overly broad instructions that invent span IDs instead of recovering from provided fragments
- No check that the proposed
trace-idmatches the original broken context

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us