Skip to content

Commit b6b440d

Browse files
authored
perf(gateway): skip clean transcript workers (#117342)
1 parent aa2a5c9 commit b6b440d

2 files changed

Lines changed: 33 additions & 7 deletions

File tree

‎src/config/sessions/session-accessor.sqlite-active-events.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -571,11 +571,12 @@ describe("SQLite active transcript event projection", () => {
571571
}
572572
});
573573

574-
it("awaits queued completion work after the preparation worker exits", async () => {
574+
it("skips the preparation worker when the projection is already current", async () => {
575575
await persistSessionTranscriptTurn(scope, {
576576
messages: [{ eventId: "seed", message: { role: "user", content: "seed" } }],
577577
touchSessionEntry: false,
578578
});
579+
queuedSessionWrite.mockClear();
579580
let resolveCompletionQueued!: () => void;
580581
const completionQueued = new Promise<void>((resolve) => {
581582
resolveCompletionQueued = resolve;
@@ -601,21 +602,26 @@ describe("SQLite active transcript event projection", () => {
601602
},
602603
);
603604
await entered;
605+
const createWorker = vi.fn(() => {
606+
throw new Error("clean projection must not spawn a worker");
607+
});
604608
const outcome = reconcileSessionTranscriptIndexes({
605609
agentId: scope.agentId,
610+
createWorker,
606611
env: scope.env,
607612
}).then(
608613
(value) => ({ value }),
609614
(error: unknown) => ({ error }),
610615
);
611616

612-
// The second queued write is the orphan sweep issued after the worker's done message.
617+
// The second queued write is the preflight transaction waiting behind the held writer.
613618
await completionQueued;
614619
expect(queuedSessionWrite).toHaveBeenCalledTimes(2);
615620
releaseWriter();
616621
await heldWriter;
617622

618623
expect(await outcome).toEqual({ value: { reconciledSessions: 0 } });
624+
expect(createWorker).not.toHaveBeenCalled();
619625
}, 10_000);
620626

621627
it("keeps dirty batch appends off the synchronous writer stack", async () => {

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

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import { randomInt } from "node:crypto";
44
import path from "node:path";
55
import { fileURLToPath, pathToFileURL } from "node:url";
6-
import { Worker } from "node:worker_threads";
6+
import { Worker, type WorkerOptions } from "node:worker_threads";
77
import { createSubsystemLogger } from "../../logging/subsystem.js";
88
import {
99
resolveOpenClawAgentSqlitePath,
@@ -17,7 +17,10 @@ import {
1717
runExclusiveSqliteSessionWrite,
1818
toDatabaseOptions,
1919
} from "./session-accessor.sqlite-scope.js";
20-
import { deleteOrphanedTranscriptIndexRowsInTransaction } from "./session-transcript-index.js";
20+
import {
21+
deleteOrphanedTranscriptIndexRowsInTransaction,
22+
listSessionsNeedingTranscriptIndexReconcile,
23+
} from "./session-transcript-index.js";
2124
import {
2225
appendPreparedSessionTranscriptProjectionChunkInTransaction,
2326
claimPreparedSessionTranscriptProjectionInTransaction,
@@ -47,6 +50,7 @@ export type SessionTranscriptReconcileResult = {
4750
};
4851

4952
type SessionTranscriptReconcileParams = OpenClawAgentDatabaseOptions & {
53+
createWorker?: (filename: string | URL, options: WorkerOptions) => Worker;
5054
preferredSessionId?: string;
5155
};
5256

@@ -198,7 +202,7 @@ async function finalizePreparedProjection(
198202
}
199203

200204
/** Prepares full trees off-thread, then commits bounded chunks through the runtime writer owner. */
201-
export function reconcileSessionTranscriptIndexes(
205+
export async function reconcileSessionTranscriptIndexes(
202206
params: SessionTranscriptReconcileParams,
203207
): Promise<SessionTranscriptReconcileResult> {
204208
const databasePath = resolveOpenClawAgentSqlitePath(params);
@@ -207,6 +211,19 @@ export function reconcileSessionTranscriptIndexes(
207211
...(params.env ? { env: params.env } : {}),
208212
path: databasePath,
209213
};
214+
// The SQLite owner can cheaply prove a clean projection before paying for a
215+
// Worker. Keep the post-worker sweep too, because request-time writers may race.
216+
const needsWorker = await runProjectionWrite(
217+
databaseOptions,
218+
"sessions.transcript-index.preflight",
219+
(database) => {
220+
deleteOrphanedTranscriptIndexRowsInTransaction(database.db);
221+
return listSessionsNeedingTranscriptIndexReconcile(database.db).length > 0;
222+
},
223+
);
224+
if (!needsWorker) {
225+
return { reconciledSessions: 0 };
226+
}
210227
const workerUrl = resolveSessionTranscriptReconcileWorkerUrl();
211228
const sourceWorkerExecArgv = workerUrl.pathname.endsWith(".ts") ? ["--import", "tsx"] : undefined;
212229
const input: SessionTranscriptReconcileWorkerInput = {
@@ -216,9 +233,12 @@ export function reconcileSessionTranscriptIndexes(
216233
};
217234
let worker: Worker;
218235
try {
219-
worker = new Worker(workerUrl, { workerData: input, execArgv: sourceWorkerExecArgv });
236+
worker = (params.createWorker ?? ((filename, options) => new Worker(filename, options)))(
237+
workerUrl,
238+
{ workerData: input, execArgv: sourceWorkerExecArgv },
239+
);
220240
} catch (error) {
221-
return Promise.reject(normalizeReconcileError(error));
241+
throw normalizeReconcileError(error);
222242
}
223243

224244
return new Promise<SessionTranscriptReconcileResult>((resolve, reject) => {

0 commit comments

Comments
 (0)