Skip to content

Commit 84fde85

Browse files
authored
perf: reduce repeated diagnostic lifecycle scans (#133466)
* perf: reduce repeated diagnostic lifecycle scans * perf: retain native scan for individual diagnostic owners * test: reset gateway admission between shared worker files
1 parent ec3077c commit 84fde85

7 files changed

Lines changed: 74 additions & 13 deletions
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { afterEach, expect, it, vi } from "vitest";
2+
import {
3+
formatPropagatedDiagnosticTraceparent,
4+
registerDiagnosticTracePropagationBridge,
5+
resetDiagnosticTracePropagationForTest,
6+
} from "./diagnostic-trace-propagation.js";
7+
8+
afterEach(resetDiagnosticTracePropagationForTest);
9+
10+
it("shares exporter ordering and cleanup across module instances", async () => {
11+
const trace = {
12+
traceId: "1234567890abcdef1234567890abcdef",
13+
spanId: "1234567890abcdef",
14+
};
15+
const older = { resolveTraceContext: () => ({ ...trace, traceFlags: "00" }) };
16+
const current = { resolveTraceContext: () => undefined };
17+
const stopOlder = registerDiagnosticTracePropagationBridge(older);
18+
vi.resetModules();
19+
const duplicate = await import("./diagnostic-trace-propagation.js");
20+
const stopCurrent = duplicate.registerDiagnosticTracePropagationBridge(current);
21+
const stopDuplicate = registerDiagnosticTracePropagationBridge(older);
22+
23+
expect(formatPropagatedDiagnosticTraceparent(trace)).toBeUndefined();
24+
stopCurrent();
25+
expect(duplicate.formatPropagatedDiagnosticTraceparent(trace)).toBe(
26+
`00-${trace.traceId}-${trace.spanId}-00`,
27+
);
28+
29+
const stopLatest = duplicate.registerDiagnosticTracePropagationBridge(current);
30+
stopOlder();
31+
stopDuplicate();
32+
expect(formatPropagatedDiagnosticTraceparent(trace)).toBeUndefined();
33+
stopLatest();
34+
expect(formatPropagatedDiagnosticTraceparent(trace)).toBe(
35+
`00-${trace.traceId}-${trace.spanId}-01`,
36+
);
37+
38+
registerDiagnosticTracePropagationBridge(current);
39+
duplicate.resetDiagnosticTracePropagationForTest();
40+
expect(formatPropagatedDiagnosticTraceparent(trace)).toBe(
41+
`00-${trace.traceId}-${trace.spanId}-01`,
42+
);
43+
});

‎src/infra/diagnostic-trace-propagation.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,11 @@ function getDiagnosticTracePropagationState(): DiagnosticTracePropagationState {
6969
function activeDiagnosticTracePropagationBridge():
7070
| RegisteredDiagnosticTracePropagationBridge
7171
| undefined {
72-
return Array.from(getDiagnosticTracePropagationState().bridges).at(-1);
72+
let active: RegisteredDiagnosticTracePropagationBridge | undefined;
73+
for (const bridge of getDiagnosticTracePropagationState().bridges) {
74+
active = bridge;
75+
}
76+
return active;
7377
}
7478

7579
export function registerDiagnosticTracePropagationBridge(

‎src/logging/diagnostic-embedded-run-index.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,13 @@ export function createDiagnosticEmbeddedRunIndex<
2121
return embeddedRun;
2222
};
2323
const clear = (activity: TActivity): void => {
24-
for (const workKey of Array.from(activity.activeEmbeddedRuns.keys())) {
25-
remove(activity, workKey);
24+
// Every local owner is leaving; only retain indexes now owned by another activity.
25+
for (const { runId } of activity.activeEmbeddedRuns.values()) {
26+
if (runIdIndex.get(runId) === activity) {
27+
runIdIndex.delete(runId);
28+
}
2629
}
30+
activity.activeEmbeddedRuns.clear();
2731
};
2832
return { clear, remove };
2933
}

‎src/logging/diagnostic-session-state.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ export function getDiagnosticSessionState(ref: SessionRef): SessionState {
188188
queueDepth: 0,
189189
};
190190
diagnosticSessionStates.set(key, created);
191-
pruneDiagnosticSessionStates(Date.now(), true);
191+
pruneDiagnosticSessionStates();
192192
return created;
193193
}
194194

‎src/logging/diagnostic.test.ts‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,6 @@ import {
4040
diagnosticSessionStates,
4141
getDiagnosticSessionState,
4242
peekDiagnosticSessionState,
43-
pruneDiagnosticSessionStates,
4443
resetDiagnosticSessionStateForTest,
4544
} from "./diagnostic-session-state.js";
4645
import {
@@ -214,17 +213,12 @@ describe("diagnostic session state pruning", () => {
214213
it("caps tracked session states to a bounded max", () => {
215214
const now = Date.now();
216215
for (let i = 0; i < 2001; i += 1) {
217-
diagnosticSessionStates.set(`session-${i}`, {
218-
sessionId: `session-${i}`,
219-
lastActivity: now + i,
220-
generation: 0,
221-
state: "idle",
222-
queueDepth: 1,
223-
});
216+
vi.setSystemTime(now + i);
217+
getDiagnosticSessionState({ sessionKey: `session-${i}` }).queueDepth = 1;
224218
}
225-
pruneDiagnosticSessionStates(now + 2002, true);
226219

227220
expect(diagnosticSessionStates.size).toBe(2000);
221+
expect(diagnosticSessionStates.has("session-0")).toBe(false);
228222
});
229223

230224
it("reuses keyed session state when later looked up by sessionId", () => {

‎test/non-isolated-runner.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ function fixtureFiles(): Record<string, string> {
9898
path.join(repoRoot, "src", "infra", "agent-run-registry.ts"),
9999
);
100100
const agentEventsPath = JSON.stringify(path.join(repoRoot, "src", "infra", "agent-events.ts"));
101+
const workAdmissionPath = JSON.stringify(
102+
path.join(repoRoot, "src", "process", "gateway-work-admission.ts"),
103+
);
101104
const activeSessionsPath = JSON.stringify(
102105
path.join(repoRoot, "src", "gateway", "active-sessions-shutdown-tracker.ts"),
103106
);
@@ -211,11 +214,15 @@ function fixtureFiles(): Record<string, string> {
211214
"",
212215
].join("\n"),
213216
"05-a-agent-run.test.ts": [
217+
`import { getActiveGatewayRootWorkCount, markGatewayRestartDraining, tryBeginGatewayRootWorkAdmission } from ${workAdmissionPath};`,
214218
`import { getAgentRunContext, registerAgentRunContext } from ${agentRunRegistryPath};`,
215219
`import { emitAgentEvent, onAgentEvent } from ${agentEventsPath};`,
216220
`import { listActiveSessionsForShutdown, noteActiveSessionForShutdown } from ${activeSessionsPath};`,
217221
'import { expect, it } from "vitest";',
218222
'it("seeds process-global run contexts", () => {',
223+
" expect(tryBeginGatewayRootWorkAdmission()).not.toBeNull();",
224+
" expect(getActiveGatewayRootWorkCount()).toBe(1);",
225+
" markGatewayRestartDraining();",
219226
' noteActiveSessionForShutdown({ cfg: {}, sessionKey: "session-a", sessionId: "session-a", storePath: "/tmp/fixture.sqlite", agentId: "main" });',
220227
" expect(listActiveSessionsForShutdown()).toHaveLength(1);",
221228
' registerAgentRunContext("unrelated-run-a", { sessionKey: "session-a" });',
@@ -232,11 +239,16 @@ function fixtureFiles(): Record<string, string> {
232239
"",
233240
].join("\n"),
234241
"05-b-agent-run.test.ts": [
242+
`import { getActiveGatewayRootWorkCount, tryBeginGatewayRootWorkAdmission } from ${workAdmissionPath};`,
235243
`import { clearAgentRunContext, getAgentRunContext, registerAgentRunContext, sweepStaleRunContexts } from ${agentRunRegistryPath};`,
236244
`import { emitAgentEvent, onAgentEvent } from ${agentEventsPath};`,
237245
`import { listActiveSessionsForShutdown } from ${activeSessionsPath};`,
238246
'import { expect, it } from "vitest";',
239247
'it("clears agent run registry state", () => {',
248+
" expect(getActiveGatewayRootWorkCount()).toBe(0);",
249+
" const admission = tryBeginGatewayRootWorkAdmission();",
250+
" expect(admission).not.toBeNull();",
251+
" admission?.release();",
240252
" expect(listActiveSessionsForShutdown()).toEqual([]);",
241253
' registerAgentRunContext("reused-run", { sessionKey: "reused-session" });',
242254
" let sequence;",

‎test/non-isolated-runner.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { TestRunner, type RunnerTask, type RunnerTestFile, vi } from "vitest";
88
import { resetAgentEventsForTest } from "../src/infra/agent-events.js";
99
import { loggingState } from "../src/logging/state.js";
1010
import { clearNamedPluginRuntimeStoresForTest } from "../src/plugin-sdk/runtime-store-registry.js";
11+
import { resetGatewayWorkAdmission } from "../src/process/gateway-work-admission.js";
1112
import { drainGlobalSingletonLifecycleState } from "../src/shared/global-singleton.js";
1213
import {
1314
type CustomElementTracking,
@@ -489,6 +490,9 @@ export default class OpenClawNonIsolatedRunner extends TestRunner {
489490
// Lifecycle-owned singletons survive module resets; close them before the next file
490491
// can observe a previous file's sessions, caches, or registered resources.
491492
await drainGlobalSingletonLifecycleState();
493+
// Finish file-owned teardown before retiring its admission leases and
494+
// reopening the shared worker for the next file.
495+
resetGatewayWorkAdmission();
492496
// Named plugin runtimes intentionally survive duplicate module evaluation in production.
493497
// Clear their shared slots here so one test file cannot lend a partial runtime to the next.
494498
clearNamedPluginRuntimeStoresForTest();

0 commit comments

Comments
 (0)