Skip to content

fix(diagnostics-otel): agent turns split into one-span traces instead of a trace tree - #116246

Merged
jesse-merhi merged 6 commits into
mainfrom
jesse/diagnostics-otel-parent-span-linking
Jul 30, 2026
Merged

jesse-merhi merged 6 commits into
mainfrom
jesse/diagnostics-otel-parent-span-linking

Conversation

@jesse-merhi

@jesse-merhi jesse-merhi commented Jul 30, 2026 •

Copy link
Copy Markdown
Member

New behavior

Operators using the diagnostics-otel plugin now see one agent turn as one
readable trace tree, including work that finishes more than 30 minutes after its
lifecycle parent ended.

The previous failure was path-dependent:

  • Gateway-dispatched runs already used the diagnostic trace id as their OTel
    trace id, so the old map key happened to match. They still lost late children
    when the retained parent expired after five seconds.
  • CLI- and cron-rooted runs let the OTel SDK create the trace id. Their diagnostic
    and OTel trace ids differed, so the old retained-parent lookup missed even
    before the five-second expiry.

openclaw.exec also never requested a parent, so shell-process spans were
exported as roots.

How it works

Completed lifecycle spans now retain a translation from the event's diagnostic
ids to the real exported OTel SpanContext. Lookups use the diagnostic trace id
that later events carry, while child spans receive the actual OTel parent.

The retained mapping no longer expires based on elapsed time. Completion paths
for message, harness, run, and harness error spans all retain their exported
context. Exec completion events preserve their OpenClaw-owned ambient trace
context without marking the payload itself as trusted, and the recorder parents
them only when this process exported the resolved ancestor.

User Impact

Normal agent turns now export as one trace tree, including model calls, context
assembly, usage, skills, tool execution, and exec spans that finish after their
lifecycle parent. No configuration or migration is required.

Evidence

A/B exporter proof

The same regression test ran against both production implementations in one
Blacksmith Testbox run.
A used the PR base production code with the PR's test; B used the current PR
production code. The test uses the real OTel SDK with an InMemorySpanExporter,
so diagnostic ids and exported OTel ids remain distinct.

Variant Test result Exported trace shape
A — PR base 1 passed, 2 failed The normal turn split across 4 trace ids; the harness-error turn split across 2
B — current PR 3 passed Both turns stayed on one trace; the missing-exported-parent guard also passed

Normal turn on A — PR base:

Trace 1
openclaw.message.processed
└─ openclaw.harness.run
   └─ openclaw.run
      └─ openclaw.model.call

Trace 2  openclaw.tool.execution     (late child of run)
Trace 3  openclaw.context.assembled  (late child of harness)
Trace 4  openclaw.model.usage        (late child of message)

The same turn on B — current PR:

Trace 1
openclaw.message.processed
├─ openclaw.harness.run
│  ├─ openclaw.run
│  │  ├─ openclaw.model.call
│  │  └─ openclaw.tool.execution     (late child retained)
│  └─ openclaw.context.assembled     (late child retained)
└─ openclaw.model.usage              (late child retained)

The aborted-turn case showed the same repair: A exported
openclaw.harness.run and its late openclaw.tool.execution child as two
traces; B exported one trace with the tool span under the harness span.

This covers the message, harness, run, harness-error, late-child, and
missing-exported-parent boundaries.

Checks

  • node scripts/run-vitest.mjs extensions/diagnostics-otel — 116 passed.
  • node scripts/run-vitest.mjs src/agents/bash-tools.exec-runtime.pty-fallback.test.ts src/agents/bash-tools.exec-runtime.test.ts — 37 passed.
  • Blacksmith Testbox run
    — 116 diagnostics tests and 37 exec-runtime tests passed; extension production
    and test typechecks, lint, boundary guards, dead-export checks, and import-cycle
    checks also passed.
  • Four node scripts/run-tsgo.mjs extension/core production and test lanes — passed.
  • node scripts/run-oxlint.mjs extensions/diagnostics-otel src/agents — passed.
  • git diff --check — passed.

Remaining proof and bounds

Maintainer decision (2026-07-30): accept the capacity-bounded retained-context lifetime with no elapsed-time expiry for this change. Retained
mappings do not expire by time. Each record is an id-to-SpanContext lookup,
not a running span. The map holds at most 1,024 records, evicts the oldest
insertion when full, and is cleared when the diagnostics service stops.

A rebase-only proof refresh is intentionally skipped: the branch is conflict-free,
and both Blacksmith runs tested the exact PR head. The required landing workflow
will verify that same head with hosted CI/Testbox before merge.

Retained trusted span contexts translate a completed lifecycle span's
diagnostic span id to the real OTel span context. That table was evicted
5s after run.completed, so children of a longer turn missed their parent
and OTel minted a fresh trace id for each one, silently splitting a turn
into single-span traces.

Retention is now identity-based and lives for the service lifetime,
bounded by MAX_RETAINED_TRUSTED_SPAN_CONTEXTS, which removes the timing
race and the drain/timeout cleanup subsystem.

Also nests openclaw.exec under its run: the exec event now carries a
trusted trace context and the recorder resolves the ambient run scope.
Retained lifecycle span contexts were stored under the span's OTel trace id
but looked up with the event's diagnostic trace id. Those are different id
spaces, so every post-completion parent lookup missed and each straggler
span started a brand-new trace.

The mocked suite could not catch this: its tracer reports the same trace id
the test feeds in, collapsing both id spaces into one value. Adds a boundary
test that runs the real OTel SDK and OTLP/protobuf exporter against a local
receiver and asserts on exported span bytes.
@openclaw-barnacle openclaw-barnacle Bot added extensions: diagnostics-otel Extension: diagnostics-otel agents Agent runtime and tooling size: M maintainer Maintainer-authored PR labels Jul 30, 2026
@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. labels Jul 30, 2026
@clawsweeper

clawsweeper Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 30, 2026, 6:39 AM ET / 10:39 UTC.

ClawSweeper review

What this changes

The PR repairs the diagnostics-otel plugin so late agent lifecycle, tool, usage, and exec spans inherit the original exported OpenTelemetry parent context instead of becoming separate traces.

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

Keep this PR open for maintainer landing review. The branch has strong real exporter proof and no remaining concrete patch defect, but it is behind current main and carries the protected maintainer label, so the final three-way merge candidate and required hosted checks should be refreshed before merge.

Priority: P2
Reviewed head: 1d5b87fd1402f4649bdb23283b2acd641fe2712d
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Strong real exporter evidence and focused regression coverage support the patch; only current-base hosted validation remains before landing.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides an A/B Blacksmith Testbox run using the real OTel SDK and exporter: the base splits one turn across multiple traces while the PR head exports the intended single trace tree.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides an A/B Blacksmith Testbox run using the real OTel SDK and exporter: the base splits one turn across multiple traces while the PR head exports the intended single trace tree.
Evidence reviewed 5 items Retained-parent implementation: The PR changes completed lifecycle handling to retain exported OpenTelemetry parent contexts and resolve later child spans from OpenClaw diagnostic trace context, addressing the distinct diagnostic-ID and OTel-ID spaces described in the PR evidence.
Exec ownership boundary: The agent exec runtime marks only the ambient OpenClaw trace context as trusted while keeping the emitted payload untrusted; the OTel recorder then uses that owned context to parent the exec span rather than treating event payload data as trusted.
Real exporter regression coverage: The added boundary test uses the real OTel SDK and an in-memory exporter, specifically covering the former false equivalence between diagnostic trace IDs and SDK-generated OTel trace IDs.
Findings None None.
Security None None.

How this fits together

The agent runtime emits diagnostic lifecycle events with OpenClaw-owned trace metadata, and the diagnostics-otel plugin records those as OpenTelemetry spans. A retained exported parent context lets later events attach to the completed lifecycle span, preserving one trace tree for an agent turn.

flowchart LR
  A[Agent runtime] --> B[Diagnostic lifecycle events]
  B --> C[Trusted trace metadata]
  C --> D[Diagnostics OTel recorder]
  D --> E[Retained exported parent context]
  E --> F[Late tool usage and exec spans]
  F --> G[Single agent-turn trace tree]
Loading

Decision needed

Question Recommendation
Should this member-authored, protected-label PR be landed after required hosted checks validate its current-base merge candidate? Validate merge candidate, then land: Run the required hosted checks against the current three-way merge result and merge if they preserve the proven exporter trace tree.

Why: The implementation and exporter proof are strong, but the branch is behind main and the maintainer label requires explicit human handling rather than automated cleanup or closure.

Before merge

  • Resolve merge risk (P1) - The PR head was proven against its older base and GitHub reports it behind current main; hosted checks should validate the current three-way merge candidate before landing.
  • Complete next step (P2) - No mechanical repair is identified; a maintainer should approve landing after current-base hosted validation because this member-authored PR has the protected maintainer label.
Agent review details

Security

None.

PR surface

Source +5, Tests +346, Docs +1. Total +352 across 12 files.

View PR surface stats
Area Files Added Removed Net
Source 8 72 67 +5
Tests 3 360 14 +346
Docs 1 5 4 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 437 85 +352

Review metrics

None.

Stored data model

Persistent data-model change detected: vector/embedding metadata: extensions/diagnostics-otel/src/service-events.ts, vector/embedding metadata: extensions/diagnostics-otel/src/service-recorders-harness.ts, vector/embedding metadata: extensions/diagnostics-otel/src/service-recorders-tools.ts, vector/embedding metadata: src/agents/bash-tools.exec-runtime.pty-fallback.test.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Preserve the bounded retained-context design, run the required hosted validation on the current merge candidate, and merge if it confirms the same one-tree exporter behavior without regressions.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Preserve the bounded retained-context design, run the required hosted validation on the current merge candidate, and merge if it confirms the same one-tree exporter behavior without regressions.

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

No high-confidence current-main reproduction was run in this read-only review, but the PR supplies a focused real-SDK exporter regression path that demonstrated the split-trace failure on its base and the repaired trace shape on its head.

Is this the best way to solve the issue?

Yes, subject to current-base validation. Translating OpenClaw diagnostic context to the actual exported OTel parent context is the narrow owner-boundary fix and avoids trusting exec payload data or adding configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 8a3f5c862b56.

Labels

Label changes:

  • remove merge-risk: 🚨 other: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This is a bounded diagnostics correctness repair with meaningful observability impact but no evidence of data loss, security exposure, or core-runtime unavailability.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides an A/B Blacksmith Testbox run using the real OTel SDK and exporter: the base splits one turn across multiple traces while the PR head exports the intended single trace tree.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides an A/B Blacksmith Testbox run using the real OTel SDK and exporter: the base splits one turn across multiple traces while the PR head exports the intended single trace tree.

Evidence

What I checked:

  • Retained-parent implementation: The PR changes completed lifecycle handling to retain exported OpenTelemetry parent contexts and resolve later child spans from OpenClaw diagnostic trace context, addressing the distinct diagnostic-ID and OTel-ID spaces described in the PR evidence. (extensions/diagnostics-otel/src/service-traces.ts:25, 1d5b87fd1402)
  • Exec ownership boundary: The agent exec runtime marks only the ambient OpenClaw trace context as trusted while keeping the emitted payload untrusted; the OTel recorder then uses that owned context to parent the exec span rather than treating event payload data as trusted. (src/agents/bash-tools.exec-runtime.ts:174, 1d5b87fd1402)
  • Real exporter regression coverage: The added boundary test uses the real OTel SDK and an in-memory exporter, specifically covering the former false equivalence between diagnostic trace IDs and SDK-generated OTel trace IDs. (extensions/diagnostics-otel/src/service.otlp-export.test.ts:1, 1d5b87fd1402)
  • Feature-history provenance: The current head commit finalizes capacity-bounded retained parent contexts after the earlier expiry-based variant and records the current intended behavior: retain mappings until bounded capacity eviction. (extensions/diagnostics-otel/src/service-traces.ts:25, 1d5b87fd1402)
  • Current merge state: GitHub reports this PR as cleanly mergeable but behind main; the prior completed ClawSweeper review likewise required validation of the actual current-base merge candidate before landing. (8a3f5c862b56)

Likely related people:

  • jesse-merhi: Authored all six commits in the trace-parenting repair series, including the real-SDK regression coverage and the final bounded-retention implementation. (role: recent diagnostics-otel contributor; confidence: high; commits: bfed8efb6ff4, 647b812ccac2, ec479212e37c; files: extensions/diagnostics-otel/src/service-traces.ts, extensions/diagnostics-otel/src/service.otlp-export.test.ts, src/agents/bash-tools.exec-runtime.ts)

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 (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-30T08:12:42.526Z sha 04e4b90 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T08:52:11.116Z sha 1d5b87f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T09:55:22.047Z sha 1d5b87f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T10:06:36.345Z sha 1d5b87f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T10:17:12.872Z sha 1d5b87f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T10:26:02.516Z sha 1d5b87f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T10:30:07.041Z sha 1d5b87f :: needs maintainer review before merge. :: none
  • reviewed 2026-07-30T10:35:02.759Z sha 1d5b87f :: needs maintainer review before merge. :: none

Review findings on the parent-span linking fix:

- completeTrackedLifecycleSpan now takes the DiagnosticTraceContext instead of a
  bare trace id beside a span id. Two adjacent hex strings let a transposition
  compile clean and silently reinstate split traces; DiagnosticTraceContext is
  the only shape an OTel SpanContext cannot satisfy (traceFlags string vs number).
- internalOrTrustedTraceContext composes normalizedTrustedTraceContext rather
  than spelling the trust predicate a third time.
- Corrected comments that claimed OTel ids never equal diagnostic ids. Spans
  parented from an upstream traceparent do adopt the diagnostic trace id; the
  removed guard only ever misfired on root lifecycle spans.
- Exec comment now states the real parent: the openclaw harness opens no run
  scope, so exec nests under openclaw.harness.run.

Test gaps closed:

- The core emitter switch was untested; reverting it kept every test green.
  The pty-fallback test now asserts the emitted metadata.
- The boundary test covered only run.completed of three lifecycle owners; it now
  covers harness.run.completed and message.processed too, each with a straggler.
- Dropped the service-context cast for the typed helper, which caught a bogus
  context.assembled field, and moved teardown into afterEach so a failed
  assertion cannot leak the real NodeSDK across files.
- Scoped the one-trace assertion to this turn's spans; faked Date so a lazy
  Date.now expiry cannot pass.

Docs: exec and tool spans now listed as staying on an upstream request trace.
…nator

Native review found three correctness gaps in the previous commit:

- Exec spans could be exported naming a parent span id nothing ever emits. The
  ambient lookup fell through to a remote-parent fallback built from diagnostic
  ids, which is a regression from the previous clean-root behavior and breaks
  waterfalls and parent-id-keyed backends. Exec now resolves only spans this
  process exported and stays a root on a miss; message spans keep the remote
  fallback because their context can come from an inbound traceparent.
- harness.run.error never retained its span context, so an aborted turn still
  split. For the openclaw harness that span is the only ancestor a late child
  has, and aborted turns emit no run.completed.
- completeTrackedLifecycleSpan no longer takes a redundant spanId.

The boundary test now runs through the OPENCLAW_OTEL_PRELOADED seam with an
in-memory exporter and releases the global tracer provider in teardown. A
NodeSDK cannot be unregistered, so the old version would have made any later
real-SDK test silently export nothing. That also deletes the hand-rolled OTLP
protobuf decoder. Added guards for the aborted-turn path and for exec staying
parentless; both are mutation-verified.
Retention had no time bound at all, so a command backgrounded by a turn could
finish hours later and still attach to a parent that ended long before. Backends
derive trace latency from the span envelope, so a 30s turn rendered as hours with
a child extending past its parent.

The horizon is checked lazily on lookup rather than on a timer: a timer firing
mid-turn is exactly what silently split traces before. Past the horizon a
straggler starts its own trace, which only loses causality for a span that would
have skewed its parent's duration anyway.

The two bounds now pin each other - shrinking the horizon to the old 5s window
fails the original regression tests, and removing it fails the new horizon test.
@jesse-merhi jesse-merhi self-assigned this Jul 30, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L and removed size: M labels Jul 30, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Jul 30, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 30, 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 30, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

1 similar comment
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Jul 30, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jul 30, 2026
@jesse-merhi
jesse-merhi marked this pull request as ready for review July 30, 2026 10:11
Copilot AI review requested due to automatic review settings July 30, 2026 10:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 30, 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:

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

2 similar comments
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 30, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Jul 30, 2026
@jesse-merhi
jesse-merhi merged commit f1ee2a3 into main Jul 30, 2026
230 of 232 checks passed
@jesse-merhi
jesse-merhi deleted the jesse/diagnostics-otel-parent-span-linking branch July 30, 2026 10:41
@jesse-merhi

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 31, 2026
… of a trace tree (openclaw#116246)

* fix(diagnostics-otel): keep parent span links across long turns

Retained trusted span contexts translate a completed lifecycle span's
diagnostic span id to the real OTel span context. That table was evicted
5s after run.completed, so children of a longer turn missed their parent
and OTel minted a fresh trace id for each one, silently splitting a turn
into single-span traces.

Retention is now identity-based and lives for the service lifetime,
bounded by MAX_RETAINED_TRUSTED_SPAN_CONTEXTS, which removes the timing
race and the drain/timeout cleanup subsystem.

Also nests openclaw.exec under its run: the exec event now carries a
trusted trace context and the recorder resolves the ambient run scope.

* fix(diagnostics-otel): key retained span contexts by diagnostic trace id

Retained lifecycle span contexts were stored under the span's OTel trace id
but looked up with the event's diagnostic trace id. Those are different id
spaces, so every post-completion parent lookup missed and each straggler
span started a brand-new trace.

The mocked suite could not catch this: its tracer reports the same trace id
the test feeds in, collapsing both id spaces into one value. Adds a boundary
test that runs the real OTel SDK and OTLP/protobuf exporter against a local
receiver and asserts on exported span bytes.

* fix(diagnostics-otel): harden span-linking contract after review

Review findings on the parent-span linking fix:

- completeTrackedLifecycleSpan now takes the DiagnosticTraceContext instead of a
  bare trace id beside a span id. Two adjacent hex strings let a transposition
  compile clean and silently reinstate split traces; DiagnosticTraceContext is
  the only shape an OTel SpanContext cannot satisfy (traceFlags string vs number).
- internalOrTrustedTraceContext composes normalizedTrustedTraceContext rather
  than spelling the trust predicate a third time.
- Corrected comments that claimed OTel ids never equal diagnostic ids. Spans
  parented from an upstream traceparent do adopt the diagnostic trace id; the
  removed guard only ever misfired on root lifecycle spans.
- Exec comment now states the real parent: the openclaw harness opens no run
  scope, so exec nests under openclaw.harness.run.

Test gaps closed:

- The core emitter switch was untested; reverting it kept every test green.
  The pty-fallback test now asserts the emitted metadata.
- The boundary test covered only run.completed of three lifecycle owners; it now
  covers harness.run.completed and message.processed too, each with a straggler.
- Dropped the service-context cast for the typed helper, which caught a bogus
  context.assembled field, and moved teardown into afterEach so a failed
  assertion cannot leak the real NodeSDK across files.
- Scoped the one-trace assertion to this turn's spans; faked Date so a lazy
  Date.now expiry cannot pass.

Docs: exec and tool spans now listed as staying on an upstream request trace.

* fix(diagnostics-otel): keep late children on the trace on every terminator

Native review found three correctness gaps in the previous commit:

- Exec spans could be exported naming a parent span id nothing ever emits. The
  ambient lookup fell through to a remote-parent fallback built from diagnostic
  ids, which is a regression from the previous clean-root behavior and breaks
  waterfalls and parent-id-keyed backends. Exec now resolves only spans this
  process exported and stays a root on a miss; message spans keep the remote
  fallback because their context can come from an inbound traceparent.
- harness.run.error never retained its span context, so an aborted turn still
  split. For the openclaw harness that span is the only ancestor a late child
  has, and aborted turns emit no run.completed.
- completeTrackedLifecycleSpan no longer takes a redundant spanId.

The boundary test now runs through the OPENCLAW_OTEL_PRELOADED seam with an
in-memory exporter and releases the global tracer provider in teardown. A
NodeSDK cannot be unregistered, so the old version would have made any later
real-SDK test silently export nothing. That also deletes the hand-rolled OTLP
protobuf decoder. Added guards for the aborted-turn path and for exec staying
parentless; both are mutation-verified.

* fix(diagnostics-otel): age retained parent contexts out after 10 minutes

Retention had no time bound at all, so a command backgrounded by a turn could
finish hours later and still attach to a parent that ended long before. Backends
derive trace latency from the span envelope, so a 30s turn rendered as hours with
a child extending past its parent.

The horizon is checked lazily on lookup rather than on a timer: a timer firing
mid-turn is exactly what silently split traces before. Past the horizon a
straggler starts its own trace, which only loses causality for a span that would
have skewed its parent's duration anyway.

The two bounds now pin each other - shrinking the horizon to the old 5s window
fails the original regression tests, and removing it fails the new horizon test.

* fix(diagnostics-otel): retain parent contexts until capacity
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 maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants