Skip to content

Persistent project knowledge graph for coding agents. MCP server with semantic search, in-process embeddings, and web explorer.

fix: make multi-statement DB writes atomic and add concurrency resilience

0xk3vin7bd1a31f9123
diff --git a/package-lock.json b/package-lock.json
index 898444a..9ed3fe0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "megamemory",
- "version": "1.4.1",
+ "version": "1.5.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "megamemory",
- "version": "1.4.1",
+ "version": "1.5.0",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/sdk": "^1.12.1",
diff --git a/src/__tests__/db.test.ts b/src/__tests__/db.test.ts
index b87f56f..a30ddd0 100644
--- a/src/__tests__/db.test.ts
+++ b/src/__tests__/db.test.ts
@@ -462,6 +462,125 @@ describe("KnowledgeDB", () => {
expect(db.getNode("rolled-back")).toBeUndefined();
});
+
+ it("runInTransaction supports nesting without error", () => {
+ db.runInTransaction(() => {
+ db.insertNode({
+ id: "outer-node",
+ name: "Outer",
+ kind: "feature",
+ summary: "outer",
+ why: null,
+ file_refs: null,
+ parent_id: null,
+ created_by_task: null,
+ embedding: null,
+ });
+ db.runInTransaction(() => {
+ db.insertNode({
+ id: "inner-node",
+ name: "Inner",
+ kind: "feature",
+ summary: "inner",
+ why: null,
+ file_refs: null,
+ parent_id: null,
+ created_by_task: null,
+ embedding: null,
+ });
+ });
+ });
+
+ expect(db.getNode("outer-node")).toBeDefined();
+ expect(db.getNode("inner-node")).toBeDefined();
+ });
+
+ it("nested runInTransaction rollback rolls back outer transaction", () => {
+ expect(() => {
+ db.runInTransaction(() => {
+ db.insertNode({
+ id: "rollback-outer",
+ name: "Outer",
+ kind: "feature",
+ summary: "outer",
+ why: null,
+ file_refs: null,
+ parent_id: null,
+ created_by_task: null,
+ embedding: null,
+ });
+ db.runInTransaction(() => {
+ throw new Error("inner failure");
+ });
+ });
+ }).toThrow("inner failure");
+
+ expect(db.getNode("rollback-outer")).toBeUndefined();
+ });
+
+ it("runWithRetry retries on SQLITE_BUSY and succeeds", () => {
+ let attempts = 0;
+ const result = db.runWithRetry(() => {
+ attempts++;
+ if (attempts < 3) throw new Error("SQLITE_BUSY");
+ return "success";
+ }, 3);
+
+ expect(result).toBe("success");
+ expect(attempts).toBe(3);
+ });
+
+ it("runWithRetry throws after max retries exceeded", () => {
+ expect(() => {
+ db.runWithRetry(() => {
+ throw new Error("SQLITE_BUSY");
+ }, 2);
+ }).toThrow("SQLITE_BUSY");
+ });
+
+ it("runWithRetry does not retry non-busy errors", () => {
+ let attempts = 0;
+ expect(() => {
+ db.runWithRetry(() => {
+ attempts++;
+ throw new Error("UNIQUE constraint failed");
+ }, 3);
+ }).toThrow("UNIQUE constraint failed");
+
+ expect(attempts).toBe(1);
+ });
+
+ it("softDeleteNode removes edges atomically", () => {
+ db.insertNode({
+ id: "del-a",
+ name: "A",
+ kind: "feature",
+ summary: "a",
+ why: null,
+ file_refs: null,
+ parent_id: null,
+ created_by_task: null,
+ embedding: null,
+ });
+ db.insertNode({
+ id: "del-b",
+ name: "B",
+ kind: "feature",
+ summary: "b",
+ why: null,
+ file_refs: null,
+ parent_id: null,
+ created_by_task: null,
+ embedding: null,
+ });
+ db.insertEdge({ from_id: "del-a", to_id: "del-b", relation: "calls" });
+
+ db.softDeleteNode("del-a", "test deletion");
+
+ const edges = db.getAllEdges();
+ const edgesToA = edges.filter((e) => e.from_id === "del-a" || e.to_id === "del-a");
+ expect(edgesToA).toHaveLength(0);
+ });
});
describe("schema v2 - merge columns", () => {
diff --git a/src/db.ts b/src/db.ts
index 26e47a8..d17ad23 100644
--- a/src/db.ts
+++ b/src/db.ts
@@ -7,6 +7,7 @@ const SCHEMA_VERSION = 4;
export class KnowledgeDB {
private db: Database.Database;
+ private _txDepth = 0;
constructor(dbPath: string) {
// Ensure directory exists
@@ -18,7 +19,7 @@ export class KnowledgeDB {
this.db = new Database(dbPath);
this.db.pragma("journal_mode = WAL");
this.db.pragma("foreign_keys = ON");
- this.db.pragma("busy_timeout = 1000");
+ this.db.pragma("busy_timeout = 5000");
this.db.pragma("synchronous = NORMAL");
this.migrate();
}
@@ -177,14 +178,49 @@ export class KnowledgeDB {
}
runInTransaction<T>(fn: () => T): T {
- this.db.exec("BEGIN IMMEDIATE");
+ if (this._txDepth > 0) {
+ // Already inside a transaction — just run the function
+ this._txDepth++;
+ try {
+ return fn();
+ } finally {
+ this._txDepth--;
+ }
+ }
+
+ this._txDepth++;
try {
- const result = fn();
- this.db.exec("COMMIT");
- return result;
- } catch (err) {
- this.db.exec("ROLLBACK");
- throw err;
+ return this.runWithRetry(() => {
+ this.db.exec("BEGIN IMMEDIATE");
+ try {
+ const result = fn();
+ this.db.exec("COMMIT");
+ return result;
+ } catch (err) {
+ this.db.exec("ROLLBACK");
+ throw err;
+ }
+ });
+ } finally {
+ this._txDepth--;
+ }
+ }
+
+ runWithRetry<T>(fn: () => T, maxRetries = 3): T {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return fn();
+ } catch (err: unknown) {
+ const isBusy =
+ err instanceof Error &&
+ (err.message.includes("SQLITE_BUSY") ||
+ err.message.includes("database is locked"));
+ if (!isBusy || attempt >= maxRetries) {
+ throw err;
+ }
+ const delayMs = 50 * Math.pow(2, attempt);
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs);
+ }
}
}
@@ -323,20 +359,22 @@ export class KnowledgeDB {
}
softDeleteNode(id: string, reason: string): boolean {
- const stmt = this.db.prepare(`
- UPDATE nodes SET removed_at = datetime('now'), removed_reason = @reason, updated_at = datetime('now')
- WHERE id = @id AND removed_at IS NULL
- `);
- const result = stmt.run({ id, reason });
-
- // Also remove edges involving this node
- if (result.changes > 0) {
- this.db
- .prepare("DELETE FROM edges WHERE from_id = ? OR to_id = ?")
- .run(id, id);
- }
-
- return result.changes > 0;
+ let changed = false;
+ this.runInTransaction(() => {
+ const stmt = this.db.prepare(`
+ UPDATE nodes SET removed_at = datetime('now'), removed_reason = @reason, updated_at = datetime('now')
+ WHERE id = @id AND removed_at IS NULL
+ `);
+ const result = stmt.run({ id, reason });
+
+ if (result.changes > 0) {
+ changed = true;
+ this.db
+ .prepare("DELETE FROM edges WHERE from_id = ? OR to_id = ?")
+ .run(id, id);
+ }
+ });
+ return changed;
}
// ---- Edge CRUD ----
@@ -609,11 +647,15 @@ export class KnowledgeDB {
}
hardDeleteNode(id: string): boolean {
- this.deleteEdgesForNode(id);
- const result = this.db
- .prepare("DELETE FROM nodes WHERE id = ?")
- .run(id);
- return result.changes > 0;
+ let changed = false;
+ this.runInTransaction(() => {
+ this.deleteEdgesForNode(id);
+ const result = this.db
+ .prepare("DELETE FROM nodes WHERE id = ?")
+ .run(id);
+ changed = result.changes > 0;
+ });
+ return changed;
}
insertNodeRaw(node: {
diff --git a/src/index.ts b/src/index.ts
index e289f71..ae4f054 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -168,6 +168,25 @@ async function startMcpServer() {
const db = new KnowledgeDB(DB_PATH);
const timeline = createTimelineLogger(db);
+ let dbClosed = false;
+ function shutdown() {
+ if (dbClosed) return;
+ dbClosed = true;
+ try {
+ db.close();
+ } catch {
+ // ignore
+ }
+ }
+ process.on("SIGINT", () => {
+ shutdown();
+ process.exit(0);
+ });
+ process.on("SIGTERM", () => {
+ shutdown();
+ process.exit(0);
+ });
+
const server = new McpServer({
name: "megamemory",
version: VERSION,
diff --git a/src/timeline.ts b/src/timeline.ts
index c3bae5e..7859eab 100644
--- a/src/timeline.ts
+++ b/src/timeline.ts
@@ -15,14 +15,18 @@ export function createTimelineLogger(db: KnowledgeDB): TimelineLogger {
return {
log(entry) {
try {
- db.insertTimelineEntry({
- tool: entry.tool,
- params: JSON.stringify(entry.params),
- result_summary: entry.result_summary,
- is_write: entry.is_write,
- is_error: entry.is_error,
- affected_ids: entry.affected_ids,
- });
+ db.runWithRetry(
+ () =>
+ db.insertTimelineEntry({
+ tool: entry.tool,
+ params: JSON.stringify(entry.params),
+ result_summary: entry.result_summary,
+ is_write: entry.is_write,
+ is_error: entry.is_error,
+ affected_ids: entry.affected_ids,
+ }),
+ 1
+ );
} catch (err) {
// Timeline logging must never break tool execution
console.error("Timeline logging failed:", err instanceof Error ? err.message : String(err));
diff --git a/src/tools.ts b/src/tools.ts
index 1981cf0..79b3655 100644
--- a/src/tools.ts
+++ b/src/tools.ts
@@ -353,44 +353,43 @@ export async function resolveConflict(
const base = nodes.find((n) => n.removed_at === null) ?? nodes[0];
const originalId = stripMergeSuffix(base.id);
- // Delete all conflict copies except the base
- for (const node of nodes) {
- if (node.id !== base.id) {
- db.hardDeleteNode(node.id);
- }
- }
+ const text = embeddingText(base.name, base.kind, input.resolved.summary);
+ const newEmbedding = await embed(text);
- // Rename the base back to the original clean ID
- if (base.id !== originalId) {
- const renamed = db.renameNodeId(base.id, originalId);
- if (!renamed) {
- throw new Error(`Failed to rename resolved node from ${base.id} to ${originalId}`);
- }
- }
-
- // Apply the resolved content
const changes: { summary?: string; why?: string; file_refs?: string[] } = {
summary: input.resolved.summary,
};
if (input.resolved.why !== undefined) changes.why = input.resolved.why;
if (input.resolved.file_refs !== undefined) changes.file_refs = input.resolved.file_refs;
- const updated = db.updateNode(originalId, changes);
- if (!updated) {
- throw new Error(`Failed to apply resolved content to ${originalId}`);
- }
+ db.runInTransaction(() => {
+ // Delete all conflict copies except the base
+ for (const node of nodes) {
+ if (node.id !== base.id) {
+ db.hardDeleteNode(node.id);
+ }
+ }
+
+ // Rename the base back to the original clean ID
+ if (base.id !== originalId) {
+ const renamed = db.renameNodeId(base.id, originalId);
+ if (!renamed) {
+ throw new Error(`Failed to rename resolved node from ${base.id} to ${originalId}`);
+ }
+ }
+
+ // Apply the resolved content
+ const updated = db.updateNode(originalId, changes);
+ if (!updated) {
+ throw new Error(`Failed to apply resolved content to ${originalId}`);
+ }
- // Regenerate embedding with the resolved summary
- const node = db.getNode(originalId);
- if (node) {
- const text = embeddingText(node.name, node.kind, input.resolved.summary);
- const newEmbedding = await embed(text);
db.updateNode(originalId, { embedding: newEmbedding });
- }
- // Clear merge flags on the resolved node and any associated edges
- db.clearNodeMergeFlags(originalId);
- db.clearEdgeMergeFlagsByGroup(input.merge_group);
+ // Clear merge flags on the resolved node and any associated edges
+ db.clearNodeMergeFlags(originalId);
+ db.clearEdgeMergeFlagsByGroup(input.merge_group);
+ });
return {
message: `Resolved "${originalId}". Reason: ${input.reason}`,