Skip to content

fix(diagnostics-otel): propagate exported span context - #112283

Merged
vincentkoc merged 4 commits into
openclaw:mainfrom
HughTang:fix/otel-harness-run-adopt-diagnostic-trace
Aug 6, 2026
Merged

vincentkoc merged 4 commits into
openclaw:mainfrom
HughTang:fix/otel-harness-run-adopt-diagnostic-trace

Conversation

@HughTang

@HughTang HughTang commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #112278
Fixes #112486

Summary

The original patch correctly identified the split trace, but its diagnostic-parent fallback could attach openclaw.harness.run to a span ID that no exporter emitted. This repair preserves HughTang's contribution while fixing the identifier mismatch at the trace translation and propagation owner boundary.

  • Diagnostic IDs remain stable correlation keys; they are not forced into OpenTelemetry with a custom IdGenerator.
  • diagnostics-otel records the actual current/exported OpenTelemetry SpanContext when each run, model, or tool span is created.
  • A synchronous typed service bridge lets core format outbound traceparent from that exporter-owned context, including plugin-owned and preloaded SDK copies.
  • Synchronous preparation receives only the event and trusted metadata; captured prompts, messages, and tool definitions stay on the normal asynchronous trusted-listener path.
  • An active bridge miss suppresses diagnostic fallback and removes a caller-supplied traceparent, so OpenClaw never advertises an unexported local parent.
  • Genuine inbound remote parents remain valid at the message boundary.
  • Harness started/completed/error fallback, mid-turn enablement, sibling run/model/tool recorders, and outbound propagation share the same contract.
  • Service lifecycle behavior includes per-signal protocol admission, settle-all local cleanup, provider flush, handler removal, bridge unregister, and preservation of the original startup error when rollback also fails.
  • The public Plugin SDK diagnostic formatter contract is unchanged.

The four-commit contributor series is rebased onto exact main 397a60582a109489d7dd4f1be1136251c10dc1b9; final head is 3c246e182d86a6c59ae8f3085a6ed6c60672e7b5. HughTang remains author of ef61be3fd3bc2cb7bec1fee7c7f19701a18e1b6a, and 431b619db9b492d0aa11a228ba3c5d96e126e09c retains the HughTang co-author trailer.

What Problem This Solves

OpenClaw diagnostic IDs and OpenTelemetry-generated span IDs are intentionally different identifier spaces. The previous outbound path serialized the diagnostic span ID while diagnostics-otel exported a different OTel span ID. The original harness fallback unified trace IDs by inventing a remote parent from the diagnostic ID, but that parent still did not exist in exported spans.

The canonical repair records the real exporter-owned context at span creation, carries it through the diagnostics owner boundary, and resolves it synchronously before outbound propagation. This fixes both the split trace in #112278 and the dangling parent in #112486 without changing OTel ID generation.

Evidence

Focused trusted-source tests:

node scripts/run-vitest.mjs src/infra/diagnostic-trace-context.test.ts src/infra/diagnostic-events.test.ts src/agents/embedded-agent-runner/run/attempt.model-diagnostic-events.test.ts src/plugins/services.test.ts
node scripts/run-vitest.mjs extensions/diagnostics-otel/src/service.test.ts
node scripts/run-vitest.mjs extensions/diagnostics-otel/src/service.otlp-export.test.ts
node scripts/run-vitest.mjs test/e2e/qa-lab/runtime/qa-otel-smoke.e2e.test.ts
node scripts/run-vitest.mjs src/gateway/server-startup-post-attach.test.ts src/plugins/one-shot-diagnostics.test.ts

Result: 443 tests passed across nine focused shards.

The real-SDK OTLP lane starts two HTTP OTLP services with real SDK/exporter instances and proves:

  • one trace with exactly one valid root;
  • every local parentSpanId resolves to an exported span;
  • genuine remote-parent behavior remains valid;
  • plugin-owned, preloaded-SDK, and mid-turn paths work;
  • outbound traceparent trace/span IDs exactly equal the exported openclaw.model.call span context.
  • synchronous preparation does not read or clone trusted private model content before the provider call.

Static and packaged proof:

pnpm tsgo:core
pnpm tsgo:core:test
pnpm tsgo:extensions
pnpm tsgo:extensions:test
pnpm tsgo:test:root
pnpm plugin-sdk:api:check
pnpm plugin-sdk:check-exports
pnpm plugin-sdk:surface:check
pnpm check:import-cycles
pnpm check:database-first-legacy-stores
pnpm check:media-download-helpers
pnpm check:runtime-sidecar-loaders
node scripts/check-native-state-schema-version.mjs
git diff --check
CI=true NODENV_VERSION=24.18.0 PNPM_CONFIG_VERIFY_DEPS_BEFORE_RUN=false pnpm build

Changed-lane guards also passed formatting, plugin boundaries, dependency pins, script declarations, dead-export scans (production/full/script: zero), auth/webhook policy checks, and targeted type-aware lint. Repository search confirms no custom IdGenerator or idGenerator in the affected implementation.

Fresh autoreview:

.agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main --engine codex --model gpt-5.6-sol --thinking high --max-priority P2

Result after the ClawSweeper hot-path correction: clean; no actionable P0-P2 findings, overall correctness patch is correct, confidence 0.91.

Exact-head hosted review and CI:

Blacksmith/Testbox and native prepare:

  • The installed CLI rejected the warmup before lease creation with not authenticated - run 'blacksmith auth login' first.
  • blacksmith auth login --non-interactive --organization openclaw did not complete unattended.
  • The direct attempt created no lease and no Testbox run URL.
  • Per trusted-source fallback policy, the focused tests, changed/static gates, and full packaged build above ran locally.
  • OPENCLAW_TESTBOX=1 scripts/pr prepare-run 112283 completed successfully at 2026-08-06T00:40:03Z in hosted_exact_or_recent_parent mode, verified the exact remote head and tree, and reused hosted exact-head gates.
  • Native prepare remote provider: none; lease ID: none; remote run URL: none.

Repair Scope

  • Architectural owner: core diagnostic propagation seam plus the diagnostics-otel exporter translation and service lifecycle.
  • Canonical fix: exporter-owned SpanContext preparation/resolution through one typed synchronous bridge.
  • Removed paths: active exporter mode no longer serializes synthetic diagnostic parents or preserves stale caller traceparent on a bridge miss; no parallel custom-ID path was added.
  • Production delta: +261/-24, net +237, justified by the typed cross-SDK ownership boundary, exporter context mapping, and lifecycle-safe bridge.
  • Test/support delta: +522/-4, net +518.
  • Docs delta: +11/-7, net +4.

@openclaw-barnacle openclaw-barnacle Bot added extensions: diagnostics-otel Extension: diagnostics-otel size: XS triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 21, 2026
@steipete steipete self-assigned this Jul 25, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. labels Jul 31, 2026
@clawsweeper

clawsweeper Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 5, 2026, 8:35 PM ET / August 6, 2026, 00:35 UTC.

ClawSweeper review

What this changes

This PR makes outbound model requests use the actual OpenTelemetry context of the exported model span instead of OpenClaw’s separate diagnostic correlation ID.

Regression provenance

Possible regression — probable (reproduction; reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

No blocking correctness finding: the exact-head bridge records and propagates exporter-owned span context, resolving the split-trace and dangling-parent reports. Merge still needs an explicit maintainer disposition for the additive plugin service-context capability.

Priority: P2
Reviewed head: 3c246e182d86a6c59ae8f3085a6ed6c60672e7b5
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Exact-head real transport proof and focused regressions support the repair; the remaining item is explicit acceptance of the additive plugin API seam.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): An exact-head member comment supplies terminal output from a real OpenTelemetry SDK/exporter path across two loopback OTLP services, showing a single rooted trace and an outbound header equal to the exported model span.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): An exact-head member comment supplies terminal output from a real OpenTelemetry SDK/exporter path across two loopback OTLP services, showing a single rooted trace and an outbound header equal to the exported model span.
Evidence reviewed 5 items Current-main failure path: Current main formats the diagnostic child context directly for outbound model requests, whereas the PR emits the model-start event first and resolves the exporter-owned context before the request headers are prepared.
Exact-head propagation owner: The bridge is installed only with active trusted diagnostics tracing, prepares model/tool starts synchronously, then resolves only a valid actual or retained OTel span context.
No synthetic-parent fallback: When an active exporter cannot resolve a span, the propagation path omits the header instead of serializing an unexported diagnostic parent.
Findings None None.
Security None None.

How this fits together

Agent diagnostics emit model-call events that the diagnostics OpenTelemetry plugin turns into spans. Before a provider request leaves OpenClaw, the model-call path now obtains the exporter-created span context and serializes it as a W3C trace header.

flowchart LR
A[Agent run] --> B[Diagnostic event]
B --> C[Diagnostics OpenTelemetry plugin]
C --> D[Exported model span]
D --> E[Outbound trace header]
E --> F[Provider or downstream trace]
Loading

Decision needed

Question Recommendation
Should the optional trusted registerTracePropagationBridge capability remain a supported plugin service-context seam for diagnostics exporters? Accept the trusted diagnostics seam: Retain the optional capability as the narrow generic boundary for exporter-owned trace propagation.

Why: The change is additive and capability-gated, but OpenClawPluginServiceContext is publicly re-exported, so its long-term plugin API contract needs maintainer intent.

Before merge

  • Resolve merge risk (P1) - The additive optional registerTracePropagationBridge capability changes the public plugin service-context type; existing consumers are not broken, but maintainers should explicitly accept this as the intended supported seam.
  • Resolve merge risk (P1) - Direct OpenTelemetry dependency-source inspection was unavailable because the checkout has no installed dependencies and network reads were blocked; exact-head real-SDK behavior proof mitigates, but does not replace, that contract check.
  • Complete next step (P2) - A maintainer must explicitly accept or reject the additive public plugin service-context seam; no mechanical repair is indicated.
Agent review details

Security

None.

PR surface

Source +242, Tests +513, Docs +4. Total +759 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 12 267 25 +242
Tests 7 516 3 +513
Docs 1 11 7 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 794 35 +759

Review metrics

Metric Value Why it matters
Production and regression coverage production +237 net; tests +518 net; docs +4 net The production growth implements the typed exporter-to-core ownership boundary; the larger test delta covers lifecycle, duplicate-span, and real OTLP behavior.
Plugin service capability 1 optional capability added The additive service-context API is the remaining compatibility decision before merge.

Stored data model

Persistent data-model change detected: vector/embedding metadata: extensions/diagnostics-otel/src/service-recorders-model.ts, vector/embedding metadata: extensions/diagnostics-otel/src/service-recorders-tools.ts, vector/embedding metadata: src/infra/diagnostic-events.ts, vector/embedding metadata: src/infra/diagnostic-trace-propagation.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: canonical
Canonical: #112283
Summary: This PR is the candidate fix for the linked split-trace and dangling-parent reports.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Accept the trusted diagnostics API seam (recommended)
    Record maintainer acceptance that the optional capability is the supported cross-plugin boundary for exporter-owned propagation.
  2. Internalize the bridge
    Replace the public service-context addition with a bundled-only boundary if maintainers do not want this plugin API surface.

Technical review

Best possible solution:

Keep one exporter-owned propagation path, explicitly accept the narrow trusted diagnostics service capability, and retain the real-SDK OTLP regression that proves every propagated parent is exported.

Do we have a high-confidence way to reproduce the issue?

Yes, source-reproducible: current main formats diagnostic identifiers into outbound headers, while the exact-head real-SDK OTLP regression proves the corrected exporter-context path.

Is this the best way to solve the issue?

Yes: recording the exporter-owned context at span creation avoids both synthetic parents and custom OpenTelemetry ID generation, while preserving diagnostic IDs as correlation keys.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 678a3c18a941.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. An exact-head member comment supplies terminal output from a real OpenTelemetry SDK/exporter path across two loopback OTLP services, showing a single rooted trace and an outbound header equal to the exported model span.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): An exact-head member comment supplies terminal output from a real OpenTelemetry SDK/exporter path across two loopback OTLP services, showing a single rooted trace and an outbound header equal to the exported model span.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The patch repairs optional diagnostics trace correlation with bounded operator impact.
  • merge-risk: 🚨 compatibility: It adds an optional capability to a publicly re-exported plugin service-context type.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): An exact-head member comment supplies terminal output from a real OpenTelemetry SDK/exporter path across two loopback OTLP services, showing a single rooted trace and an outbound header equal to the exported model span.
  • proof: sufficient: Contributor real behavior proof is sufficient. An exact-head member comment supplies terminal output from a real OpenTelemetry SDK/exporter path across two loopback OTLP services, showing a single rooted trace and an outbound header equal to the exported model span.

Evidence

What I checked:

Likely related people:

  • vincentkoc: Authored three of the four PR commits, supplied exact-head proof, and recently landed adjacent diagnostics-otel lifecycle and protocol repairs. (role: recent area contributor; confidence: high; commits: 431b619db9b4, 871d8fb442a5, 3c246e182d86; files: extensions/diagnostics-otel/src/service.ts, extensions/diagnostics-otel/src/service-traces.ts)
  • HughTang: Authored the initial diagnostic trace-context change and the linked reports that define the observed split-trace behavior. (role: original tracing contributor; confidence: medium; commits: ef61be3fd3bc; files: extensions/diagnostics-otel/src/service-recorders-tools.ts)
  • steipete: Recent diagnostics service refactor history and the PR assignment connect this person to the surrounding owner boundary. (role: adjacent refactor contributor; confidence: medium; commits: 6454b07; files: src/plugins/services.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record maintainer acceptance of the optional trusted diagnostics service capability.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-07-30T10:48:02.432Z sha d7975921b480a835e8e3fd13e98ae5826c23ff6e :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-01T23:13:07.757Z sha d7975921b480a835e8e3fd13e98ae5826c23ff6e :: needs real behavior proof before merge. :: [P1] Do not parent harness roots to unexported diagnostic spans
  • reviewed 2026-08-03T12:10:56.769Z sha d7975921b480a835e8e3fd13e98ae5826c23ff6e :: found issues before merge. :: [P1] Avoid remote parents that have no exported OTel span
  • reviewed 2026-08-05T19:33:58.210Z sha d9ce5238e05086f413de45793e68e03aae61b37f :: needs real behavior proof before merge. :: [P1] Break the diagnostic-events import cycle | [P1] Preserve the public trace formatter contract | [P2] Filter propagation before cloning event payloads
  • reviewed 2026-08-05T20:41:42.773Z sha 37ac1b9e099110526108a52dad1f9d5a4adfe37a :: needs real behavior proof before merge. :: [P2] Avoid cloning private diagnostic payloads before model calls

@vincentkoc vincentkoc self-assigned this Jul 31, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Aug 1, 2026
@guizaols

guizaols commented Aug 3, 2026

Copy link
Copy Markdown

Validated this PR against real traffic. It does what it says: with the patch applied, one agent
turn becomes one trace spanning both the gateway and the service it calls back into.

Resulting trace, 377 spans, two services:

14649ms  [gateway]  openclaw.harness.run
14641ms  [gateway]    openclaw.run
 5801ms  [gateway]      openclaw.tool.execution
 5500ms  [caller]       POST /api/internal/agent_tools/search_products
 4931ms  [gateway]      openclaw.model.call
 2751ms  [gateway]      openclaw.model.call
  482ms  [caller]          SELECT ...
  417ms  [caller]        GET /api/internal/agent_tools/last_purchases
  294ms  [caller]        GET /api/internal/agent_tools/open_cart

openclaw-stg-proc3 contributes 6 spans, the calling service 371, all on trace id
27b3a715c6c11586c36a45fc2862f9d1. Without the patch, same setup, the two sides land on
unrelated trace ids (2bc5f442… for the harness, 7e4a45b6… for the callbacks).

A gotcha for anyone else validating this PR. We first concluded the patch had not worked,
because the callback spans never showed up in our tracing backend. That was our own fault and
worth flagging: the receiving service was running OTEL_TRACES_SAMPLER=traceidratio, which is
not parent-based, so it re-rolled the sampling decision on the shared trace id and dropped it.
Switching to parentbased_traceidratio made it honour the gateway's decision and the callback
spans appeared. If you validate this and see only gateway spans on the trace, check the sampler
on the receiving side before blaming the patch.

One thing this PR does not fix, and probably should be landed alongside #112486. In the
trace above, openclaw.harness.run and each callback span carry a parentSpanId that is never
exported, so the unified trace still has no root:

openclaw.harness.run                            parentSpanId=<not exported>
POST /api/internal/agent_tools/search_products  parentSpanId=<not exported>

The practical effect is that the spans are correctly grouped but the hierarchy is not fully
resolvable. This PR is what makes the trace whole; #112486 is what makes it rooted.

Environment: gateway [email protected], @openclaw/[email protected] with these
three call sites patched in (in 2026.6.11 they live in service.ts, and
internalOrTrustedParentContext already exists there, so the change applies cleanly to that
release too). GATEWAY_PROCS=4, OTLP/HTTP → OpenTelemetry Collector → Grafana Tempo.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 3, 2026
@vincentkoc
vincentkoc force-pushed the fix/otel-harness-run-adopt-diagnostic-trace branch from d797592 to d9ce523 Compare August 5, 2026 19:24
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L and removed size: XS labels Aug 5, 2026
@vincentkoc vincentkoc changed the title fix(diagnostics-otel): harness.run root span adopts diagnostic trace context fix(diagnostics-otel): propagate exported span context Aug 5, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Aug 5, 2026
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Aug 5, 2026
@clawsweeper clawsweeper Bot added the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label Aug 5, 2026
HughTang and others added 3 commits August 6, 2026 00:49
…context

Fall back to internalOrTrustedParentContext when there is no active
tracked parent, so the openclaw.harness.run root span (and its whole
OTel subtree) adopts the diagnostic traceId instead of minting a new
OTel root. This lets spans propagated via the diagnostic traceparent
(e.g. a2a-gateway a2a.call / downstream a2a.task) share one trace with
the run internals.
@vincentkoc
vincentkoc force-pushed the fix/otel-harness-run-adopt-diagnostic-trace branch from 37ac1b9 to 510ba03 Compare August 5, 2026 23:36
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Exact head: 510ba03ced014926844d4dac40884f671a1b8b38

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc
vincentkoc force-pushed the fix/otel-harness-run-adopt-diagnostic-trace branch from 510ba03 to 3c246e1 Compare August 6, 2026 00:08
@vincentkoc

vincentkoc commented Aug 6, 2026 •

Copy link
Copy Markdown
Member

Exact-head real OTLP proof for 3c246e182d86a6c59ae8f3085a6ed6c60672e7b5.

Command:

node scripts/run-vitest.mjs extensions/diagnostics-otel/src/service.otlp-export.test.ts

Observed terminal result:

RUN  v4.1.10
Test Files  1 passed (1)
Tests       82 passed (82)
Duration    1.77s

This lane uses real OpenTelemetry SDK/provider/exporter instances and two loopback HTTP OTLP services. A temporary evidence-only reporter over the same exact-head capturedSpans data printed the following redacted output; it did not change the commit. Stable placeholders preserve identity and parent equality:

OTLP_PROOF_BEGIN
span_count=7
trace_count=1
root_count=1
root_names=peer.request
unresolved_local_parents=0
exported_model.trace_id=[trace-1]
exported_model.span_id=[span-3]
outbound.traceparent=00-[trace-1]-[span-3]-01
outbound_matches_exported_model=true
span name=openclaw.harness.run trace=[trace-1] id=[span-1] parent=[span-2]
span name=openclaw.message.processed trace=[trace-1] id=[span-2] parent=[span-7]
span name=openclaw.model.call trace=[trace-1] id=[span-3] parent=[span-4]
span name=openclaw.run trace=[trace-1] id=[span-4] parent=[span-1]
span name=openclaw.tool.execution trace=[trace-1] id=[span-5] parent=[span-4]
span name=peer.callback trace=[trace-1] id=[span-6] parent=[span-3]
span name=peer.request trace=[trace-1] id=[span-7] parent=<root>
OTLP_PROOF_END

Source:

test("propagates the exported model span across two OTLP services with one rooted trace", async () => {
const receiver = startLocalOtlpReceiver();
const port = await receiver.listen();
const endpoint = `http://127.0.0.1:${port}`;
releasePreloadedOtelGlobals();
const peerProvider = new BasicTracerProvider({
resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: "openclaw-otel-peer" }),
spanProcessors: [
new SimpleSpanProcessor(
new OTLPTraceExporter({
url: `${endpoint}/v1/traces`,
}),
),
],
});
const peerTracer = peerProvider.getTracer("openclaw-otel-peer");
const peerRoot = peerTracer.startSpan("peer.request");
const peerRootContext = peerRoot.spanContext();
const inboundParent = createDiagnosticTraceContext({
traceId: peerRootContext.traceId,
spanId: peerRootContext.spanId,
traceFlags: peerRootContext.traceFlags.toString(16).padStart(2, "0"),
});
const { service, ctx } = await startOtelService({
endpoint,
traces: true,
metrics: false,
logs: false,
configure: (serviceContext) => {
serviceContext.config.diagnostics!.otel!.serviceName = "openclaw-otel-gateway";
},
});
try {
const messageTrace = createChildDiagnosticTraceContext(inboundParent);
const harnessTrace = createChildDiagnosticTraceContext(messageTrace);
const runTrace = createChildDiagnosticTraceContext(harnessTrace);
const toolTrace = createChildDiagnosticTraceContext(runTrace);
const base = { runId: "run-live-bridge", provider: "openai", model: "gpt-5.6-luna" };
const harnessBase = { ...base, harnessId: "openclaw" };
emit({
type: "message.dispatch.started",
channel: "web",
source: "http",
trace: messageTrace,
});
emit({ type: "harness.run.started", ...harnessBase, trace: harnessTrace });
emit({ type: "run.started", ...base, trace: runTrace });
const outboundTraceparent = runModelCallAndCaptureTraceparent({
...base,
callId: "call-live-bridge",
trace: runTrace,
});
const outboundContext = parseDiagnosticTraceparent(outboundTraceparent);
expect(outboundContext).toBeDefined();
const peerCallback = peerTracer.startSpan(
"peer.callback",
{},
trace.setSpanContext(context.active(), {
traceId: outboundContext!.traceId,
spanId: outboundContext!.spanId!,
traceFlags: Number.parseInt(outboundContext!.traceFlags ?? "00", 16),
isRemote: true,
}),
);
peerCallback.end();
emit({
type: "tool.execution.started",
runId: base.runId,
toolName: "http",
trace: toolTrace,
});
emit({
type: "tool.execution.completed",
runId: base.runId,
toolName: "http",
durationMs: 10,
trace: toolTrace,
});
emit({
type: "run.completed",
...base,
outcome: "completed",
durationMs: 60,
trace: runTrace,
});
emit({
type: "harness.run.completed",
...harnessBase,
outcome: "completed",
durationMs: 70,
trace: harnessTrace,
});
emit({
type: "message.processed",
channel: "web",
outcome: "completed",
durationMs: 80,
trace: messageTrace,
});
await waitForDiagnosticEventsDrained();
peerRoot.end();
await service.stop?.(ctx);
await peerProvider.shutdown();
const spans = receiver.capturedSpans.filter((span) =>
[
"peer.request",
"peer.callback",
"openclaw.message.processed",
"openclaw.harness.run",
"openclaw.run",
"openclaw.model.call",
"openclaw.tool.execution",
].includes(span.name),
);
const spanIds = new Set(spans.map((span) => span.spanId));
const roots = spans.filter((span) => !span.parentSpanId);
const modelSpan = spans.find((span) => span.name === "openclaw.model.call");
expect(spans).toHaveLength(7);
expect(new Set(spans.map((span) => span.traceId)).size).toBe(1);
expect(roots.map((span) => span.name)).toEqual(["peer.request"]);
expect(spans.every((span) => !span.parentSpanId || spanIds.has(span.parentSpanId))).toBe(true);
expect(outboundContext?.traceId).toBe(modelSpan?.traceId);
expect(outboundContext?.spanId).toBe(modelSpan?.spanId);
expect(spans.find((span) => span.name === "peer.callback")?.parentSpanId).toBe(
modelSpan?.spanId,
);
} finally {
peerRoot.end();
await service.stop?.(ctx);
await peerProvider.shutdown();
await receiver.close();
}

The hot-path follow-up also removes private diagnostic payloads from synchronous preparation. Its regression test passes captured model content with an observable getter and proves preparation never reads it.

Source:

it("prepares trusted events synchronously without cloning private data", async () => {
const diagnosticTrace = createDiagnosticTraceContext({
traceId: "4bf92f3577b34da6a3ce929d0e0e4736",
spanId: "00f067aa0ba902b7",
traceFlags: "01",
});
const exportedTrace = createDiagnosticTraceContext({
traceId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
spanId: "bbbbbbbbbbbbbbbb",
traceFlags: "00",
});
const prepared: string[] = [];
let privateDataReads = 0;
const bridge: DiagnosticTracePropagationBridge<
DiagnosticEventPayload,
DiagnosticEventMetadata
> = {
shouldPrepareEvent(event) {
return event.type === "model.call.started";
},
prepareEvent(event) {
prepared.push(event.type);
},
resolveTraceContext(traceContext) {
expect(traceContext).toBe(diagnosticTrace);
return exportedTrace;
},
};
registerDiagnosticTracePropagationBridge(bridge);
emitTrustedDiagnosticEventWithPrivateData(
{
type: "model.call.started",
runId: "run-1",
callId: "call-1",
provider: "openai",
model: "gpt-5.4",
trace: diagnosticTrace,
},
{
modelContent: {
get inputMessages() {
privateDataReads += 1;
return ["secret prompt"];
},
},
},
);
expect(privateDataReads).toBe(0);
emitTrustedDiagnosticEvent({
type: "model.call.completed",
runId: "run-1",
callId: "call-1",
provider: "openai",
model: "gpt-5.4",
durationMs: 1,
trace: diagnosticTrace,
});
expect(prepared).toEqual(["model.call.started"]);
expect(formatDiagnosticTraceparent(diagnosticTrace)).toBe(
`00-${diagnosticTrace.traceId}-${diagnosticTrace.spanId}-01`,
);
expect(formatPropagatedDiagnosticTraceparent(diagnosticTrace)).toBe(
`00-${exportedTrace.traceId}-${exportedTrace.spanId}-00`,
);
await waitForDiagnosticEventsDrained();
expect(privateDataReads).toBe(0);
});

@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Exact head: 3c246e182d86a6c59ae8f3085a6ed6c60672e7b5

@clawsweeper

clawsweeper Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 6, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Maintainer disposition for exact head 3c246e182d86a6c59ae8f3085a6ed6c60672e7b5:

No code changed after the exact-head review.

@vincentkoc
vincentkoc merged commit a1064ad into openclaw:main Aug 6, 2026
142 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 6, 2026
* fix(diagnostics-otel): harness.run root span adopts diagnostic trace context

Fall back to internalOrTrustedParentContext when there is no active
tracked parent, so the openclaw.harness.run root span (and its whole
OTel subtree) adopts the diagnostic traceId instead of minting a new
OTel root. This lets spans propagated via the diagnostic traceparent
(e.g. a2a-gateway a2a.call / downstream a2a.task) share one trace with
the run internals.

* fix(diagnostics-otel): propagate exported span context

Co-authored-by: HughTang <[email protected]>

* fix(diagnostics): break propagation import cycle

* fix(diagnostics): preserve trace propagation contracts

---------

Co-authored-by: Vincent Koc <[email protected]>
vincentkoc added a commit to VACInc/openclaw that referenced this pull request Aug 6, 2026
…cope

* origin/main: (24 commits)
  fix(backup): skip transient gateway lock databases (openclaw#119782)
  test(agents): use canonical auth session fixtures (openclaw#119821)
  fix(memory): keep QMD file hints after stale docid misses (issue openclaw#113041) (openclaw#113515)
  test(doctor): align fast-path repair contracts (openclaw#119812)
  perf(agents): index subagent recovery ownership (openclaw#119793)
  fix(gateway): keep chat startup off catalog discovery (openclaw#119742)
  fix(test): keep TUI PTY suites in their owner lane (openclaw#119787)
  docs: correct dashboard auth precedence (openclaw#119785)
  docs: document control ui owner handoff
  fix: grant host-authorized control ui owner access
  fix(worktrees): preserve registered roots during orphan cleanup (openclaw#119709)
  fix(matrix): prevent shared client key collisions (openclaw#119667)
  fix(diagnostics-otel): propagate exported span context (openclaw#112283)
  fix(worker): isolate state observer failures (openclaw#117507)
  fix(qa): attest realized profile executions (openclaw#119761)
  fix(gateway): finish successful sessions after timestamp races (openclaw#119752)
  fix(agents): fence restart recovery lifecycle (openclaw#119776)
  fix(ui): preserve chat history and active run timing (openclaw#119729)
  improve(ollama): reduce inactive startup cost (openclaw#119745)
  improve(gateway): defer inactive plugin runtime imports (openclaw#119733)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: diagnostics-otel Extension: diagnostics-otel gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

4 participants