|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | +import type { DatabaseSync } from "node:sqlite"; |
| 4 | +import { createDeferred } from "openclaw/plugin-sdk/extension-shared"; |
| 5 | +import type { MemorySyncParams } from "openclaw/plugin-sdk/memory-core-host-engine-storage"; |
| 6 | +import { describe, expect, it, vi } from "vitest"; |
| 7 | +import { createManagerIndexFixture } from "./manager-index.test-support.js"; |
| 8 | +import type { MemoryIndexMeta } from "./manager-reindex-state.js"; |
| 9 | + |
| 10 | +const { closeAllMemorySearchManagers, getMemorySearchManager } = await import("./index.js"); |
| 11 | + |
| 12 | +describe("automatic candidates during provenance repair", () => { |
| 13 | + const fixture = createManagerIndexFixture({ |
| 14 | + getMemorySearchManager, |
| 15 | + closeAllMemorySearchManagers, |
| 16 | + }); |
| 17 | + |
| 18 | + it.each([false, true])( |
| 19 | + "returns promptly while a large rebuild is pending (startup catch-up: %s)", |
| 20 | + async (startupCatchup) => { |
| 21 | + const projectKey = "github.com/example/project"; |
| 22 | + await fs.writeFile( |
| 23 | + path.join(fixture.paths.workspace, "MEMORY.md"), |
| 24 | + `- Keep the release local. <!-- trigger: release local --> <!-- project: ${projectKey} -->\n`, |
| 25 | + ); |
| 26 | + await Promise.all( |
| 27 | + Array.from({ length: 256 }, (_, index) => |
| 28 | + fs.writeFile( |
| 29 | + path.join(fixture.paths.memory, `entry-${index}.md`), |
| 30 | + `# Entry ${index}\nSynthetic memory content ${index}.\n`, |
| 31 | + ), |
| 32 | + ), |
| 33 | + ); |
| 34 | + const cfg = fixture.createConfig({ |
| 35 | + provider: "batch-wide-test", |
| 36 | + batchEnabled: true, |
| 37 | + vectorEnabled: false, |
| 38 | + sources: startupCatchup ? ["memory", "sessions"] : ["memory"], |
| 39 | + sessionMemory: startupCatchup, |
| 40 | + }); |
| 41 | + if (startupCatchup) { |
| 42 | + await fixture.seedSessionTranscript({ |
| 43 | + sessionId: "legacy-session", |
| 44 | + messages: [{ role: "user", timestamp: 1, content: "Remember the release preference." }], |
| 45 | + }); |
| 46 | + } |
| 47 | + const initial = await fixture.getFreshManager(cfg, "cli"); |
| 48 | + await initial.sync({ reason: "cli", force: true }); |
| 49 | + const db = Reflect.get(initial, "db") as DatabaseSync; |
| 50 | + // Older indexes have neither classified provenance nor a chunking version. |
| 51 | + db.exec("DELETE FROM memory_index_chunk_provenance; DELETE FROM memory_embedding_cache"); |
| 52 | + const row = db |
| 53 | + .prepare("SELECT value FROM memory_index_meta WHERE key = 'memory_index_meta_v1'") |
| 54 | + .get() as { value: string }; |
| 55 | + const meta = JSON.parse(row.value) as MemoryIndexMeta; |
| 56 | + delete meta.provenanceVersion; |
| 57 | + delete meta.chunkingVersion; |
| 58 | + db.prepare("UPDATE memory_index_meta SET value = ? WHERE key = 'memory_index_meta_v1'").run( |
| 59 | + JSON.stringify(meta), |
| 60 | + ); |
| 61 | + await initial.close(); |
| 62 | + |
| 63 | + const gate = createDeferred<void>(); |
| 64 | + fixture.provider.providerRuntimeBatchGate = gate.promise; |
| 65 | + const upgraded = await fixture.getFreshManager(cfg); |
| 66 | + const candidates: Promise<unknown>[] = []; |
| 67 | + try { |
| 68 | + expect(upgraded.status().custom?.indexIdentity).toMatchObject({ |
| 69 | + status: "mismatched", |
| 70 | + reason: "index provenance classifier changed", |
| 71 | + }); |
| 72 | + if (startupCatchup) { |
| 73 | + await vi.waitFor(() => expect(fixture.provider.providerRuntimeActiveBatchCalls).toBe(1), { |
| 74 | + timeout: 10_000, |
| 75 | + }); |
| 76 | + } |
| 77 | + let completed = 0; |
| 78 | + for (const lookup of [ |
| 79 | + () => upgraded.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }), |
| 80 | + () => upgraded.listTriggerCandidates({ activeProjectKeys: [projectKey] }), |
| 81 | + ]) { |
| 82 | + candidates.push( |
| 83 | + lookup().then((results) => { |
| 84 | + completed += 1; |
| 85 | + return results; |
| 86 | + }), |
| 87 | + ); |
| 88 | + } |
| 89 | + await vi.waitFor(() => expect(completed).toBe(2)); |
| 90 | + expect(await Promise.all(candidates)).toEqual([[], []]); |
| 91 | + await vi.waitFor(() => expect(fixture.provider.providerRuntimeActiveBatchCalls).toBe(1), { |
| 92 | + timeout: 10_000, |
| 93 | + }); |
| 94 | + expect(upgraded.status().dirty).toBe(true); |
| 95 | + } finally { |
| 96 | + gate.resolve(); |
| 97 | + await Promise.allSettled(candidates); |
| 98 | + } |
| 99 | + await upgraded.sync({ reason: "test-repair-complete" }); |
| 100 | + expect(upgraded.status().dirty).toBe(false); |
| 101 | + const expected = [ |
| 102 | + expect.objectContaining({ |
| 103 | + projectKey, |
| 104 | + triggers: "release local", |
| 105 | + provenance: expect.objectContaining({ originClass: "agent" }), |
| 106 | + }), |
| 107 | + ]; |
| 108 | + expect( |
| 109 | + await upgraded.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }), |
| 110 | + ).toEqual(expected); |
| 111 | + expect(await upgraded.listTriggerCandidates({ activeProjectKeys: [projectKey] })).toEqual( |
| 112 | + expected, |
| 113 | + ); |
| 114 | + }, |
| 115 | + ); |
| 116 | + |
| 117 | + it("drains admitted candidate repair retries before closing the database", async () => { |
| 118 | + const projectKey = "github.com/example/project"; |
| 119 | + await fs.writeFile( |
| 120 | + path.join(fixture.paths.workspace, "MEMORY.md"), |
| 121 | + `- Preserve the release preference. <!-- trigger: release local --> <!-- project: ${projectKey} -->\n`, |
| 122 | + ); |
| 123 | + const ftsConfig = fixture.createConfig({ provider: "none", vectorEnabled: false }); |
| 124 | + const initial = await fixture.getFreshManager(ftsConfig, "cli"); |
| 125 | + await initial.sync({ reason: "cli", force: true }); |
| 126 | + // The existing migration will invalidate these sources on the next open. |
| 127 | + const initialDb = Reflect.get(initial, "db") as DatabaseSync; |
| 128 | + initialDb.exec("DELETE FROM memory_index_chunk_provenance"); |
| 129 | + await initial.close(); |
| 130 | + |
| 131 | + const initialization = createDeferred<void>(); |
| 132 | + const retryStarted = createDeferred<void>(); |
| 133 | + const retry = createDeferred<void>(); |
| 134 | + fixture.provider.providerInitGate = initialization.promise; |
| 135 | + fixture.provider.providerCreationFailure = "local"; |
| 136 | + const upgraded = await fixture.getFreshManager( |
| 137 | + fixture.createConfig({ provider: "local", vectorEnabled: false }), |
| 138 | + "cli", |
| 139 | + ); |
| 140 | + const owner = upgraded as unknown as { |
| 141 | + runSync: (params?: MemorySyncParams) => Promise<void>; |
| 142 | + }; |
| 143 | + const runSync = owner.runSync.bind(upgraded); |
| 144 | + let pendingRetry: Promise<void> | undefined; |
| 145 | + const retryGate = vi.spyOn(owner, "runSync").mockImplementation((params) => { |
| 146 | + retryStarted.resolve(); |
| 147 | + pendingRetry = retry.promise.then(() => runSync(params)); |
| 148 | + return pendingRetry; |
| 149 | + }); |
| 150 | + // This is the same public sync admission used by detached startup catch-up. |
| 151 | + // Attach rejection handling immediately; its failed initialization is expected. |
| 152 | + const startup = upgraded.sync({ reason: "session-startup-catchup" }); |
| 153 | + const startupOutcome = startup.then( |
| 154 | + () => undefined, |
| 155 | + (error: unknown) => error, |
| 156 | + ); |
| 157 | + let closing: Promise<void> | undefined; |
| 158 | + let closeSettled = false; |
| 159 | + try { |
| 160 | + await vi.waitFor(() => expect(fixture.provider.providerCalls.at(-1)?.provider).toBe("local")); |
| 161 | + await expect( |
| 162 | + upgraded.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }), |
| 163 | + ).resolves.toEqual([]); |
| 164 | + closing = upgraded.close().then(() => { |
| 165 | + closeSettled = true; |
| 166 | + }); |
| 167 | + // Let close enter its drain before the already-running sync fails. This |
| 168 | + // reproduces the original execution order without a timing-based sleep. |
| 169 | + await Promise.resolve(); |
| 170 | + initialization.resolve(); |
| 171 | + await retryStarted.promise; |
| 172 | + // Give teardown a turn to finish while the admitted retry remains gated. |
| 173 | + await new Promise<void>((resolve) => { |
| 174 | + setImmediate(resolve); |
| 175 | + }); |
| 176 | + expect(closeSettled).toBe(false); |
| 177 | + retry.resolve(); |
| 178 | + await closing; |
| 179 | + expect(await startupOutcome).toBeInstanceOf(Error); |
| 180 | + |
| 181 | + // Observable persistence proof: close did not merely cancel or abandon |
| 182 | + // the retry; its classified candidates survive a fresh manager open. |
| 183 | + const reopened = await fixture.getFreshManager(ftsConfig, "cli"); |
| 184 | + expect( |
| 185 | + await reopened.listCuratedProjectCandidates({ activeProjectKeys: [projectKey] }), |
| 186 | + ).toEqual([ |
| 187 | + expect.objectContaining({ |
| 188 | + projectKey, |
| 189 | + triggers: "release local", |
| 190 | + provenance: expect.objectContaining({ originClass: "agent" }), |
| 191 | + }), |
| 192 | + ]); |
| 193 | + } finally { |
| 194 | + initialization.resolve(); |
| 195 | + retry.resolve(); |
| 196 | + await startupOutcome; |
| 197 | + await pendingRetry?.catch(() => undefined); |
| 198 | + await closing; |
| 199 | + await upgraded.close(); |
| 200 | + retryGate.mockRestore(); |
| 201 | + } |
| 202 | + }); |
| 203 | +}); |
0 commit comments