Skip to content

Commit e670e11

Browse files
author
hzq
committed
Revalidate cached workspace attachment manifests
Check the staged file identities before reusing a prepared manifest. Restore missing files exclusively from the authorized bytes, and verify changed or freshly written files without overwriting an unexpected replacement.
1 parent e14b44c commit e670e11

5 files changed

Lines changed: 305 additions & 28 deletions

File tree

‎docs/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,7 @@ Portable tool and skill bindings belong to kernel agents. Native/external agents
382382

383383
Built-in `read_skill` exposes only files from the immutable selected bundle. Built-in file tools reject traversal/symlinks and operate in the session workspace. Inputs appear at `inputs/<file_id>/<filename>` and artifacts at `outputs/<filename>`.
384384

385-
Concurrent calls in a session can share preparation for the same attachment manifest. Staging a different manifest waits for the current users before replacing an output alias. The session directory and its paths do not change.
385+
Concurrent calls in a session can share preparation for the same attachment manifest. Staging a different manifest waits for the current users before replacing an output alias. A new use of a cached manifest checks its declared files before dispatch: missing files are restored from the authorized payload, and changed metadata requires a digest check. A mismatched file is not overwritten by cache repair. The session directory and its paths do not change.
386386

387387
## Node wire protocol
388388

‎docs/zh-CN/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -400,7 +400,7 @@ MCP 桥接复用普通运行端点,不暴露 owner 管理员专用的 A2A 核
400400

401401
内置的 `read_skill` 只暴露选中的不可变能力包里的文件。内置文件工具拒绝目录穿越/符号链接,并在会话工作区里运行。输入出现在 `inputs/<file_id>/<filename>`,产物在 `outputs/<filename>`。
402402

403-
同一会话内,附件清单相同的并发调用可共用准备结果。不同清单等当前调用结束后再准备,避免运行中覆盖同名产物。会话目录及其路径不变。
403+
同一会话内,附件清单相同的并发调用可共用准备结果。不同清单等当前调用结束后再准备,避免运行中覆盖同名产物。重新使用已缓存的清单时,派发前会核对声明的文件:缺失文件从已授权的附件补回,元数据变化的文件重新核对摘要。缓存修复不会覆盖摘要不符的文件。会话目录及其路径不变。
404404

405405
<a id="node-wire-protocol"></a>
406406

‎src/fabric/session-workspaces.ts‎

Lines changed: 65 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
1-
import { existsSync } from 'node:fs';
21
import { mkdir } from 'node:fs/promises';
32
import path from 'node:path';
43
import type { WorkerConfig } from '../config/config.js';
54
import { AbortableWait } from '../core/abortable-wait.js';
65
import type { FilePayload, WorkContext } from '../core/contracts.js';
7-
import {
8-
abortError,
9-
checkAbort,
10-
Fault,
11-
readBounded,
12-
relativeName,
13-
sha,
14-
writePrivate,
15-
} from '../core/util.js';
6+
import { abortError, checkAbort, Fault, relativeName, sha, writePrivate } from '../core/util.js';
7+
import { missing, verifiedWorkspaceFileStamp, workspaceFileStamp } from './workspace-file.js';
168

179
type Phase = {
1810
fingerprint: string;
@@ -23,11 +15,15 @@ type Phase = {
2315
ready: AbortableWait<string>;
2416
};
2517
type Lane = { phases: Phase[]; idle: PromiseWithResolvers<void> };
18+
type Prepared = { fingerprint: string; stamps: Map<string, string> };
19+
const PREPARED_SESSIONS = 256;
20+
const PREPARED_FILES = 4096;
2621

2722
/** Same manifests can use one session directory concurrently. A change waits for its old users. */
2823
export class SessionWorkspaces {
2924
private readonly lanes = new Map<string, Lane>();
30-
private readonly prepared = new Map<string, string>();
25+
private readonly prepared = new Map<string, Prepared>();
26+
private preparedFiles = 0;
3127
private closing?: Promise<void>;
3228

3329
constructor(
@@ -145,27 +141,69 @@ export class SessionWorkspaces {
145141
sha(this.config.owner).slice(0, 16),
146142
session,
147143
);
148-
if (this.prepared.get(session) === fingerprint && existsSync(root)) return root;
149-
// If staging fails partway, no prior fingerprint may stand in for the resulting directory.
150-
this.prepared.delete(session);
144+
const previous = this.prepared.get(session);
145+
const warm = previous?.fingerprint === fingerprint ? previous : undefined;
146+
// A different manifest may change aliases even if its staging eventually fails.
147+
if (!warm) this.forget(session);
151148
await mkdir(root, { recursive: true, mode: 0o700 });
149+
const stamps = new Map<string, string>();
152150
for (const [name, file] of files) {
153-
const data = Buffer.from(file.content, 'base64');
154-
if (sha(data) !== file.sha256)
155-
throw new Fault('file_integrity', 'Input file digest mismatch.');
151+
const stamp = warm
152+
? await this.revalidate(root, name, file, warm.stamps.get(name))
153+
: await this.materialize(root, name, file, !file.workspacePath);
154+
if (files.size <= PREPARED_FILES) stamps.set(name, stamp);
155+
}
156+
if (files.size <= PREPARED_FILES) this.remember(session, { fingerprint, stamps });
157+
return root;
158+
}
159+
160+
private async revalidate(
161+
root: string,
162+
name: string,
163+
file: FilePayload,
164+
previous?: string,
165+
): Promise<string> {
166+
const observed = await workspaceFileStamp(root, name);
167+
if (observed !== undefined) {
168+
if (observed === previous) return observed;
156169
try {
157-
await this.write(root, name, data, !file.workspacePath);
170+
return await verifiedWorkspaceFileStamp(root, name, file.sha256);
158171
} catch (error) {
159-
if (
160-
(error as NodeJS.ErrnoException).code !== 'EEXIST' ||
161-
sha(await readBounded(root, name)) !== file.sha256
162-
)
163-
throw error;
172+
if (!missing(error)) throw error;
164173
}
165174
}
166-
this.prepared.set(session, fingerprint);
167-
if (this.prepared.size > 256) this.prepared.delete(this.prepared.keys().next().value!);
168-
return root;
175+
// Repair an absent path only. A concurrent replacement must pass verification, not be erased.
176+
return this.materialize(root, name, file, true);
177+
}
178+
179+
private async materialize(
180+
root: string,
181+
name: string,
182+
file: FilePayload,
183+
exclusive: boolean,
184+
): Promise<string> {
185+
const data = Buffer.from(file.content, 'base64');
186+
if (sha(data) !== file.sha256) throw new Fault('file_integrity', 'Input file digest mismatch.');
187+
try {
188+
await this.write(root, name, data, exclusive);
189+
} catch (error) {
190+
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
191+
}
192+
// Read back materialized bytes once. A pathname stat alone cannot prove a completed write.
193+
return verifiedWorkspaceFileStamp(root, name, file.sha256);
194+
}
195+
196+
private forget(session: string): void {
197+
this.preparedFiles -= this.prepared.get(session)?.stamps.size ?? 0;
198+
this.prepared.delete(session);
199+
}
200+
201+
private remember(session: string, prepared: Prepared): void {
202+
this.forget(session);
203+
this.prepared.set(session, prepared);
204+
this.preparedFiles += prepared.stamps.size;
205+
while (this.prepared.size > PREPARED_SESSIONS || this.preparedFiles > PREPARED_FILES)
206+
this.forget(this.prepared.keys().next().value!);
169207
}
170208

171209
close(): Promise<void> {
@@ -175,5 +213,6 @@ export class SessionWorkspaces {
175213
private async drain(): Promise<void> {
176214
await Promise.all([...this.lanes.values()].map((lane) => lane.idle.promise));
177215
this.prepared.clear();
216+
this.preparedFiles = 0;
178217
}
179218
}

‎src/fabric/workspace-file.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { createHash } from 'node:crypto';
2+
import { constants, type BigIntStats } from 'node:fs';
3+
import { lstat, open } from 'node:fs/promises';
4+
import { LIMITS } from '../core/limits.js';
5+
import { Fault, safePath } from '../core/util.js';
6+
7+
export const missing = (error: unknown) => (error as NodeJS.ErrnoException)?.code === 'ENOENT';
8+
9+
const changed = () => new Fault('file_integrity', 'A prepared workspace file has changed.');
10+
11+
function fileStamp(stat: BigIntStats): string {
12+
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}`;
14+
}
15+
16+
export async function workspaceFileStamp(root: string, name: string): Promise<string | undefined> {
17+
try {
18+
const target = await safePath(root, name);
19+
return fileStamp(await lstat(target, { bigint: true }));
20+
} catch (error) {
21+
if (missing(error)) return undefined;
22+
throw error;
23+
}
24+
}
25+
26+
/** Bind a verified digest to one opened file, not to a later lookup of its name. */
27+
export async function verifiedWorkspaceFileStamp(
28+
root: string,
29+
name: string,
30+
digest: string,
31+
): Promise<string> {
32+
const target = await safePath(root, name);
33+
const handle = await open(
34+
target,
35+
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
36+
);
37+
try {
38+
const before = await handle.stat({ bigint: true });
39+
const stamp = fileStamp(before);
40+
if (before.size > BigInt(LIMITS.workspaceTransferBytes)) throw changed();
41+
const hash = createHash('sha256');
42+
const chunk = Buffer.allocUnsafe(64 * 1024);
43+
let offset = 0;
44+
for (;;) {
45+
const { bytesRead } = await handle.read(chunk, 0, chunk.length, offset);
46+
if (!bytesRead) break;
47+
offset += bytesRead;
48+
if (offset > LIMITS.workspaceTransferBytes) throw changed();
49+
hash.update(chunk.subarray(0, bytesRead));
50+
}
51+
if (
52+
hash.digest('hex') !== digest ||
53+
stamp !== fileStamp(await handle.stat({ bigint: true })) ||
54+
stamp !== (await workspaceFileStamp(root, name))
55+
)
56+
throw changed();
57+
return stamp;
58+
} finally {
59+
await handle.close();
60+
}
61+
}

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

Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
import assert from 'node:assert/strict';
2+
import { constants } from 'node:fs';
3+
import { mkdtemp, readFile, rm, utimes, writeFile } from 'node:fs/promises';
4+
import { createRequire, syncBuiltinESMExports } from 'node:module';
5+
import os from 'node:os';
6+
import path from 'node:path';
7+
import test from 'node:test';
8+
import { workerSchema } from '../src/config/config.js';
9+
import type { FilePayload, WorkContext } from '../src/core/contracts.js';
10+
import { sha, writePrivate } from '../src/core/util.js';
11+
import { SessionWorkspaces } from '../src/fabric/session-workspaces.js';
12+
import { WorkerRuntime } from '../src/fabric/worker.js';
13+
import { builtin, makeBundle } from '../src/lang/bundle.js';
14+
import { agent } from './helpers.js';
15+
16+
const alias = 'outputs/result.txt';
17+
const inputPath = 'inputs/attached/note.txt';
18+
const signal = () => new AbortController().signal;
19+
const config = (dataDir: string) => workerSchema.parse({ dataDir, nodeId: 'cache-fixture' });
20+
function file(id: string, text: string, workspacePath?: string): FilePayload {
21+
const bytes = Buffer.from(text);
22+
return {
23+
id,
24+
name: 'note.txt',
25+
content: bytes.toString('base64'),
26+
sha256: sha(bytes),
27+
workspacePath,
28+
};
29+
}
30+
function context(files: FilePayload[]): WorkContext {
31+
return { files, owner: 'owner', sessionId: 'same', runId: 'resp_fixture', digest: 'fixture' };
32+
}
33+
34+
test('a new worker phase restores missing declared files without rebuilding the session or dropping its other files', async () => {
35+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-missing-'));
36+
const worker = new WorkerRuntime(config(base));
37+
const binding = builtin('read_file');
38+
const bundle = makeBundle(agent({ tools: [binding] }));
39+
const manifest = context([
40+
file('attached', 'input bytes'),
41+
file('prior_output', 'artifact bytes', alias),
42+
]);
43+
const run = (name: string) =>
44+
worker.execute(
45+
{
46+
kind: 'tool',
47+
binding,
48+
arguments: { path: name },
49+
context: { ...manifest, digest: bundle.digest },
50+
},
51+
signal(),
52+
async () => {},
53+
);
54+
try {
55+
await worker.install(bundle);
56+
assert.deepEqual(await run(inputPath), { value: { text: 'input bytes' } });
57+
const root = path.join(base, 'sessions', sha('owner').slice(0, 16), manifest.sessionId);
58+
await writeFile(path.join(root, 'unrelated.txt'), 'keep');
59+
await rm(path.join(root, inputPath));
60+
assert.deepEqual(await run(inputPath), { value: { text: 'input bytes' } });
61+
await rm(path.join(root, alias));
62+
assert.deepEqual(await run(alias), { value: { text: 'artifact bytes' } });
63+
assert.equal(await readFile(path.join(root, 'unrelated.txt'), 'utf8'), 'keep');
64+
} finally {
65+
await worker.close();
66+
await rm(base, { recursive: true, force: true });
67+
}
68+
});
69+
70+
test('unchanged files require no read handle; a metadata change verifies just that file', async (t) => {
71+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-witness-'));
72+
const workspaces = new SessionWorkspaces(config(base));
73+
const manifest = context([file('attached', 'first'), file('other', 'second')]);
74+
const fs = createRequire(import.meta.url)(
75+
'node:fs/promises',
76+
) as typeof import('node:fs/promises');
77+
const original = fs.open;
78+
const reads: string[] = [];
79+
const mocked = t.mock.method(fs, 'open', (...args: Parameters<typeof original>) => {
80+
const [target, flags] = args;
81+
if (typeof flags === 'number' && !(flags & (constants.O_WRONLY | constants.O_RDWR)))
82+
reads.push(String(target));
83+
return original(...args);
84+
});
85+
syncBuiltinESMExports();
86+
const activate = () => workspaces.use(manifest, signal(), async (root) => root);
87+
try {
88+
const root = await activate();
89+
reads.length = 0;
90+
assert.equal(await activate(), root);
91+
assert.deepEqual(reads, []);
92+
const touched = path.join(root, inputPath);
93+
await utimes(touched, new Date(), new Date('2020-01-01T00:00:00Z'));
94+
await activate();
95+
assert.deepEqual(
96+
reads.map((name) => path.basename(path.dirname(name))),
97+
['attached'],
98+
);
99+
reads.length = 0;
100+
await activate();
101+
assert.deepEqual(reads, []);
102+
} finally {
103+
mocked.mock.restore();
104+
syncBuiltinESMExports();
105+
await workspaces.close();
106+
await rm(base, { recursive: true, force: true });
107+
}
108+
});
109+
110+
for (const target of ['attachment', 'artifact'] as const)
111+
test(`an edited ${target} cannot execute or be silently overwritten on repeated activations`, async () => {
112+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-edit-'));
113+
const workspaces = new SessionWorkspaces(config(base));
114+
const isAlias = target === 'artifact';
115+
const manifest = context([file('attached', 'version-A', isAlias ? alias : undefined)]);
116+
try {
117+
const root = await workspaces.use(manifest, signal(), async (root) => root);
118+
const name = path.join(root, isAlias ? alias : inputPath);
119+
await writeFile(name, 'version-B');
120+
await utimes(name, new Date(), new Date('2020-01-01T00:00:00Z'));
121+
for (let i = 0; i < 2; i++)
122+
await assert.rejects(
123+
workspaces.use(manifest, signal(), async () => assert.fail('unverified operation ran')),
124+
{ code: 'file_integrity' },
125+
);
126+
assert.equal(await readFile(name, 'utf8'), 'version-B');
127+
} finally {
128+
await workspaces.close();
129+
await rm(base, { recursive: true, force: true });
130+
}
131+
});
132+
133+
test('a new file at a missing alias is not overwritten while repair is opening the path', async () => {
134+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-repair-race-'));
135+
let repairing = false;
136+
const workspaces = new SessionWorkspaces(config(base), async (...args) => {
137+
const [root, name, , exclusive] = args;
138+
if (repairing) {
139+
assert.equal(exclusive, true);
140+
await writePrivate(root, name, 'new on-disk bytes', true);
141+
}
142+
return writePrivate(...args);
143+
});
144+
const manifest = context([file('attached', 'original', alias)]);
145+
try {
146+
const root = await workspaces.use(manifest, signal(), async (root) => root);
147+
await rm(path.join(root, alias));
148+
repairing = true;
149+
await assert.rejects(
150+
workspaces.use(manifest, signal(), async () => assert.fail('replacement passed')),
151+
{ code: 'file_integrity' },
152+
);
153+
assert.equal(await readFile(path.join(root, alias), 'utf8'), 'new on-disk bytes');
154+
} finally {
155+
await workspaces.close();
156+
await rm(base, { recursive: true, force: true });
157+
}
158+
});
159+
160+
test('a materialized path is not acknowledged if its bytes change before staging completes', async () => {
161+
const base = await mkdtemp(path.join(os.tmpdir(), 'oaa-prepared-write-race-'));
162+
const workspaces = new SessionWorkspaces(config(base), async (...args) => {
163+
await writePrivate(...args);
164+
await writeFile(path.join(args[0], args[1]), 'different');
165+
});
166+
try {
167+
await assert.rejects(
168+
workspaces.use(context([file('attached', 'original')]), signal(), async () =>
169+
assert.fail('changed bytes passed'),
170+
),
171+
{ code: 'file_integrity' },
172+
);
173+
} finally {
174+
await workspaces.close();
175+
await rm(base, { recursive: true, force: true });
176+
}
177+
});

0 commit comments

Comments
 (0)