Skip to content

Commit f4768cf

Browse files
authored
fix(turso): stop dispose closeAll from racing sibling idle handlers (#447)
Reference-count plugin instances so only the last dispose closes the shared Turso pool, and revalidate cached DB handles like SkillsManager (#443).
1 parent 3bac015 commit f4768cf

10 files changed

Lines changed: 222 additions & 14 deletions

File tree

‎src/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { userPromptManager } from "./services/user-prompt/user-prompt-manager.js
1313
import { startWebServer, WebServer } from "./services/web-server.js";
1414
import { ensureTursoReady } from "./services/turso/ready.js";
1515
import { tursoConnectionManager } from "./services/turso/connection-manager.js";
16+
import { retainPluginTurso } from "./services/turso/plugin-refs.js";
1617
import { WebAuth } from "./services/web-auth.js";
1718

1819
import { isConfigured, CONFIG, initConfig } from "./config.js";
@@ -375,6 +376,10 @@ export const OpenCodeMemPlugin: Plugin = async (ctx: PluginInput) => {
375376
const pluginLifetime = new AbortController();
376377
let cleanedUp = false;
377378

379+
// Lease the shared Turso pool for this plugin instance. Several OpenCode
380+
// sessions share one process; dispose must not closeAll while siblings live (#443).
381+
retainPluginTurso();
382+
378383
const GLOBAL_PLUGIN_WARMUP_KEY = Symbol.for("opencode-mem.plugin.warmedup");
379384

380385
if (!(globalThis as any)[GLOBAL_PLUGIN_WARMUP_KEY] && isConfigured()) {

‎src/services/ai/session/ai-session-manager.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,16 @@ export class AISessionManager {
5252
}
5353

5454
private async ready(): Promise<TursoDb> {
55-
if (!this.db || !this.initPromise) {
55+
await this.initialize();
56+
// Connection manager is authoritative: another plugin instance's dispose
57+
// may close/replace the pooled handle underneath a cached TursoDb (#443).
58+
if (this.db) {
59+
const current = await tursoConnectionManager.getConnection(this.dbPath);
60+
if (current === this.db) {
61+
return this.db;
62+
}
63+
this.reset();
5664
await this.initialize();
57-
} else {
58-
await this.initPromise;
5965
}
6066

6167
if (!this.db) {

‎src/services/auto-capture.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ export async function performAutoCapture(
5858

5959
/**
6060
* Wait until every capture job that has already been enqueued finishes.
61-
* Used by plugin dispose so `memoryClient.close()` does not race an
62-
* in-flight capture that was intentionally left uncancellable.
61+
* Used by plugin dispose so the last `memoryClient.close()` (refcount → 0)
62+
* does not race an in-flight capture that was intentionally left uncancellable.
6363
*/
6464
export function awaitCaptureDrain(): Promise<void> {
6565
return captureChain;

‎src/services/client.ts‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -105,9 +105,14 @@ export class LocalMemoryClient {
105105
}
106106

107107
async close(): Promise<void> {
108-
const { closeTursoAndInvalidateCaches } = await import("./turso/lifecycle.js");
109-
await closeTursoAndInvalidateCaches();
110-
this.reset();
108+
// Release one plugin-instance lease. Only the last live instance closes the
109+
// process-wide Turso pool — otherwise a disposing session races sibling
110+
// idle handlers with "database connection is not open" (#443).
111+
const { releasePluginTurso } = await import("./turso/lifecycle.js");
112+
const closed = await releasePluginTurso();
113+
if (closed) {
114+
this.reset();
115+
}
111116
}
112117

113118
async searchMemories(query: string, containerTag: string, scope: MemoryScope = "project") {

‎src/services/turso/lifecycle.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,28 @@ import { userPromptManager } from "../user-prompt/user-prompt-manager.js";
55
import { userProfileManager } from "../user-profile/user-profile-manager.js";
66
import { aiSessionManager } from "../ai/session/ai-session-manager.js";
77
import { skillsManager } from "../skills/skills-manager.js";
8+
import { releasePluginTursoLease } from "./plugin-refs.js";
9+
10+
export {
11+
retainPluginTurso,
12+
pluginTursoRefCount,
13+
resetPluginTursoRefsForTests,
14+
} from "./plugin-refs.js";
15+
16+
/**
17+
* Drop one plugin-instance lease. Closes the process-wide pool only when the
18+
* last live instance is gone (or when no retain was recorded — tests / force
19+
* close via `memoryClient.close()`).
20+
*
21+
* @returns `true` when connections were closed and manager caches invalidated
22+
*/
23+
export async function releasePluginTurso(): Promise<boolean> {
24+
if (!releasePluginTursoLease()) {
25+
return false;
26+
}
27+
await closeTursoAndInvalidateCaches();
28+
return true;
29+
}
830

931
export async function closeTursoAndInvalidateCaches(): Promise<void> {
1032
await tursoConnectionManager.closeAll();

‎src/services/turso/plugin-refs.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Process-wide lease count for live plugin instances. OpenCode Desktop hosts
3+
* several sessions in one process; each session loads its own plugin instance.
4+
* Disposing one must not close the shared Turso pool while others are alive
5+
* (#443).
6+
*
7+
* Kept free of manager imports so `index.ts` can retain without pulling the
8+
* full Turso lifecycle graph at module load.
9+
*/
10+
const PLUGIN_TURSO_REFS_KEY = Symbol.for("opencode-mem.plugin.tursoRefs");
11+
12+
type PluginTursoRefs = { count: number };
13+
14+
function pluginTursoRefs(): PluginTursoRefs {
15+
const g = globalThis as typeof globalThis & {
16+
[PLUGIN_TURSO_REFS_KEY]?: PluginTursoRefs;
17+
};
18+
if (!g[PLUGIN_TURSO_REFS_KEY]) {
19+
g[PLUGIN_TURSO_REFS_KEY] = { count: 0 };
20+
}
21+
return g[PLUGIN_TURSO_REFS_KEY];
22+
}
23+
24+
/** Register a live plugin instance that depends on the shared Turso pool. */
25+
export function retainPluginTurso(): void {
26+
pluginTursoRefs().count += 1;
27+
}
28+
29+
/**
30+
* Drop one plugin-instance lease.
31+
* @returns `true` when the caller should close the process-wide Turso pool
32+
* (last live instance, or no retain was recorded — tests / direct close)
33+
*/
34+
export function releasePluginTursoLease(): boolean {
35+
const refs = pluginTursoRefs();
36+
if (refs.count > 0) {
37+
refs.count -= 1;
38+
return refs.count === 0;
39+
}
40+
// No retain recorded (tests calling memoryClient.close() directly) — close.
41+
return true;
42+
}
43+
44+
/** Current live plugin-instance lease count (test / diagnostics). */
45+
export function pluginTursoRefCount(): number {
46+
return pluginTursoRefs().count;
47+
}
48+
49+
/** Reset lease count without touching connections (tests). */
50+
export function resetPluginTursoRefsForTests(): void {
51+
pluginTursoRefs().count = 0;
52+
}

‎src/services/user-profile/user-profile-manager.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,10 +140,16 @@ export class UserProfileManager {
140140
}
141141

142142
private async ready(): Promise<TursoDb> {
143-
if (!this.db || !this.initPromise) {
143+
await this.initialize();
144+
// Connection manager is authoritative: another plugin instance's dispose
145+
// may close/replace the pooled handle underneath a cached TursoDb (#443).
146+
if (this.db) {
147+
const current = await tursoConnectionManager.getConnection(this.dbPath);
148+
if (current === this.db) {
149+
return this.db;
150+
}
151+
this.reset();
144152
await this.initialize();
145-
} else {
146-
await this.initPromise;
147153
}
148154

149155
if (!this.db) {

‎src/services/user-prompt/user-prompt-manager.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,16 @@ export class UserPromptManager {
5656
}
5757

5858
private async ready(): Promise<TursoDb> {
59-
if (!this.db || !this.initPromise) {
59+
await this.initialize();
60+
// Connection manager is authoritative: another plugin instance's dispose
61+
// may close/replace the pooled handle underneath a cached TursoDb (#443).
62+
if (this.db) {
63+
const current = await tursoConnectionManager.getConnection(this.dbPath);
64+
if (current === this.db) {
65+
return this.db;
66+
}
67+
this.reset();
6068
await this.initialize();
61-
} else {
62-
await this.initPromise;
6369
}
6470

6571
if (!this.db) {
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { afterEach, describe, expect, it } from "bun:test";
2+
import { mkdtempSync } from "node:fs";
3+
import { join } from "node:path";
4+
import { tmpdir } from "node:os";
5+
import { cleanupTursoTestDirectory } from "./turso-test-utils.js";
6+
7+
describe("plugin Turso refcount (#443)", () => {
8+
let baseDir: string;
9+
10+
afterEach(async () => {
11+
const { resetPluginTursoRefsForTests } = await import("../src/services/turso/lifecycle.js");
12+
resetPluginTursoRefsForTests();
13+
await cleanupTursoTestDirectory(baseDir);
14+
});
15+
16+
it("releasePluginTurso keeps the pool open while another instance is alive", async () => {
17+
baseDir = mkdtempSync(join(tmpdir(), "turso-refcount-"));
18+
const { CONFIG } = await import("../src/config.js");
19+
CONFIG.storagePath = baseDir;
20+
21+
const {
22+
retainPluginTurso,
23+
releasePluginTurso,
24+
pluginTursoRefCount,
25+
resetPluginTursoRefsForTests,
26+
closeTursoAndInvalidateCaches,
27+
} = await import("../src/services/turso/lifecycle.js");
28+
const { userPromptManager } =
29+
await import("../src/services/user-prompt/user-prompt-manager.js");
30+
const { tursoConnectionManager } = await import("../src/services/turso/connection-manager.js");
31+
32+
await closeTursoAndInvalidateCaches();
33+
resetPluginTursoRefsForTests();
34+
35+
retainPluginTurso();
36+
retainPluginTurso();
37+
expect(pluginTursoRefCount()).toBe(2);
38+
39+
const id = await userPromptManager.savePrompt("sess-a", "msg-a", "/tmp/p", "hello");
40+
const dbPath = join(baseDir, "user-prompts.db");
41+
const handleBefore = await tursoConnectionManager.getConnection(dbPath);
42+
43+
const closedOnFirstRelease = await releasePluginTurso();
44+
expect(closedOnFirstRelease).toBe(false);
45+
expect(pluginTursoRefCount()).toBe(1);
46+
47+
// Sibling instance still live: same pooled handle, queries still work.
48+
expect(await tursoConnectionManager.getConnection(dbPath)).toBe(handleBefore);
49+
const prompt = await userPromptManager.getPromptById(id);
50+
expect(prompt?.content).toBe("hello");
51+
52+
const closedOnLastRelease = await releasePluginTurso();
53+
expect(closedOnLastRelease).toBe(true);
54+
expect(pluginTursoRefCount()).toBe(0);
55+
});
56+
57+
it("memoryClient.close only invalidates when the last lease is released", async () => {
58+
baseDir = mkdtempSync(join(tmpdir(), "turso-refcount-client-"));
59+
const { CONFIG } = await import("../src/config.js");
60+
CONFIG.storagePath = baseDir;
61+
62+
const {
63+
retainPluginTurso,
64+
pluginTursoRefCount,
65+
resetPluginTursoRefsForTests,
66+
closeTursoAndInvalidateCaches,
67+
} = await import("../src/services/turso/lifecycle.js");
68+
const { memoryClient } = await import("../src/services/client.js");
69+
const { userPromptManager } =
70+
await import("../src/services/user-prompt/user-prompt-manager.js");
71+
72+
await closeTursoAndInvalidateCaches();
73+
resetPluginTursoRefsForTests();
74+
75+
retainPluginTurso();
76+
retainPluginTurso();
77+
expect(pluginTursoRefCount()).toBe(2);
78+
79+
const id = await userPromptManager.savePrompt("sess-b", "msg-b", "/tmp/p", "world");
80+
81+
await memoryClient.close();
82+
expect(pluginTursoRefCount()).toBe(1);
83+
expect((await userPromptManager.getPromptById(id))?.content).toBe("world");
84+
85+
await memoryClient.close();
86+
expect(pluginTursoRefCount()).toBe(0);
87+
});
88+
});

‎tests/turso-connection-lifecycle.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,4 +46,22 @@ describe("turso connection lifecycle", () => {
4646
await reopened.get(`SELECT name FROM sqlite_master WHERE name = 'lifecycle_probe'`)
4747
).toBeTruthy();
4848
});
49+
50+
it("UserPromptManager reopens after closeConnection without lifecycle reset (#443)", async () => {
51+
baseDir = mkdtempSync(join(tmpdir(), "turso-lifecycle-stale-"));
52+
const { CONFIG } = await import("../src/config.js");
53+
CONFIG.storagePath = baseDir;
54+
55+
const { userPromptManager } =
56+
await import("../src/services/user-prompt/user-prompt-manager.js");
57+
const { tursoConnectionManager } = await import("../src/services/turso/connection-manager.js");
58+
59+
const id = await userPromptManager.savePrompt("sess-2", "msg-2", "/tmp/project", "stale-guard");
60+
expect((await userPromptManager.getPromptById(id))?.content).toBe("stale-guard");
61+
62+
await tursoConnectionManager.closeConnection(join(baseDir, "user-prompts.db"));
63+
64+
const prompt = await userPromptManager.getPromptById(id);
65+
expect(prompt?.content).toBe("stale-guard");
66+
});
4967
});

0 commit comments

Comments
 (0)