Skip to content

Commit d17b12f

Browse files
committed
perf(ci): reuse compiled session workers
1 parent 4a79c12 commit d17b12f

6 files changed

Lines changed: 33 additions & 45 deletions

File tree

‎docs/reference/test.md‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -179,17 +179,18 @@ and runtime parents on TypeScript. Importing a declared subprocess entrypoint
179179
compiles the fixed test entry set and its workspace dependencies into one fresh
180180
invocation directory under `.artifacts/vitest-workers/`.
181181

182-
The seven application subprocess entries run as plain Node JavaScript without a
182+
The nine declared application entries run as plain Node JavaScript without a
183183
TypeScript loader: SQLite read-only snapshots, database verification, Tailscale
184-
route ownership, the service relay, its POSIX and Windows anchors, and the memory
185-
plugin's KNN child. The same generation also compiles the fake-backend TUI
184+
route ownership, the service relay, its POSIX and Windows anchors, the memory
185+
plugin's KNN child, and the session transcript archive and reconciliation workers.
186+
The same generation also compiles the fake-backend TUI
186187
fixture's four runtime roots together: the real TUI, embedded reply producer,
187188
reply metadata reader, and outbound normalizer. Shared chunks preserve their
188189
module and WeakMap identity. Generated TUI fixtures remain `.mts` files: Node
189190
launches them with `--import tsx` for their own syntax, while Bun handles that
190191
syntax natively without the Node loader. Only their runtime imports change.
191-
Application/package build entries and Vitest source parents stay unchanged. This
192-
does not convert Worker-thread entries or arbitrary source CLI fixtures.
192+
Package build entry paths and Vitest source parents stay unchanged. Other
193+
Worker-thread entries and arbitrary source CLI fixtures remain outside this declared set.
193194

194195
Preparation is lazy across both projects and shards. Config imports, listing
195196
tests, and tiny tests that do not import these declarations do not load the

‎src/config/sessions/session-accessor.sqlite-archive.ts‎

Lines changed: 3 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import { createHash, randomUUID } from "node:crypto";
22
import fs from "node:fs";
33
import path from "node:path";
4-
import { fileURLToPath, pathToFileURL } from "node:url";
54
import { Worker } from "node:worker_threads";
65
import { toStringifiedError } from "@openclaw/normalization-core/error-coercion";
76
import { syncDirectoryBestEffortSync } from "../../infra/directory-durability.js";
7+
import { runtimeProcessEntrypoints } from "../../infra/runtime-process-entrypoints.js";
8+
import { resolveRuntimeWorkerUrl } from "../../infra/runtime-worker-url.js";
89
import { KeyedAsyncQueue } from "../../plugin-sdk/keyed-async-queue.js";
910
import { withOpenClawAgentDatabaseReadOnly } from "../../state/openclaw-agent-db-readonly.js";
1011
import {
@@ -268,21 +269,6 @@ export function publishEncodedSessionTranscriptArchive(params: {
268269
return archivePath;
269270
}
270271

271-
function resolveSqliteTranscriptArchiveWorkerUrl(currentModuleUrl = import.meta.url): URL {
272-
const currentPath = fileURLToPath(currentModuleUrl);
273-
const normalized = currentPath.replaceAll(path.sep, "/");
274-
const distMarker = "/dist/";
275-
const distIndex = normalized.lastIndexOf(distMarker);
276-
if (distIndex >= 0) {
277-
const distRoot = currentPath.slice(0, distIndex + distMarker.length);
278-
return pathToFileURL(
279-
path.join(distRoot, "config", "sessions", "session-accessor.sqlite-archive.worker.js"),
280-
);
281-
}
282-
const extension = path.extname(currentPath) || ".js";
283-
return new URL(`./session-accessor.sqlite-archive.worker${extension}`, currentModuleUrl);
284-
}
285-
286272
function resolveSourceWorkerExecArgv(): string[] {
287273
// Node 22 can strip the .ts entrypoint itself, but `--import tsx` does not
288274
// register tsx's ESM resolver inside a Worker. Explicitly register the
@@ -297,7 +283,7 @@ function spawnSqliteTranscriptArchiveWorker<Result>(params: {
297283
expectedMessageType: "done" | "published";
298284
workerData: object;
299285
}): Promise<Result[]> {
300-
const workerUrl = resolveSqliteTranscriptArchiveWorkerUrl();
286+
const workerUrl = resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.sessionTranscriptArchive);
301287
let worker: Worker;
302288
try {
303289
const sourceWorkerExecArgv = workerUrl.pathname.endsWith(".ts")

‎src/config/sessions/session-transcript-reconcile.ts‎

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
// Transcript projection reconciliation owner. Gateway startup awaits it;
22
// request paths may only schedule it and return a bounded retryable response.
33
import { randomInt } from "node:crypto";
4-
import path from "node:path";
54
import { setTimeout as delay } from "node:timers/promises";
6-
import { fileURLToPath, pathToFileURL } from "node:url";
75
import { Worker, type WorkerOptions } from "node:worker_threads";
86
import { toStringifiedError } from "@openclaw/normalization-core/error-coercion";
97
import { isPathInside } from "../../infra/path-guards.js";
8+
import { runtimeProcessEntrypoints } from "../../infra/runtime-process-entrypoints.js";
9+
import { resolveRuntimeWorkerUrl } from "../../infra/runtime-worker-url.js";
1010
import { createSubsystemLogger } from "../../logging/subsystem.js";
1111
import {
1212
openOpenClawAgentDatabase,
@@ -69,21 +69,6 @@ function reconcileKey(params: OpenClawAgentDatabaseOptions): string {
6969
return resolveOpenClawAgentSqlitePath(params);
7070
}
7171

72-
function resolveSessionTranscriptReconcileWorkerUrl(currentModuleUrl = import.meta.url): URL {
73-
const currentPath = fileURLToPath(currentModuleUrl);
74-
const normalized = currentPath.replaceAll(path.sep, "/");
75-
const distMarker = "/dist/";
76-
const distIndex = normalized.lastIndexOf(distMarker);
77-
if (distIndex >= 0) {
78-
const distRoot = currentPath.slice(0, distIndex + distMarker.length);
79-
return pathToFileURL(
80-
path.join(distRoot, "config", "sessions", "session-transcript-reconcile.worker.js"),
81-
);
82-
}
83-
const extension = path.extname(currentPath) || ".js";
84-
return new URL(`./session-transcript-reconcile.worker${extension}`, currentModuleUrl);
85-
}
86-
8772
function yieldToGateway(): Promise<void> {
8873
return new Promise((resolve) => {
8974
setImmediate(resolve);
@@ -226,7 +211,7 @@ export async function reconcileSessionTranscriptIndexes(
226211
if (!needsWorker) {
227212
return { reconciledSessions: 0 };
228213
}
229-
const workerUrl = resolveSessionTranscriptReconcileWorkerUrl();
214+
const workerUrl = resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.sessionTranscriptReconcile);
230215
const sourceWorkerExecArgv = workerUrl.pathname.endsWith(".ts") ? ["--import", "tsx"] : undefined;
231216
const input: SessionTranscriptReconcileWorkerInput = {
232217
agentId: params.agentId,

‎src/infra/runtime-process-entrypoints.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@ export const runtimeProcessEntrypoints = {
1212
sourceWorkerName: "../state/openclaw-database-verify.worker",
1313
distWorkerPath: "state/openclaw-database-verify.worker.js",
1414
},
15+
sessionTranscriptArchive: {
16+
currentModuleUrl,
17+
sourceWorkerName: "../config/sessions/session-accessor.sqlite-archive.worker",
18+
distWorkerPath: "config/sessions/session-accessor.sqlite-archive.worker.js",
19+
},
20+
sessionTranscriptReconcile: {
21+
currentModuleUrl,
22+
sourceWorkerName: "../config/sessions/session-transcript-reconcile.worker",
23+
distWorkerPath: "config/sessions/session-transcript-reconcile.worker.js",
24+
},
1525
tailscaleRouteOwner: {
1626
currentModuleUrl,
1727
sourceWorkerName: "tailscale-route-owner.worker",

‎test/scripts/vitest-worker-artifacts.test-support.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ export function workerProbe(
225225
import path from 'node:path';
226226
import { fileURLToPath } from 'node:url';
227227
import { DatabaseSync } from 'node:sqlite';
228+
import { Worker } from 'node:worker_threads';
228229
import { it, expect, vi, inject } from 'vitest';
229230
import {value} from '#fixture-value';
230231
import { runtimeProcessEntrypoints } from ${JSON.stringify(path.join(root, "src/infra/runtime-process-entrypoints.ts"))};
@@ -234,18 +235,23 @@ export function workerProbe(
234235
import { tuiPtyRuntimeEntrypoints } from ${JSON.stringify(path.join(root, "src/tui/tui-pty-runtime-test-support.ts"))};
235236
import { resolveRuntimeWorkerUrl } from ${JSON.stringify(path.join(root, "src/infra/runtime-worker-url.ts"))};
236237
import { prepareSqliteReadOnlyLocation } from ${JSON.stringify(path.join(root, "src/infra/sqlite-readonly-location.ts"))};
238+
import { runSqliteTranscriptArchivePublishWorker } from ${JSON.stringify(path.join(root, "src/config/sessions/session-accessor.sqlite-archive.ts"))};
237239
const tuiUrls = Object.values(tuiPtyRuntimeEntrypoints).map(entry => resolveRuntimeWorkerUrl(entry).href);
238240
// Import acquisition must finish during collection, before any fixture hook starts.
239241
const tuiPresentAtCollection = tuiUrls.every(url => fs.existsSync(new URL(url)));
240242
vi.mock('node:child_process', async (original) => {
241243
const actual = await original();
242244
return {...actual, execFile: vi.fn(actual.execFile)};
243245
});
246+
vi.mock('node:worker_threads', async (original) => {
247+
const actual = await original();
248+
return {...actual, Worker: vi.fn(function(...args) { return new actual.Worker(...args); })};
249+
});
244250
it('runs current SQLite code in the expected execution mode', async () => {
245251
const launcherArgv = inject('launcherArgv');
246252
expect(path.isAbsolute(launcherArgv[1])).toBe(true);
247253
expect(path.basename(launcherArgv[1])).toBe('vitest.mjs');
248-
expect(Object.values(runtimeProcessBuildEntries)).toHaveLength(7);
254+
expect(Object.values(runtimeProcessBuildEntries)).toHaveLength(9);
249255
for (const source of Object.values(runtimeProcessBuildEntries)) {
250256
expect(source).not.toContain('/dist/');
251257
expect(source).toMatch(/\\.ts$/);
@@ -272,6 +278,10 @@ export function workerProbe(
272278
const args = cp.execFile.mock.calls[0][1];
273279
const generation = runtimeProcessEntrypoints.sqliteReadOnly.currentModuleUrl;
274280
const sourceMode = ${mode === "auto" ? "generation.endsWith('.ts')" : mode === "source"};
281+
await expect(runSqliteTranscriptArchivePublishWorker([])).resolves.toEqual([]);
282+
const [archiveUrl] = Worker.mock.calls.at(-1);
283+
expect(archiveUrl.href.endsWith(sourceMode ? '.ts' : '.js')).toBe(true);
284+
if (!sourceMode) expect(fileURLToPath(archiveUrl).startsWith(fileURLToPath(new URL('../', generation)))).toBe(true);
275285
expect(tuiUrls).toHaveLength(4);
276286
for (const url of tuiUrls) {
277287
expect(url.endsWith(sourceMode ? '.ts' : '.js')).toBe(true);

‎tsdown.config.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -380,10 +380,6 @@ function buildCoreDistEntries(): Record<string, string> {
380380
"agents/compaction-planning.worker": "src/agents/compaction-planning.worker.ts",
381381
"agents/model-provider-auth.worker": "src/agents/model-provider-auth.worker.ts",
382382
"agents/prepared-model-catalog.worker": "src/agents/prepared-model-catalog.worker.ts",
383-
"config/sessions/session-accessor.sqlite-archive.worker":
384-
"src/config/sessions/session-accessor.sqlite-archive.worker.ts",
385-
"config/sessions/session-transcript-reconcile.worker":
386-
"src/config/sessions/session-transcript-reconcile.worker.ts",
387383
...runtimeProcessBuildEntries,
388384
...runtimeProcessDeclarationEntries,
389385
"system-agent/setup-inference-detection.worker":

0 commit comments

Comments
 (0)