Skip to content

Commit ff45aaf

Browse files
yetvalobviyus
andauthored
fix(memory-core): restore MEMORY.md after failed fallback write (#126486)
Preserve the verified MEMORY.md preimage when the ACL-compatible in-place promotion fallback fails after a partial write. Complete short restore writes before truncating and syncing, then return the original write error. Co-authored-by: Yuval Dinodia <[email protected]> Co-authored-by: Ayaan Zaidi <[email protected]>
1 parent 9b4f522 commit ff45aaf

2 files changed

Lines changed: 139 additions & 0 deletions

File tree

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { afterEach, expect, it, vi } from "vitest";
5+
import { hashMemoryContent, writeMemoryContent } from "./short-term-promotion-memory-write.js";
6+
7+
const openState = vi.hoisted(() => ({
8+
failInPlaceWriteAfterBytes: null as number | null,
9+
shortFirstRestoreWrite: false,
10+
}));
11+
12+
vi.mock("node:fs/promises", async (importOriginal) => {
13+
const actual = await importOriginal<typeof import("node:fs/promises")>();
14+
const open: typeof actual.open = async (...args) => {
15+
const handle = await actual.open(...(args as Parameters<typeof actual.open>));
16+
const partialBytes = openState.failInPlaceWriteAfterBytes;
17+
if (args[1] !== "r+" || partialBytes === null) {
18+
return handle;
19+
}
20+
openState.failInPlaceWriteAfterBytes = null;
21+
let shortWriteArmed = openState.shortFirstRestoreWrite;
22+
openState.shortFirstRestoreWrite = false;
23+
const realWrite = handle.write.bind(handle);
24+
const failingWriteFile = async (content: string) => {
25+
const partial = Buffer.from(content, "utf-8").subarray(0, partialBytes);
26+
await realWrite(partial, 0, partial.length, 0);
27+
throw Object.assign(new Error("EFBIG: file too large, write"), { code: "EFBIG" });
28+
};
29+
const write = async (buffer: Buffer, offset: number, length: number, position: number) => {
30+
const cappedLength = shortWriteArmed && length > 1 ? Math.floor(length / 2) : length;
31+
shortWriteArmed = false;
32+
return await realWrite(buffer, offset, cappedLength, position);
33+
};
34+
Object.defineProperties(handle, {
35+
writeFile: { value: failingWriteFile },
36+
write: { value: write },
37+
});
38+
return handle;
39+
};
40+
return { ...actual, default: { ...actual, open }, open };
41+
});
42+
43+
const cleanups: Array<() => Promise<void>> = [];
44+
45+
afterEach(async () => {
46+
openState.failInPlaceWriteAfterBytes = null;
47+
openState.shortFirstRestoreWrite = false;
48+
while (cleanups.length > 0) {
49+
await cleanups.pop()?.();
50+
}
51+
});
52+
53+
async function setupReadOnlyMemoryDir(originalContent: string): Promise<string> {
54+
const tempRoot = await fs.realpath(
55+
await fs.mkdtemp(path.join(os.tmpdir(), "memory-write-test-")),
56+
);
57+
const memoryDir = path.join(tempRoot, "workspace");
58+
await fs.mkdir(memoryDir);
59+
const memoryPath = path.join(memoryDir, "MEMORY.md");
60+
await fs.writeFile(memoryPath, originalContent, "utf-8");
61+
await fs.chmod(memoryDir, 0o555);
62+
cleanups.push(async () => {
63+
await fs.chmod(memoryDir, 0o755);
64+
await fs.rm(tempRoot, { recursive: true, force: true });
65+
});
66+
return memoryPath;
67+
}
68+
69+
it.runIf(process.platform !== "win32")(
70+
"keeps the original MEMORY.md when the in-place fallback write fails partway",
71+
async () => {
72+
const original = "# Long-Term Memory\n\n- existing entry that must survive\n";
73+
const memoryPath = await setupReadOnlyMemoryDir(original);
74+
const promoted = `${original}${"- promoted entry\n".repeat(200)}`;
75+
openState.failInPlaceWriteAfterBytes = 1024;
76+
77+
await expect(
78+
writeMemoryContent({
79+
memoryPath,
80+
memoryWritePath: memoryPath,
81+
expectedHash: hashMemoryContent(original),
82+
expectedContent: original,
83+
allowInPlaceFallback: true,
84+
content: promoted,
85+
}),
86+
).rejects.toMatchObject({ code: "EFBIG" });
87+
88+
expect(await fs.readFile(memoryPath, "utf-8")).toBe(original);
89+
},
90+
);
91+
92+
it.runIf(process.platform !== "win32")(
93+
"completes the restore across short writes before truncating",
94+
async () => {
95+
const original = "# Long-Term Memory\n\n- existing entry that must survive\n";
96+
const memoryPath = await setupReadOnlyMemoryDir(original);
97+
const promoted = `# Long-Term Memory\n\n## 2026-08-19\n${"- promoted entry\n".repeat(200)}`;
98+
openState.failInPlaceWriteAfterBytes = 1024;
99+
openState.shortFirstRestoreWrite = true;
100+
101+
await expect(
102+
writeMemoryContent({
103+
memoryPath,
104+
memoryWritePath: memoryPath,
105+
expectedHash: hashMemoryContent(original),
106+
expectedContent: original,
107+
allowInPlaceFallback: true,
108+
content: promoted,
109+
}),
110+
).rejects.toMatchObject({ code: "EFBIG" });
111+
112+
expect(await fs.readFile(memoryPath, "utf-8")).toBe(original);
113+
},
114+
);

‎extensions/memory-core/src/short-term-promotion-memory-write.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,31 @@ async function writeExistingMemoryInPlace(params: {
8282
await handle.truncate(Buffer.byteLength(params.content));
8383
await handle.sync();
8484
return true;
85+
} catch (error) {
86+
const original = Buffer.from(params.expectedContent, "utf-8");
87+
try {
88+
let restored = 0;
89+
while (restored < original.length) {
90+
const { bytesWritten } = await handle.write(
91+
original,
92+
restored,
93+
original.length - restored,
94+
restored,
95+
);
96+
if (bytesWritten <= 0) {
97+
throw new Error("MEMORY.md restore write made no progress", { cause: error });
98+
}
99+
restored += bytesWritten;
100+
}
101+
await handle.truncate(original.length);
102+
await handle.sync();
103+
} catch (restoreError) {
104+
throw new Error(
105+
"MEMORY.md in-place write failed and restoring the original content also failed",
106+
{ cause: restoreError },
107+
);
108+
}
109+
throw error;
85110
} finally {
86111
await handle.close();
87112
}

0 commit comments

Comments
 (0)