Skip to content
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
959edbc
fix(studio-server): a file the drive never answers no longer holds a …
miguel-heygen Nov 18, 2026
29ee475
fix(studio-server): keep history's comment share at or below its base
miguel-heygen Nov 18, 2026
e718969
fix(studio-server): a first copy that lands past its deadline is kept…
miguel-heygen Nov 19, 2026
4892c12
fix(studio-server): a late first copy is adopted and kept while anoth…
miguel-heygen Nov 19, 2026
68a04bb
fix(studio-server): a waiting late first copy counts as baseline and …
miguel-heygen Nov 19, 2026
4b65fe7
fix(studio-server): every reread of an owed file takes a copy slot an…
miguel-heygen Nov 19, 2026
065757f
fix(studio-server): history pins a copy as it is filed and keeps a re…
miguel-heygen Nov 19, 2026
59d9710
fix(studio-server): a history pin is taken and released by its owner,…
miguel-heygen Nov 19, 2026
9e2378b
Merge remote-tracking branch 'origin/main' into fix/history-copy-dead…
miguel-heygen Nov 21, 2026
27631d4
fix(studio-server): an agent step waits at most a deadline for a file…
miguel-heygen Nov 21, 2026
397d3bf
fix(studio-server): undo refuses a file whose first copy landed after…
miguel-heygen Nov 21, 2026
031671c
chore(studio-server): give the packed size budget its usual 5% headroom
miguel-heygen Nov 21, 2026
33eafbf
fix(studio-server): an agent step that goes ahead of a first copy own…
miguel-heygen Nov 21, 2026
6ff4d4e
fix(studio-server): undo of a step that went ahead of a pending first…
miguel-heygen Nov 21, 2026
dfe957d
Merge remote-tracking branch 'origin/main' into fix/history-copy-dead…
miguel-heygen Nov 21, 2026
a30cf5b
fix(studio-server): an undo after a step that rewrote a pending file …
miguel-heygen Nov 21, 2026
a2032ba
fix(studio-server): a step ahead of a pending file refuses undo after…
miguel-heygen Nov 21, 2026
b910bd6
fix(studio-server): a step that went ahead of a pending file never un…
miguel-heygen Nov 21, 2026
021580d
fix(studio-server): a recovered step keeps its guard through a second…
miguel-heygen Nov 21, 2026
2e293fc
fix(studio-server): a start keeps receipts heard before its read; reo…
miguel-heygen Nov 21, 2026
59ee378
fix(studio-server): a first copy's start follows only receipts heard …
miguel-heygen Nov 21, 2026
5a0b3a6
fix(studio-server): bytes kept for a pending first copy count as star…
miguel-heygen Nov 21, 2026
46e78b1
Merge remote-tracking branch 'origin/main' into fix/history-copy-dead…
miguel-heygen Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions packages/studio-server/src/history/__fixtures__/stepThenDie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Reads of `stuck` (comma-separated) never answer; a step rewrites or deletes them, then the process dies: "open"
// mid-step, "reopen"/"reopen-list" recovering the JSON window, at its first sweep/went-ahead.json write.
import fs, { unlinkSync, writeFileSync } from "node:fs";
import fsp from "node:fs/promises";
import { syncBuiltinESMExports } from "node:module";
import { join } from "node:path";

const [projectDir, historyRoot, stuck, mode = "close", closedWindow] = process.argv.slice(2);
const stuckFiles = stuck!.split(",");
const realOpen = fsp.open;
fsp.open = (async (...args: Parameters<typeof realOpen>) => {
if (stuckFiles.includes(String(args[0]))) await new Promise(() => {});
if (mode === "reopen" && String(args[0]) === join(projectDir!, "index.html"))
process.kill(process.pid, "SIGKILL");
return realOpen(...args);
}) as typeof realOpen;
const realRename = fs.renameSync;
fs.renameSync = ((from: fs.PathLike, to: fs.PathLike) => {
realRename(from, to);
if (mode === "reopen-list" && String(to).endsWith("went-ahead.json"))
process.kill(process.pid, "SIGKILL");
}) as typeof realRename;
syncBuiltinESMExports();

const { openProjectHistory } = await import("../projectHistory.js");
const history = await openProjectHistory({
projectDir: projectDir!,
historyRoot: historyRoot!,
firstCopyFileMs: 100,
now: () => Date.now() + 60_000,
...(closedWindow && { closedWindow: JSON.parse(closedWindow) }),
});
const agent = { kind: "agent", name: "Framey" } as const;
const index = join(projectDir!, "index.html");
if (mode === "earlier") {
writeFileSync(index, "<html>first</html>");
await history.claim({ kind: "person", name: "You" }, "First", [index]);
}
const step = await history.beginWindow(agent, "Step");
await new Promise((sent) => process.send!({ id: step.id }, sent));
for (const path of stuckFiles)
if (mode === "delete") unlinkSync(path);
else writeFileSync(path, "// agent\n");
writeFileSync(index, "<html>agent</html>");
for (const path of stuckFiles) history.noteChange(path);
history.noteChange(index);
if (mode !== "open") await step.close();
process.kill(process.pid, "SIGKILL");
111 changes: 111 additions & 0 deletions packages/studio-server/src/history/blobStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ vi.mock("node:fs/promises", async (importOriginal) => {
rename: vi.fn(actual.rename),
copyFile: vi.fn(actual.copyFile),
open: vi.fn(actual.open),
rm: vi.fn(actual.rm),
};
});

Expand All @@ -33,6 +34,7 @@ const {
rename: realRename,
copyFile: realCopyFile,
open: realOpen,
rm: realRm,
} = await vi.importActual<typeof import("node:fs/promises")>("node:fs/promises");
const busy = () => Object.assign(new Error("EPERM: operation not permitted"), { code: "EPERM" });
const platform = process.platform;
Expand Down Expand Up @@ -225,6 +227,115 @@ describe("the history store's count of what it holds", () => {
});
});

describe("a pinned copy", () => {
it("survives every prune from the moment it is filed until it is unpinned", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-"));
try {
const small = join(root, "small.txt");
const large = join(root, "large.txt");
writeFileSync(small, "pinned bytes");
writeFileSync(large, "y".repeat(200 * 1024));
const store = await openBlobStore(join(root, "history", "blobs"));
const hashes = [await store.put(small, true), await store.put(large, true)];
await store.prune(new Set());
for (const hash of hashes) expect(store.has(hash!)).toBe(true);
for (const hash of hashes) store.unpin(hash!);
await store.prune(new Set());
for (const hash of hashes) expect(store.has(hash!)).toBe(false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});

it("pins a copy whose bytes the store already holds, and keeps it until each pin is let go", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-"));
try {
const file = join(root, "same.txt");
writeFileSync(file, "same bytes");
const store = await openBlobStore(join(root, "history", "blobs"));
const hash = (await store.put(file))!;
await store.put(file, true);
await store.put(file, true);
store.unpin(hash);
await store.prune(new Set());
expect(store.has(hash)).toBe(true);
store.unpin(hash);
await store.prune(new Set());
expect(store.has(hash)).toBe(false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});

describe("a pinned copy filed while its hash is pruned", () => {
afterEach(() => {
vi.mocked(fsp.rm).mockImplementation(realRm);
vi.mocked(fsp.open).mockImplementation(realOpen);
});

it("is filed again after the delete, never deleted after it is pinned", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-"));
try {
const file = join(root, "same.txt");
writeFileSync(file, "same bytes");
const blobs = join(root, "history", "blobs");
const store = await openBlobStore(blobs);
const hash = (await store.put(file))!;
let release = () => {};
const held = new Promise<void>((resolve) => (release = resolve));
let deleting = 0;
vi.mocked(fsp.rm).mockImplementation(async (...args: Parameters<typeof realRm>) => {
if (String(args[0]).endsWith(hash)) {
deleting += 1;
await held;
}
return realRm(...args);
});
let read = false;
vi.mocked(fsp.open).mockImplementation(async (...args: Parameters<typeof realOpen>) => {
const handle = await realOpen(...args);
if (String(args[0]) !== file) return handle;
const close = handle.close.bind(handle);
handle.close = async () => {
await close();
read = true;
};
return handle;
});
const pruned = store.prune(new Set());
await vi.waitFor(() => expect(deleting).toBe(1));
const pinned = store.put(file, true);
// The put has read its bytes and come to the store while the delete is still under way.
await vi.waitFor(() => expect(read).toBe(true));
release();
await Promise.all([pruned, pinned]);
expect(store.has(hash)).toBe(true);
await expect(readBlob(blobs, hash)).resolves.toEqual(Buffer.from("same bytes"));
} finally {
rmSync(root, { recursive: true, force: true });
}
});

it("takes no pin when the duplicate it staged cannot be removed", async () => {
const root = mkdtempSync(join(tmpdir(), "hf-blob-pin-"));
try {
const large = join(root, "large.txt");
writeFileSync(large, "z".repeat(200 * 1024));
const store = await openBlobStore(join(root, "history", "blobs"));
await store.put(large);
vi.mocked(fsp.rm).mockImplementation(async (...args: Parameters<typeof realRm>) => {
if (String(args[0]).includes("incoming-")) throw busy();
return realRm(...args);
});
await expect(store.put(large, true)).rejects.toThrow("EPERM");
expect([...store.pinned()]).toEqual([]);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});

describe("a file written to while the history reads it", () => {
let root: string;
beforeEach(() => {
Expand Down
80 changes: 59 additions & 21 deletions packages/studio-server/src/history/blobStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ import { assertLandedIn, assertStillWithin, folderWithin } from "./containedPath
/** File contents stored once by sha256, text and binary alike. */
export interface BlobStore {
/** Copies the file in (cloned where it can) and returns its hash; null while it keeps changing. */
put(absPath: string): Promise<string | null>;
put(absPath: string, pin?: boolean, onRead?: () => void): Promise<string | null>;
unpin(hash: string): void;
pinned(): Iterable<string>;
reference(absPath: string): Promise<string>;
has(hash: string): boolean;
read(hash: string): Promise<Buffer>;
Expand Down Expand Up @@ -75,13 +77,17 @@ export async function hashFile(path: string): Promise<string> {

async function readIfSmall(
path: string,
onRead: () => void,
): Promise<{ bytes: Buffer; mode: number; moved: boolean } | null> {
const handle = await open(path, "r");
try {
const before = await handle.stat();
if (before.size > READ_ONCE_AT_MOST_BYTES) return null;
const bytes = await handle.readFile();
return { bytes, mode: before.mode, moved: !unchanged(before, await handle.stat()) };
const moved = !unchanged(before, await handle.stat());
// At the read itself, not after the close, which a slow drive can hold.
if (!moved) onRead();
return { bytes, mode: before.mode, moved };
} finally {
await handle.close();
}
Expand Down Expand Up @@ -194,11 +200,23 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
for (const hash of asideSizes.keys()) holds.set(hash, new Set(["*"]));
const pathOf = (hash: string) => blobPath(sizes.has(hash) ? dir : asideDir, hash);
let total = [...sizes.values()].reduce((sum, size) => sum + size, 0);
const forget = async (hash: string) => {
await rm(blobPath(dir, hash), { force: true });
total -= sizes.get(hash) ?? 0;
sizes.delete(hash);
const pins = new Map<string, number>();
const pin = (hash: string) => pins.set(hash, (pins.get(hash) ?? 0) + 1);
const turns = new Map<string, Promise<unknown>>();
const inTurn = <T>(hash: string, step: () => Promise<T>): Promise<T> => {
const done = (turns.get(hash) ?? Promise.resolve()).then(step, step);
const tail = done.catch(() => {});
turns.set(hash, tail);
void tail.then(() => turns.get(hash) === tail && turns.delete(hash));
return done;
};
const forget = (hash: string) =>
inTurn(hash, async () => {
if (pins.has(hash) || !sizes.has(hash)) return;
await rm(blobPath(dir, hash), { force: true });
total -= sizes.get(hash) ?? 0;
sizes.delete(hash);
});
const forgetAside = async (hash: string) => {
await rm(blobPath(asideDir, hash), { force: true });
asideSizes.delete(hash);
Expand All @@ -216,9 +234,12 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
await write();
});
// The bytes hashed are the bytes filed, so a write racing the read can never file bytes under the wrong hash.
const putBytes = async (bytes: Buffer, mode: number) => {
const putBytes = async (bytes: Buffer, mode: number, pinned: boolean) => {
const hash = sha256(bytes);
if (sizes.has(hash)) return hash;
return inTurn(hash, () => filedBytes(hash, bytes, mode, pinned));
};
const filedBytes = async (hash: string, bytes: Buffer, mode: number, pinned: boolean) => {
if (sizes.has(hash)) return pinned ? (pin(hash), hash) : hash;
const temp = join(dir, `incoming-${randomUUID()}`);
try {
await withFolderMadeIfMissing(dir, () => writeFile(temp, bytes, { mode }));
Expand All @@ -231,12 +252,18 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
throw error;
}
file(hash, bytes.length);
if (pinned) pin(hash);
return hash;
};

const putIfUnchanged = async (absPath: string): Promise<string | null> => {
const small = await readIfSmall(absPath);
if (small) return small.moved ? null : putBytes(small.bytes, small.mode);
const putIfUnchanged = async (
absPath: string,
pinned: boolean,
onRead: () => void,
): Promise<string | null> => {
const small = await readIfSmall(absPath, onRead);
if (small?.moved) return null;
if (small) return putBytes(small.bytes, small.mode, pinned);
// Hash the copy, not the source, so a write racing the copy can never file bytes under the wrong hash.
const temp = join(dir, `incoming-${randomUUID()}`);
// Recreated if removed while open, so a missing folder is never mistaken for a deleted project file.
Expand All @@ -252,22 +279,27 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
await rm(temp, { force: true });
return null;
}
onRead();
const hash = await hashFile(temp);
if (sizes.has(hash)) {
await rm(temp, { force: true });
return inTurn(hash, async () => {
if (sizes.has(hash)) {
await rm(temp, { force: true });
if (pinned) pin(hash);
return hash;
}
await mkdir(dirname(blobPath(dir, hash)), { recursive: true });
const size = (await stat(temp)).size;
await renameWithRetryAsync(temp, blobPath(dir, hash));
file(hash, size);
if (pinned) pin(hash);
return hash;
}
await mkdir(dirname(blobPath(dir, hash)), { recursive: true });
const size = (await stat(temp)).size;
await renameWithRetryAsync(temp, blobPath(dir, hash));
file(hash, size);
return hash;
});
};

return {
async put(absPath) {
async put(absPath, pinned = false, onRead = () => {}) {
for (let read = 0; read < READS_BEFORE_LEAVING_IT; read += 1) {
const hash = await putIfUnchanged(absPath);
const hash = await putIfUnchanged(absPath, pinned, onRead);
if (hash !== null) return hash;
}
return null;
Expand Down Expand Up @@ -314,6 +346,12 @@ export async function openBlobStore(dir: string): Promise<BlobStore> {
async drop(hashes) {
for (const hash of hashes) if (sizes.has(hash)) await forget(hash);
},
unpin(hash) {
const left = (pins.get(hash) ?? 0) - 1;
if (left > 0) pins.set(hash, left);
else pins.delete(hash);
},
pinned: () => pins.keys(),
async prune(keep) {
for (const hash of [...sizes.keys()]) if (!keep.has(hash)) await forget(hash);
for (const hash of [...asideSizes.keys()]) if (!keep.has(hash)) await forgetAside(hash);
Expand Down
Loading
Loading