Skip to content

Commit 1d5b87f

Browse files
committed
fix(diagnostics-otel): retain parent contexts until capacity
1 parent 04e4b90 commit 1d5b87f

3 files changed

Lines changed: 15 additions & 63 deletions

File tree

‎extensions/diagnostics-otel/src/service-constants.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,5 +83,3 @@ export const CONTEXT_TOKENS_BUCKETS = [
8383
2_000_000,
8484
];
8585
export const MAX_RETAINED_TRUSTED_SPAN_CONTEXTS = 1024;
86-
/** Outlasts any real turn, so only stragglers that would skew a parent's duration miss. */
87-
export const RETAINED_TRUSTED_SPAN_CONTEXT_MAX_AGE_MS = 600_000;

‎extensions/diagnostics-otel/src/service-traces.ts‎

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,7 @@ import type {
1111
DiagnosticTraceContext,
1212
} from "../api.js";
1313
import { redactOtelAttributes } from "./service-attributes.js";
14-
import {
15-
MAX_RETAINED_TRUSTED_SPAN_CONTEXTS,
16-
RETAINED_TRUSTED_SPAN_CONTEXT_MAX_AGE_MS,
17-
} from "./service-constants.js";
14+
import { MAX_RETAINED_TRUSTED_SPAN_CONTEXTS } from "./service-constants.js";
1815
import {
1916
contextForTraceContext,
2017
normalizedTrustedTraceContext,
@@ -28,13 +25,12 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
2825
string,
2926
{ span: ReturnType<typeof tracer.startSpan>; spanId: string; owner: TrustedSpanAliasOwner }
3027
>();
31-
// Translates a completed lifecycle span's diagnostic span id to the real OTel span
32-
// context so late children still attach to the span we exported. Children of a long
33-
// turn arrive many ticks later, so the horizon must outlast a whole turn; past it a
34-
// straggler would stretch its parent's reported duration instead.
28+
// Keeps a completed lifecycle span's real OTel context for late children.
29+
// Ended contexts remain valid parents without changing their span duration.
30+
// Entries live until capacity eviction or service stop.
3531
const retainedTrustedSpanContexts = new Map<
3632
string,
37-
{ spanContext: SpanContext; retainedAtMs: number; owner?: TrustedSpanAliasOwner }
33+
{ spanContext: SpanContext; owner?: TrustedSpanAliasOwner }
3834
>();
3935
const stopActiveTrustedSpans = () => {
4036
const stopAt = Date.now();
@@ -130,14 +126,6 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
130126
if (!retained) {
131127
return undefined;
132128
}
133-
// Aged out lazily rather than on a timer: a timer that fires mid-turn is what
134-
// silently split traces before, and an expired parent would only skew its duration.
135-
if (Date.now() - retained.retainedAtMs > RETAINED_TRUSTED_SPAN_CONTEXT_MAX_AGE_MS) {
136-
retainedTrustedSpanContexts.delete(
137-
retainedTrustedSpanContextKey(traceContext.traceId, spanId, retained.owner),
138-
);
139-
return undefined;
140-
}
141129
if (retained.owner && !sameTrustedSpanAliasOwner(retained.owner, owner)) {
142130
return undefined;
143131
}
@@ -298,9 +286,9 @@ export function createDiagnosticsTraceRuntime(tracer: Tracer) {
298286
) => {
299287
retainedTrustedSpanContexts.set(retainedTrustedSpanContextKey(traceId, spanId, owner), {
300288
spanContext,
301-
retainedAtMs: Date.now(),
302289
...(owner ? { owner } : {}),
303290
});
291+
// Map iteration is insertion-ordered, so this removes the oldest mapping first.
304292
while (retainedTrustedSpanContexts.size > MAX_RETAINED_TRUSTED_SPAN_CONTEXTS) {
305293
const oldestKey = retainedTrustedSpanContexts.keys().next().value;
306294
if (!oldestKey) {

‎extensions/diagnostics-otel/src/service.test.ts‎

Lines changed: 9 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -191,10 +191,7 @@ import {
191191
runWithDiagnosticTraceContext,
192192
} from "openclaw/plugin-sdk/plugin-test-runtime";
193193
import { emitDiagnosticEvent } from "../api.js";
194-
import {
195-
MAX_RETAINED_TRUSTED_SPAN_CONTEXTS,
196-
RETAINED_TRUSTED_SPAN_CONTEXT_MAX_AGE_MS,
197-
} from "./service-constants.js";
194+
import { MAX_RETAINED_TRUSTED_SPAN_CONTEXTS } from "./service-constants.js";
198195
import { createDiagnosticsOtelService } from "./service.js";
199196
import {
200197
CHILD_SPAN_ID,
@@ -218,8 +215,8 @@ import {
218215
function numberedSpanId(index: number) {
219216
return (index + 0x1000).toString(16).padStart(16, "0");
220217
}
221-
// Comfortably past the retention window a late child used to depend on.
222-
const LATE_CHILD_RETENTION_ELAPSED_MS = 6_000;
218+
// Longer than the default 30-minute background exec timeout.
219+
const LATE_CHILD_ELAPSED_MS = 30 * 60_000 + 1_000;
223220
const PROTO_KEY = "__proto__";
224221
const MAX_TEST_OTEL_CONTENT_ATTRIBUTE_CHARS = 128 * 1024;
225222
const OTEL_TRUNCATED_SUFFIX_MAX_CHARS = 20;
@@ -3654,10 +3651,9 @@ describe("diagnostics-otel service", () => {
36543651
);
36553652
});
36563653

3657-
// Real turns run far longer than any retention window, so children can be
3658-
// dispatched long after run.completed ended the parent span. A missed parent
3659-
// lookup makes OTel mint a fresh trace id, silently splitting the turn into
3660-
// one-span traces, so the link must not depend on elapsed time.
3654+
// Background commands can finish long after run.completed ended the parent span.
3655+
// A missed parent lookup makes OTel mint a fresh trace id, silently splitting the
3656+
// turn into one-span traces, so the link must not depend on elapsed time.
36613657
test.each([
36623658
[
36633659
"openclaw.model.call",
@@ -3679,20 +3675,17 @@ describe("diagnostics-otel service", () => {
36793675
},
36803676
],
36813677
] as const)(
3682-
"parents late %s spans into the run trace after retention elapses",
3678+
"parents late %s spans into the run trace after more than 30 minutes",
36833679
async (spanName, childEvent) => {
3684-
// Fake setTimeout so any retained-context timer can be advanced, and Date so a
3685-
// Date.now()-based lazy expiry cannot pass either. setImmediate stays real so the
3686-
// diagnostic queue keeps draining. This test asserts no timings itself.
3687-
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
3680+
vi.useFakeTimers({ toFake: ["Date"] });
36883681
try {
36893682
await startOtelService({ traces: true, metrics: true });
36903683

36913684
emitRunStarted();
36923685
const runSpanContext = spanByName("openclaw.run").spanContext();
36933686
emitRunCompleted();
36943687

3695-
vi.advanceTimersByTime(LATE_CHILD_RETENTION_ELAPSED_MS);
3688+
vi.setSystemTime(Date.now() + LATE_CHILD_ELAPSED_MS);
36963689
await flushDiagnosticEvents();
36973690
await waitForDiagnosticEventsDrained();
36983691
await flushDiagnosticEvents();
@@ -3709,33 +3702,6 @@ describe("diagnostics-otel service", () => {
37093702
},
37103703
);
37113704

3712-
// Past the horizon a straggler would only stretch its parent's reported duration, so
3713-
// it starts its own trace instead. The window must stay far above a real turn.
3714-
test("stops parenting late children once the retention horizon has passed", async () => {
3715-
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
3716-
try {
3717-
await startOtelService({ traces: true, metrics: true });
3718-
3719-
emitRunStarted();
3720-
emitRunCompleted();
3721-
vi.advanceTimersByTime(RETAINED_TRUSTED_SPAN_CONTEXT_MAX_AGE_MS + 1_000);
3722-
await flushDiagnosticEvents();
3723-
telemetryState.tracer.startSpan.mockClear();
3724-
3725-
emitTrustedDiagnosticEvent({
3726-
type: "model.call.completed",
3727-
...MODEL_CALL_FIXTURE,
3728-
durationMs: 80,
3729-
trace: createTestTrace(MODEL_CALL_SPAN_ID, CHILD_SPAN_ID),
3730-
});
3731-
await flushDiagnosticEvents();
3732-
3733-
expect(startedSpanParentContexts("openclaw.model.call")[0]).toBeUndefined();
3734-
} finally {
3735-
vi.useRealTimers();
3736-
}
3737-
});
3738-
37393705
// Retained contexts outlive the turn, so this bound is what keeps a long-lived
37403706
// gateway from growing the map without limit.
37413707
test("bounds retained run contexts by evicting the oldest completed runs", async () => {

0 commit comments

Comments
 (0)