|
| 1 | +import { setTimeout as delay } from "node:timers/promises"; |
| 2 | +import { Worker, type WorkerOptions } from "node:worker_threads"; |
| 3 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 4 | +import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js"; |
| 5 | +import { |
| 6 | + closeOpenClawAgentDatabasesForTest, |
| 7 | + openOpenClawAgentDatabase, |
| 8 | +} from "../../state/openclaw-agent-db.js"; |
| 9 | +import { |
| 10 | + closeOpenClawStateDatabaseForTest, |
| 11 | + openOpenClawStateDatabase, |
| 12 | +} from "../../state/openclaw-state-db.js"; |
| 13 | +import { withEnvAsync } from "../../test-utils/env.js"; |
| 14 | +import { persistSessionTranscriptTurn } from "./session-accessor.js"; |
| 15 | +import { |
| 16 | + reconcileSessionTranscriptIndexes, |
| 17 | + waitForSessionTranscriptIndexReconcile, |
| 18 | +} from "./session-transcript-reconcile.js"; |
| 19 | +import type { SessionTranscriptReconcileWorkerMessage } from "./session-transcript-reconcile.worker.js"; |
| 20 | + |
| 21 | +const tempDirs = useAutoCleanupTempDirTracker(afterEach); |
| 22 | + |
| 23 | +type TerminalType = Extract< |
| 24 | + SessionTranscriptReconcileWorkerMessage, |
| 25 | + { type: "done" | "failed" } |
| 26 | +>["type"]; |
| 27 | + |
| 28 | +function countAgentDatabaseLeases(pathname: string): number { |
| 29 | + // SAFETY: SQLite COUNT(*) always returns one row with the numeric alias requested here. |
| 30 | + const row = openOpenClawStateDatabase() |
| 31 | + .db.prepare( |
| 32 | + `SELECT COUNT(*) AS count |
| 33 | + FROM agent_database_leases |
| 34 | + WHERE owner_pid = ? AND path = ?`, |
| 35 | + ) |
| 36 | + .get(process.pid, pathname) as { count: number }; |
| 37 | + return row.count; |
| 38 | +} |
| 39 | + |
| 40 | +function createCleanupFenceProbe() { |
| 41 | + const stateDatabase = openOpenClawStateDatabase(); |
| 42 | + let lockHeld = false; |
| 43 | + let resolvePlanStarted!: () => void; |
| 44 | + let resolveTerminal!: (type: TerminalType) => void; |
| 45 | + const planStarted = new Promise<void>((resolve) => { |
| 46 | + resolvePlanStarted = resolve; |
| 47 | + }); |
| 48 | + const terminal = new Promise<TerminalType>((resolve) => { |
| 49 | + resolveTerminal = resolve; |
| 50 | + }); |
| 51 | + const createWorker = (filename: string | URL, options: WorkerOptions): Worker => { |
| 52 | + const worker = new Worker(filename, options); |
| 53 | + // This listener is registered before the reconciler's listener. Holding |
| 54 | + // the state writer after plan-start fences the worker's lease release. |
| 55 | + worker.on("message", (message: SessionTranscriptReconcileWorkerMessage) => { |
| 56 | + if (message.type === "plan-start" && !lockHeld) { |
| 57 | + stateDatabase.db.exec("BEGIN IMMEDIATE;"); |
| 58 | + lockHeld = true; |
| 59 | + resolvePlanStarted(); |
| 60 | + } |
| 61 | + if (message.type === "done" || message.type === "failed") { |
| 62 | + resolveTerminal(message.type); |
| 63 | + } |
| 64 | + }); |
| 65 | + return worker; |
| 66 | + }; |
| 67 | + |
| 68 | + return { |
| 69 | + createWorker, |
| 70 | + planStarted, |
| 71 | + release(): void { |
| 72 | + if (!lockHeld) { |
| 73 | + return; |
| 74 | + } |
| 75 | + stateDatabase.db.exec("ROLLBACK;"); |
| 76 | + lockHeld = false; |
| 77 | + }, |
| 78 | + terminal, |
| 79 | + }; |
| 80 | +} |
| 81 | + |
| 82 | +async function waitForCurrentProjection(databasePath: string, sessionId: string): Promise<void> { |
| 83 | + const database = openOpenClawAgentDatabase({ agentId: "main", path: databasePath }); |
| 84 | + await vi.waitFor( |
| 85 | + () => { |
| 86 | + expect( |
| 87 | + database.db |
| 88 | + .prepare("SELECT needs_rebuild FROM session_transcript_index_state WHERE session_id = ?") |
| 89 | + .get(sessionId), |
| 90 | + ).toEqual({ needs_rebuild: 0 }); |
| 91 | + }, |
| 92 | + { interval: 10, timeout: 5_000 }, |
| 93 | + ); |
| 94 | +} |
| 95 | + |
| 96 | +describe("session transcript reconcile worker lifecycle", () => { |
| 97 | + it.each([ |
| 98 | + { expectedTerminal: "done" as const, failAfterFirstPlan: false }, |
| 99 | + { expectedTerminal: "failed" as const, failAfterFirstPlan: true }, |
| 100 | + ])( |
| 101 | + "releases its database before reporting $expectedTerminal", |
| 102 | + async ({ expectedTerminal, failAfterFirstPlan }) => { |
| 103 | + const stateDir = tempDirs.make("openclaw-transcript-worker-cleanup-"); |
| 104 | + await withEnvAsync({ OPENCLAW_STATE_DIR: stateDir }, async () => { |
| 105 | + const primarySessionId = "cleanup-primary"; |
| 106 | + const primaryScope = { |
| 107 | + agentId: "main", |
| 108 | + sessionId: primarySessionId, |
| 109 | + sessionKey: "agent:main:cleanup-primary", |
| 110 | + }; |
| 111 | + try { |
| 112 | + await persistSessionTranscriptTurn(primaryScope, { |
| 113 | + messages: [ |
| 114 | + { |
| 115 | + eventId: "primary-message", |
| 116 | + message: { role: "user", content: "primary" }, |
| 117 | + }, |
| 118 | + ], |
| 119 | + touchSessionEntry: false, |
| 120 | + }); |
| 121 | + if (failAfterFirstPlan) { |
| 122 | + await persistSessionTranscriptTurn( |
| 123 | + { |
| 124 | + agentId: "main", |
| 125 | + sessionId: "cleanup-malformed", |
| 126 | + sessionKey: "agent:main:cleanup-malformed", |
| 127 | + }, |
| 128 | + { |
| 129 | + messages: [ |
| 130 | + { |
| 131 | + eventId: "malformed-message", |
| 132 | + message: { role: "user", content: "malformed" }, |
| 133 | + }, |
| 134 | + ], |
| 135 | + touchSessionEntry: false, |
| 136 | + }, |
| 137 | + ); |
| 138 | + } |
| 139 | + await waitForSessionTranscriptIndexReconcile({ agentId: "main" }); |
| 140 | + |
| 141 | + const database = openOpenClawAgentDatabase({ agentId: "main" }); |
| 142 | + const databasePath = database.path; |
| 143 | + database.db |
| 144 | + .prepare( |
| 145 | + "UPDATE session_transcript_index_state SET needs_rebuild = 1 WHERE session_id = ?", |
| 146 | + ) |
| 147 | + .run(primarySessionId); |
| 148 | + if (failAfterFirstPlan) { |
| 149 | + database.db |
| 150 | + .prepare( |
| 151 | + "UPDATE session_transcript_index_state SET needs_rebuild = 1 WHERE session_id = ?", |
| 152 | + ) |
| 153 | + .run("cleanup-malformed"); |
| 154 | + database.db |
| 155 | + .prepare( |
| 156 | + "UPDATE transcript_events SET event_json = '{' WHERE session_id = ? AND seq = 1", |
| 157 | + ) |
| 158 | + .run("cleanup-malformed"); |
| 159 | + } |
| 160 | + |
| 161 | + const baselineLeaseCount = countAgentDatabaseLeases(databasePath); |
| 162 | + expect(baselineLeaseCount).toBe(1); |
| 163 | + const probe = createCleanupFenceProbe(); |
| 164 | + const outcome = reconcileSessionTranscriptIndexes({ |
| 165 | + agentId: "main", |
| 166 | + createWorker: probe.createWorker, |
| 167 | + preferredSessionId: primarySessionId, |
| 168 | + }).then( |
| 169 | + (value) => ({ status: "fulfilled" as const, value }), |
| 170 | + (error: unknown) => ({ status: "rejected" as const, error }), |
| 171 | + ); |
| 172 | + |
| 173 | + let terminalWhileCleanupWasFenced: TerminalType | undefined; |
| 174 | + try { |
| 175 | + await probe.planStarted; |
| 176 | + expect(countAgentDatabaseLeases(databasePath)).toBe(baselineLeaseCount + 1); |
| 177 | + await waitForCurrentProjection(databasePath, primarySessionId); |
| 178 | + terminalWhileCleanupWasFenced = await Promise.race([ |
| 179 | + probe.terminal, |
| 180 | + delay(1_000).then(() => undefined), |
| 181 | + ]); |
| 182 | + } finally { |
| 183 | + probe.release(); |
| 184 | + } |
| 185 | + |
| 186 | + const result = await outcome; |
| 187 | + expect(terminalWhileCleanupWasFenced).toBeUndefined(); |
| 188 | + await expect(probe.terminal).resolves.toBe(expectedTerminal); |
| 189 | + expect(countAgentDatabaseLeases(databasePath)).toBe(baselineLeaseCount); |
| 190 | + if (expectedTerminal === "done") { |
| 191 | + expect(result).toEqual({ |
| 192 | + status: "fulfilled", |
| 193 | + value: { reconciledSessions: 1 }, |
| 194 | + }); |
| 195 | + } else { |
| 196 | + expect(result.status).toBe("rejected"); |
| 197 | + } |
| 198 | + } finally { |
| 199 | + closeOpenClawAgentDatabasesForTest(); |
| 200 | + closeOpenClawStateDatabaseForTest(); |
| 201 | + } |
| 202 | + }); |
| 203 | + }, |
| 204 | + 20_000, |
| 205 | + ); |
| 206 | +}); |
0 commit comments