Skip to content

Commit 6a6e213

Browse files
author
hzq
committed
Batch metadata checks for warm workspace attachments
Share root and parent observations in one preparation and recheck the directories before using the result. Fall back to individual checks for missing or changed paths without weakening digest validation or repair.
1 parent e670e11 commit 6a6e213

3 files changed

Lines changed: 150 additions & 6 deletions

File tree

‎src/fabric/session-workspaces.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,12 @@ import type { WorkerConfig } from '../config/config.js';
44
import { AbortableWait } from '../core/abortable-wait.js';
55
import type { FilePayload, WorkContext } from '../core/contracts.js';
66
import { abortError, checkAbort, Fault, relativeName, sha, writePrivate } from '../core/util.js';
7-
import { missing, verifiedWorkspaceFileStamp, workspaceFileStamp } from './workspace-file.js';
7+
import {
8+
matchesWorkspaceFiles,
9+
missing,
10+
verifiedWorkspaceFileStamp,
11+
workspaceFileStamp,
12+
} from './workspace-file.js';
813

914
type Phase = {
1015
fingerprint: string;
@@ -146,6 +151,10 @@ export class SessionWorkspaces {
146151
// A different manifest may change aliases even if its staging eventually fails.
147152
if (!warm) this.forget(session);
148153
await mkdir(root, { recursive: true, mode: 0o700 });
154+
if (warm && (await matchesWorkspaceFiles(root, warm.stamps))) {
155+
this.remember(session, warm);
156+
return root;
157+
}
149158
const stamps = new Map<string, string>();
150159
for (const [name, file] of files) {
151160
const stamp = warm

‎src/fabric/workspace-file.ts‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,65 @@
11
import { createHash } from 'node:crypto';
22
import { constants, type BigIntStats } from 'node:fs';
3-
import { lstat, open } from 'node:fs/promises';
3+
import { lstat, open, realpath } from 'node:fs/promises';
4+
import path from 'node:path';
45
import { LIMITS } from '../core/limits.js';
5-
import { Fault, safePath } from '../core/util.js';
6+
import { Fault, relativeName, safePath } from '../core/util.js';
67

78
export const missing = (error: unknown) => (error as NodeJS.ErrnoException)?.code === 'ENOENT';
89

910
const changed = () => new Fault('file_integrity', 'A prepared workspace file has changed.');
1011

12+
function stamp(stat: BigIntStats): string {
13+
return `${stat.dev}:${stat.ino}:${stat.birthtimeNs}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
14+
}
15+
1116
function fileStamp(stat: BigIntStats): string {
1217
if (!stat.isFile()) throw new Fault('invalid_file', 'Expected a regular workspace file.');
13-
return `${stat.dev}:${stat.ino}:${stat.birthtimeNs}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
18+
return stamp(stat);
19+
}
20+
21+
const invalidPath = () =>
22+
new Fault('invalid_path', 'Symlinks and non-directory parents are not allowed.');
23+
24+
async function directoryStamp(directory: string): Promise<string> {
25+
const current = await lstat(directory, { bigint: true });
26+
if (!current.isDirectory()) throw invalidPath();
27+
return stamp(current);
28+
}
29+
30+
/** Share path observations only within one activation. A changed tree falls back to fresh checks. */
31+
export async function matchesWorkspaceFiles(
32+
root: string,
33+
expected: ReadonlyMap<string, string>,
34+
): Promise<boolean> {
35+
// The second directory check is not worthwhile for small manifests.
36+
if (expected.size < 4) return false;
37+
try {
38+
const base = await realpath(root);
39+
const originalRoot = await directoryStamp(base);
40+
const parents = new Map<string, string>();
41+
for (const [name, previous] of expected) {
42+
const parts = relativeName(name).split('/');
43+
const leaf = parts.pop()!;
44+
let dirname = base;
45+
for (const part of parts) {
46+
dirname = path.join(dirname, part);
47+
if (!parents.has(dirname)) {
48+
if (parents.size >= 4096) return false;
49+
parents.set(dirname, await directoryStamp(dirname));
50+
}
51+
}
52+
const observed = await lstat(path.join(dirname, leaf), { bigint: true });
53+
if (observed.isSymbolicLink()) throw invalidPath();
54+
if (fileStamp(observed) !== previous) return false;
55+
}
56+
for (const [directory, before] of parents)
57+
if ((await directoryStamp(directory)) !== before) return false;
58+
return (await realpath(root)) === base && (await directoryStamp(base)) === originalRoot;
59+
} catch (error) {
60+
if (missing(error) || (error as NodeJS.ErrnoException)?.code === 'ENOTDIR') return false;
61+
throw error;
62+
}
1463
}
1564

1665
export async function workspaceFileStamp(root: string, name: string): Promise<string | undefined> {

‎test/workspace-file-cache.test.ts‎

Lines changed: 88 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import assert from 'node:assert/strict';
22
import { constants } from 'node:fs';
3-
import { mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises';
3+
import { mkdir, mkdtemp, readFile, rename, rm, symlink, utimes, writeFile } from 'node:fs/promises';
44
import { createRequire, syncBuiltinESMExports } from 'node:module';
55
import os from 'node:os';
66
import path from 'node:path';
@@ -39,6 +39,8 @@ test('a new worker phase restores missing declared files without rebuilding the
3939
const manifest = context([
4040
file('attached', 'input bytes'),
4141
file('prior_output', 'artifact bytes', alias),
42+
file('companion', 'companion bytes'),
43+
file('second_output', 'another artifact', 'outputs/another.txt'),
4244
]);
4345
const run = (name: string) =>
4446
worker.execute(
@@ -70,25 +72,45 @@ test('a new worker phase restores missing declared files without rebuilding the
7072
test('unchanged files require no read handle; a metadata change verifies just that file', async (t) => {
7173
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-witness-'));
7274
const workspaces = new SessionWorkspaces(config(base));
73-
const manifest = context([file('attached', 'first'), file('other', 'second')]);
75+
const manifest = context([
76+
file('attached', 'first'),
77+
file('other', 'second'),
78+
file('output', 'third', alias),
79+
file('output2', 'fourth', 'outputs/second.txt'),
80+
]);
7481
const fs = createRequire(import.meta.url)(
7582
'node:fs/promises',
7683
) as typeof import('node:fs/promises');
7784
const original = fs.open;
85+
const realpath = fs.realpath;
86+
const mkdir = fs.mkdir;
87+
let roots = 0;
88+
let creates = 0;
7889
const reads: string[] = [];
7990
const mocked = t.mock.method(fs, 'open', (...args: Parameters<typeof original>) => {
8091
const [target, flags] = args;
8192
if (typeof flags === 'number' && !(flags & (constants.O_WRONLY | constants.O_RDWR)))
8293
reads.push(String(target));
8394
return original(...args);
8495
});
96+
const resolved = t.mock.method(fs, 'realpath', (...args: Parameters<typeof realpath>) => {
97+
roots++;
98+
return realpath(...args);
99+
});
100+
const made = t.mock.method(fs, 'mkdir', (...args: Parameters<typeof mkdir>) => {
101+
creates++;
102+
return mkdir(...args);
103+
});
85104
syncBuiltinESMExports();
86105
const activate = () => workspaces.use(manifest, signal(), async (root) => root);
87106
try {
88107
const root = await activate();
89108
reads.length = 0;
109+
roots = creates = 0;
90110
assert.equal(await activate(), root);
91111
assert.deepEqual(reads, []);
112+
assert.equal(roots, 2, 'resolve the root once, then recheck it');
113+
assert.equal(creates, 1, 'do not repeat root preparation for each path');
92114
const touched = path.join(root, inputPath);
93115
await utimes(touched, new Date(), new Date('2020-01-01T00:00:00Z'));
94116
await activate();
@@ -101,12 +123,76 @@ test('unchanged files require no read handle; a metadata change verifies just th
101123
assert.deepEqual(reads, []);
102124
} finally {
103125
mocked.mock.restore();
126+
resolved.mock.restore();
127+
made.mock.restore();
104128
syncBuiltinESMExports();
105129
await workspaces.close();
106130
await rm(base, { recursive: true, force: true });
107131
}
108132
});
109133

134+
const batchFiles = () =>
135+
Array.from({ length: 4 }, (_, i) =>
136+
file(`output_${i}`, `fixture-${i}`, `outputs/nested/note-${i}.txt`),
137+
);
138+
139+
test('a parent replaced after the batch has seen its final leaf invalidates the shared observation', async (t) => {
140+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-parent-change-'));
141+
const workspaces = new SessionWorkspaces(config(base));
142+
const manifest = context(batchFiles());
143+
const fs = createRequire(import.meta.url)(
144+
'node:fs/promises',
145+
) as typeof import('node:fs/promises');
146+
const stat = fs.lstat;
147+
let changed = false;
148+
const root = await workspaces.use(manifest, signal(), async (root) => root);
149+
const directory = path.join(root, 'outputs', 'nested');
150+
const mocked = t.mock.method(fs, 'lstat', async (...args: Parameters<typeof stat>) => {
151+
const observed = await stat(...args);
152+
if (!changed && String(args[0]).endsWith(path.join('outputs', 'nested', 'note-3.txt'))) {
153+
changed = true;
154+
await rename(directory, directory + '-saved');
155+
await mkdir(directory);
156+
await writeFile(path.join(directory, 'note-0.txt'), 'new local bytes');
157+
}
158+
return observed;
159+
});
160+
syncBuiltinESMExports();
161+
try {
162+
await assert.rejects(
163+
workspaces.use(manifest, signal(), async () => assert.fail('old directory snapshot passed')),
164+
{ code: 'file_integrity' },
165+
);
166+
assert.equal(changed, true);
167+
assert.equal(await readFile(path.join(directory, 'note-0.txt'), 'utf8'), 'new local bytes');
168+
} finally {
169+
mocked.mock.restore();
170+
syncBuiltinESMExports();
171+
await workspaces.close();
172+
await rm(base, { recursive: true, force: true });
173+
}
174+
});
175+
176+
test('batched metadata checks do not follow a symbolic parent even to matching fixture files', async () => {
177+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-link-parent-'));
178+
const workspaces = new SessionWorkspaces(config(base));
179+
const manifest = context(batchFiles());
180+
try {
181+
const root = await workspaces.use(manifest, signal(), async (root) => root);
182+
const directory = path.join(root, 'outputs', 'nested');
183+
const saved = path.join(base, 'outside-session');
184+
await rename(directory, saved);
185+
await symlink(saved, directory, process.platform === 'win32' ? 'junction' : 'dir');
186+
await assert.rejects(
187+
workspaces.use(manifest, signal(), async () => assert.fail('linked parent passed')),
188+
{ code: 'invalid_path' },
189+
);
190+
} finally {
191+
await workspaces.close();
192+
await rm(base, { recursive: true, force: true });
193+
}
194+
});
195+
110196
for (const target of ['attachment', 'artifact'] as const)
111197
test(`an edited ${target} cannot execute or be silently overwritten on repeated activations`, async () => {
112198
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-edit-'));

0 commit comments

Comments
 (0)