Skip to content

Commit 233ac85

Browse files
authored
perf(sessions): defer transcript index rebuilds to the reconcile worker (#129182)
* perf(sessions): defer transcript index rebuilds to the reconcile worker Transcript replace, exact rewrite, text repair, and message-cut no longer rebuild the full FTS/active-event projection inside their synchronous write transactions. They mark the projection dirty and schedule the existing chunked worker-owned reconcile after commit via the post-commit publication seam; search already hides needs_rebuild sessions and mirror-facts falls back to raw rows while the projection lags. Doctor import and canonical repair keep synchronous reconciliation. A/B probe: compaction replace of a 60k-event transcript blocked the event loop 3197ms before, 764ms after, with the projection converging off-thread. * test(sessions): await projection convergence before proving turn cursors Replace now defers the projection rebuild, so the ordered-turn setup must wait for the reconcile worker before committed cursors are provable; the invalidation fallback for unproven cursors keeps its own coverage. * perf(sessions): size-gate synchronous transcript index rebuilds Small transcripts (<=4k events and <=4MiB) keep the original synchronous in-transaction rebuild (~250ms bound, no reader dirty window); only large transcripts defer to the reconcile worker where the FTS retokenization cost would stall the event loop. Probe: 60k-event replace stalls 639ms (deferred) vs 3197ms before; 2k-event replace is 95ms with search current immediately. * test(sessions): settle deferred reconcile before teardown and history reads Oversized chat.history fixtures take the deferred rebuild path, so the shared transcript seeding helper awaits projection convergence, and the archive-worker suite settles the reconcile worker before removing its temp dir (Windows cannot unlink the still-open agent DB). * fix(test): satisfy agent database options in archive-worker teardown * fix(sessions): resolve reconcile only after the worker thread exits The reconcile promise previously settled via fire-and-forget terminate, letting waiters delete the database file while the worker thread still held its SQLite handle open (Windows unlink fails with EBUSY). Settle now finishes through worker.terminate()'s exit promise on every path.
1 parent c692865 commit 233ac85

14 files changed

Lines changed: 244 additions & 47 deletions

‎src/commands/doctor-session-transcript-headers.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
upsertSessionEntryCore,
88
} from "../config/sessions/session-accessor.js";
99
import { readTranscriptStorageRows } from "../config/sessions/session-accessor.sqlite-read.js";
10+
import { waitForSessionTranscriptIndexReconcile } from "../config/sessions/session-transcript-reconcile.js";
1011
import { CURRENT_SESSION_VERSION } from "../config/sessions/version.js";
1112
import type { OpenClawConfig } from "../config/types.openclaw.js";
1213
import {
@@ -61,6 +62,7 @@ describe("doctor SQLite session transcript header repair", () => {
6162
});
6263

6364
afterEach(async () => {
65+
await waitForSessionTranscriptIndexReconcile({ agentId: AGENT_ID, env: state.env });
6466
closeOpenClawAgentDatabasesForTest();
6567
closeOpenClawStateDatabaseForTest();
6668
await state.cleanup();
@@ -168,6 +170,7 @@ describe("doctor SQLite session transcript header repair", () => {
168170
{ event_id: "user-1", parent_id: "model-1", seq: 2 },
169171
{ event_id: "leaf-1", parent_id: "user-1", seq: 3 },
170172
]);
173+
await waitForSessionTranscriptIndexReconcile(databaseOptions);
171174
expect(
172175
database.db
173176
.prepare(

‎src/commands/doctor-session-transcript-labels.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "../config/sessions/session-accessor.sqlite-read.js";
1313
import { appendTranscriptEventsInTransaction } from "../config/sessions/session-accessor.sqlite-transcript-store.js";
1414
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
15+
import { waitForSessionTranscriptIndexReconcile } from "../config/sessions/session-transcript-reconcile.js";
1516
import type { OpenClawConfig } from "../config/types.openclaw.js";
1617
import {
1718
closeOpenClawAgentDatabasesForTest,
@@ -211,6 +212,7 @@ describe("doctor SQLite session transcript label migration", () => {
211212
});
212213

213214
afterEach(async () => {
215+
await waitForSessionTranscriptIndexReconcile({ agentId: AGENT_ID, env: state.env });
214216
closeOpenClawAgentDatabasesForTest();
215217
closeOpenClawStateDatabaseForTest();
216218
await state.cleanup();
@@ -536,8 +538,9 @@ describe("doctor SQLite session transcript label migration", () => {
536538
);
537539

538540
await runTranscriptLabelHealth(state, true);
541+
await waitForSessionTranscriptIndexReconcile(databaseOptions);
539542

540-
// The rebuild (delete+reconcile) must re-derive the FTS timestamp from the row's own created_at,
543+
// The deferred rebuild must re-derive the FTS timestamp from the row's own created_at,
541544
// NOT stamp Date.now(); otherwise every timestamp-less event's search recency resets on repair.
542545
expect(readFtsTimestamp()).toBe(OLD_CREATED_AT);
543546
});

‎src/commands/doctor-session-transcript-labels.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,12 +226,14 @@ export async function noteSessionTranscriptLabelHealth(params: {
226226
// Build per-row change list keyed by seq. Parse each row individually so unparseable
227227
// rows (with corrupted eventJson) don't break the whole session.
228228
const updates: Array<{ seq: number; eventJson: string }> = [];
229+
let hasMalformedRow = false;
229230
for (const row of readResult.rows) {
230231
let event: TranscriptEvent;
231232
try {
232233
event = JSON.parse(row.eventJson) as TranscriptEvent;
233234
} catch {
234-
// Skip rows with unparseable eventJson (corrupted data).
235+
// A malformed sibling cannot produce a valid deferred projection after repair.
236+
hasMalformedRow = true;
235237
continue;
236238
}
237239
if (normalizeLegacyInboundContextLabels(event)) {
@@ -249,6 +251,9 @@ export async function noteSessionTranscriptLabelHealth(params: {
249251
// REPAIR PHASE (if --fix): process immediately, don't buffer.
250252
if (params.shouldRepair) {
251253
try {
254+
if (hasMalformedRow) {
255+
throw new Error(`transcript contains malformed event JSON for ${sessionId}`);
256+
}
252257
runOpenClawAgentWriteTransaction(
253258
(writeDatabase) => {
254259
// Use rows-only guard (tolerant of malformed JSON in sibling rows).

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ import {
3030
import { touchTranscriptMutationInTransaction } from "./session-accessor.sqlite-transcript-state.js";
3131
import { replaceTranscriptEvents } from "./session-accessor.sqlite-transcript-write.js";
3232
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
33+
import {
34+
waitForSessionTranscriptIndexReconcile,
35+
waitForSessionTranscriptProjection,
36+
} from "./session-transcript-reconcile.js";
3337

3438
type TestTranscriptEvent = {
3539
id: string;
@@ -45,7 +49,13 @@ describe("SQLite transcript archive worker", () => {
4549
storePath = path.join(tempDir, "agents", "main", "sessions", "sessions.json");
4650
});
4751

48-
afterEach(() => {
52+
afterEach(async () => {
53+
// A deferred projection reconcile worker may still hold the agent DB open;
54+
// Windows cannot unlink open files, so settle it before removing tempDir.
55+
await waitForSessionTranscriptIndexReconcile({
56+
agentId: "main",
57+
path: resolveSqliteTargetFromSessionStorePath(storePath).path,
58+
});
4959
closeOpenClawAgentDatabasesForTest();
5060
fs.rmSync(tempDir, { recursive: true, force: true });
5161
});
@@ -426,6 +436,7 @@ describe("SQLite transcript archive worker", () => {
426436
db.selectFrom("session_windows").select("session_id").where("session_id", "=", sessionId),
427437
).rows.length,
428438
});
439+
await waitForSessionTranscriptProjection(scope);
429440
const before = readLifecycleCounts();
430441

431442
await expect(

‎src/config/sessions/session-accessor.sqlite-canonical-repair.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ function copySqliteSessionOwnedStateForRepair(params: {
469469
if (!replaced) {
470470
continue;
471471
}
472-
// Search and active-event tables are derived from transcript_events; force their canonical rebuild.
472+
// Doctor repair runs outside gateway requests and must atomically finish copied projections.
473473
deleteSessionTranscriptIndexInTransaction(params.destination.db, sessionId);
474474
reconcileSessionTranscriptIndexInTransaction(params.destination.db, sessionId);
475475
publishSessionEntryCacheInvalidation(params.destination);

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ function importSqliteSessionRowsInTransaction(
152152
);
153153
}
154154
transcriptEvents = exactTranscriptRows.length;
155+
// Doctor imports run outside gateway requests and must finish with a complete projection.
155156
reconcileSessionTranscriptIndexInTransaction(database.db, params.entry.sessionId);
156157
publishSessionEntryCacheInvalidation(database);
157158
}
@@ -180,6 +181,7 @@ function importSqliteSessionRowsInTransaction(
180181
transcriptEvents += 1;
181182
}
182183
}
184+
// Doctor imports run outside gateway requests and must finish with a complete projection.
183185
reconcileSessionTranscriptIndexInTransaction(database.db, params.entry.sessionId);
184186
publishSessionEntryCacheInvalidation(database);
185187
}

‎src/config/sessions/session-accessor.sqlite-message-cut.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ import {
2424
updateSessionEntry,
2525
upsertSessionEntryCore,
2626
} from "./session-accessor.js";
27+
import { SYNC_REBUILD_MAX_BYTES } from "./session-transcript-index.js";
28+
import { waitForSessionTranscriptProjection } from "./session-transcript-reconcile.js";
2729
import type { InternalSessionEntry } from "./types.js";
2830

2931
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
@@ -507,6 +509,31 @@ describe("SQLite session message cuts", () => {
507509
});
508510
});
509511

512+
it("defers an oversized rewind projection until the reconcile worker finishes", async () => {
513+
const { env, scope } = await createSession();
514+
await appendTranscriptEvent(scope, {
515+
type: "oversized-padding",
516+
padding: "x".repeat(SYNC_REBUILD_MAX_BYTES),
517+
});
518+
519+
const result = await rewindSessionToMessage({
520+
agentId,
521+
env,
522+
entryId: "user-2",
523+
sessionKey,
524+
});
525+
if (result.status !== "created") {
526+
throw new Error("expected oversized rewind result");
527+
}
528+
const targetScope = { agentId, env, sessionId: result.entry.sessionId, sessionKey };
529+
expect(() => readSessionTranscriptMessageEvents(targetScope)).toThrow(
530+
/projection is rebuilding/,
531+
);
532+
533+
await waitForSessionTranscriptProjection(targetScope);
534+
expect(readSessionTranscriptMessageEvents(targetScope)).toHaveLength(2);
535+
});
536+
510537
it("omits editor attachments for a text-only message", async () => {
511538
const { env } = await createSession();
512539

‎src/config/sessions/session-accessor.sqlite-message-cut.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import {
2626
toDatabaseOptions,
2727
type ResolvedSqliteScope,
2828
} from "./session-accessor.sqlite-scope.js";
29+
import { ensureTranscriptSessionRoot } from "./session-accessor.sqlite-transcript-state.js";
2930
import { appendTranscriptEventsInTransaction } from "./session-accessor.sqlite-transcript-store.js";
3031
import type {
3132
SessionBranchListParams,
@@ -38,7 +39,12 @@ import type {
3839
} from "./session-accessor.types.js";
3940
import { buildSessionCreationStamp } from "./session-entry-provenance.js";
4041
import { inheritSessionSelection } from "./session-entry-selection.js";
41-
import { reconcileSessionTranscriptIndexInTransaction } from "./session-transcript-index.js";
42+
import {
43+
markSessionTranscriptIndexDirtyInTransaction,
44+
reconcileSessionTranscriptIndexInTransaction,
45+
SYNC_REBUILD_MAX_BYTES,
46+
SYNC_REBUILD_MAX_ROWS,
47+
} from "./session-transcript-index.js";
4248
import { createSessionTranscriptHeader } from "./transcript-header.js";
4349
import {
4450
isSessionTranscriptLeafControl,
@@ -325,8 +331,20 @@ function mutateSqliteSessionAtMessageInTransaction(
325331
targetId: params.mode === "switch" ? params.entryId : (cut?.parentId ?? null),
326332
},
327333
];
334+
let copiedBytes = 0;
335+
const rebuildSynchronously =
336+
params.mode !== "fork" &&
337+
nextEvents.length <= SYNC_REBUILD_MAX_ROWS &&
338+
nextEvents.every((event) => {
339+
copiedBytes += JSON.stringify(event).length;
340+
return copiedBytes <= SYNC_REBUILD_MAX_BYTES;
341+
});
342+
if (params.mode !== "fork" && !rebuildSynchronously) {
343+
ensureTranscriptSessionRoot(database, targetScope, Date.parse(header.timestamp));
344+
markSessionTranscriptIndexDirtyInTransaction(database.db, nextSessionId);
345+
}
328346
appendTranscriptEventsInTransaction(database, targetScope, nextEvents);
329-
if (params.mode !== "fork") {
347+
if (rebuildSynchronously) {
330348
reconcileSessionTranscriptIndexInTransaction(database.db, nextSessionId);
331349
}
332350

‎src/config/sessions/session-accessor.sqlite-transcript-state.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import {
1414
assertCanonicalSessionKeyWriteMatchesDatabase,
1515
canonicalSessionKeyMigrationRequiredError,
1616
} from "./session-canonical-key.js";
17-
import { deleteSessionTranscriptIndexInTransaction } from "./session-transcript-index.js";
1817
import {
1918
foldedSessionKeyAliasCandidates,
2019
normalizeStoreSessionKey,
@@ -290,7 +289,5 @@ export function deleteTranscriptEventsInTransaction(
290289
database.db,
291290
db.deleteFrom("transcript_events").where("session_id", "=", sessionId),
292291
);
293-
// FTS rows have no FK onto transcript_events; clear them in this transaction.
294-
deleteSessionTranscriptIndexInTransaction(database.db, sessionId);
295292
return (result.numAffectedRows ?? 0n) > 0n;
296293
}

0 commit comments

Comments
 (0)