Skip to content

Commit e14b44c

Browse files
author
hzq
committed
Coordinate worker attachment staging by manifest
Share preparation for matching inputs and keep the active manifest stable across invocation. Wait before changing attachment sets in the same session, and invalidate cached preparation when a write fails.
1 parent 013995f commit e14b44c

5 files changed

Lines changed: 448 additions & 72 deletions

File tree

‎docs/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,8 @@ 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.
386+
385387
## Node wire protocol
386388

387389
Opening a WebSocket is not node registration. The gateway allows one unfinished handshake per node ID and 64 per gateway; established workers do not count. At capacity or during node hub shutdown, a valid node credential receives HTTP 503 and can retry with backoff. The gateway closes any handshake still unfinished after five seconds. It sends `welcome` before making the worker available for dispatch. Workers also time out waiting for `welcome` after five seconds and reconnect with backoff; HTTP 401/403 still stops reconnect attempts.

‎docs/zh-CN/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,8 @@ MCP 桥接复用普通运行端点,不暴露 owner 管理员专用的 A2A 核
400400

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

403+
同一会话内,附件清单相同的并发调用可共用准备结果。不同清单等当前调用结束后再准备,避免运行中覆盖同名产物。会话目录及其路径不变。
404+
403405
<a id="node-wire-protocol"></a>
404406

405407
## 节点线协议(Node wire protocol)

‎src/fabric/session-workspaces.ts‎

Lines changed: 179 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
import { existsSync } from 'node:fs';
2+
import { mkdir } from 'node:fs/promises';
3+
import path from 'node:path';
4+
import type { WorkerConfig } from '../config/config.js';
5+
import { AbortableWait } from '../core/abortable-wait.js';
6+
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';
16+
17+
type Phase = {
18+
fingerprint: string;
19+
stage?: () => Promise<string>;
20+
users: number;
21+
state: 'queued' | 'staging' | 'settled';
22+
result: PromiseWithResolvers<string>;
23+
ready: AbortableWait<string>;
24+
};
25+
type Lane = { phases: Phase[]; idle: PromiseWithResolvers<void> };
26+
27+
/** Same manifests can use one session directory concurrently. A change waits for its old users. */
28+
export class SessionWorkspaces {
29+
private readonly lanes = new Map<string, Lane>();
30+
private readonly prepared = new Map<string, string>();
31+
private closing?: Promise<void>;
32+
33+
constructor(
34+
private readonly config: Pick<WorkerConfig, 'dataDir' | 'nodeId' | 'owner'>,
35+
private readonly write = writePrivate,
36+
) {}
37+
38+
async use<T>(context: WorkContext, signal: AbortSignal, run: (root: string) => Promise<T>) {
39+
checkAbort(signal);
40+
if (this.closing) throw new Fault('shutting_down', 'Worker is shutting down.', 503);
41+
const session = context.sessionId;
42+
if (
43+
typeof session !== 'string' ||
44+
!/^[A-Za-z0-9_-]+$/.test(session) ||
45+
context.owner !== this.config.owner
46+
)
47+
throw new Fault('invalid_context', 'Worker ownership or session does not match.', 403);
48+
const files = this.select(context.files);
49+
const fingerprint = sha(
50+
JSON.stringify(
51+
[...files]
52+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
53+
.map(([name, f]) => [name, f.id, f.sha256]),
54+
),
55+
);
56+
let lane = this.lanes.get(session);
57+
if (!lane) {
58+
lane = { phases: [], idle: Promise.withResolvers<void>() };
59+
this.lanes.set(session, lane);
60+
}
61+
let phase = lane.phases.at(-1);
62+
// Join only the last group; a new reader must not jump a different manifest already queued.
63+
if (!phase || phase.fingerprint !== fingerprint) {
64+
const result = Promise.withResolvers<string>();
65+
phase = {
66+
fingerprint,
67+
stage: () => this.stage(session, fingerprint, files),
68+
users: 0,
69+
state: 'queued',
70+
result,
71+
ready: new AbortableWait(result.promise),
72+
};
73+
lane.phases.push(phase);
74+
}
75+
phase.users++;
76+
this.advance(session, lane);
77+
try {
78+
const root = await phase.ready.wait(signal);
79+
checkAbort(signal);
80+
return await run(root);
81+
} finally {
82+
phase.users--;
83+
if (!phase.users && phase.state === 'queued') {
84+
lane.phases.splice(lane.phases.indexOf(phase), 1);
85+
phase.result.reject(abortError());
86+
}
87+
this.advance(session, lane);
88+
}
89+
}
90+
91+
private advance(session: string, lane: Lane): void {
92+
while (lane.phases[0]?.state === 'settled' && !lane.phases[0].users) lane.phases.shift();
93+
const head = lane.phases[0];
94+
if (!head) {
95+
this.lanes.delete(session);
96+
lane.idle.resolve();
97+
} else if (head.state === 'queued') {
98+
head.state = 'staging';
99+
const stage = head.stage!;
100+
head.stage = undefined;
101+
const settled = () => {
102+
head.state = 'settled';
103+
this.advance(session, lane);
104+
};
105+
void stage().then(
106+
(root) => {
107+
head.result.resolve(root);
108+
settled();
109+
},
110+
(error) => {
111+
head.result.reject(error);
112+
settled();
113+
},
114+
);
115+
}
116+
}
117+
118+
private select(files: FilePayload[]): Map<string, FilePayload> {
119+
// A later artifact at the same logical output path is the selected version, as on the wire.
120+
const selected = new Map(files.map((f) => [f.workspacePath ?? `inputs/${f.id}/${f.name}`, f]));
121+
for (const [name, file] of selected) {
122+
if (file.allowedNodes && !file.allowedNodes.includes(this.config.nodeId))
123+
throw new Fault('data_placement_denied', 'Input file cannot be sent to this node.', 403);
124+
if (
125+
typeof file.id !== 'string' ||
126+
!/^[A-Za-z0-9_-]+$/.test(file.id) ||
127+
(file.workspacePath !== undefined &&
128+
(typeof file.workspacePath !== 'string' || !file.workspacePath.startsWith('outputs/')))
129+
)
130+
throw new Fault('invalid_file', 'Invalid workspace file reference.');
131+
if (!file.workspacePath) relativeName(file.name);
132+
relativeName(name);
133+
}
134+
return selected;
135+
}
136+
137+
private async stage(
138+
session: string,
139+
fingerprint: string,
140+
files: Map<string, FilePayload>,
141+
): Promise<string> {
142+
const root = path.join(
143+
this.config.dataDir,
144+
'sessions',
145+
sha(this.config.owner).slice(0, 16),
146+
session,
147+
);
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);
151+
await mkdir(root, { recursive: true, mode: 0o700 });
152+
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.');
156+
try {
157+
await this.write(root, name, data, !file.workspacePath);
158+
} catch (error) {
159+
if (
160+
(error as NodeJS.ErrnoException).code !== 'EEXIST' ||
161+
sha(await readBounded(root, name)) !== file.sha256
162+
)
163+
throw error;
164+
}
165+
}
166+
this.prepared.set(session, fingerprint);
167+
if (this.prepared.size > 256) this.prepared.delete(this.prepared.keys().next().value!);
168+
return root;
169+
}
170+
171+
close(): Promise<void> {
172+
return (this.closing ??= this.drain());
173+
}
174+
175+
private async drain(): Promise<void> {
176+
await Promise.all([...this.lanes.values()].map((lane) => lane.idle.promise));
177+
this.prepared.clear();
178+
}
179+
}

‎src/fabric/worker.ts‎

Lines changed: 19 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { validateModelWork } from '../core/work-manifest.js';
44
import { executeNative, collectNativeArtifacts } from './native-executor.js';
55
import { ProjectWorkspaces } from './project-workspaces.js';
66
import { mkdir, readdir } from 'node:fs/promises';
7-
import { existsSync } from 'node:fs';
87
import { JsonSchemas } from '../core/schemas.js';
98
import { McpConnections, mcpConfigured, descriptorDigest, findMcpTool } from './mcp-connections.js';
109
import type { WorkerConfig } from '../config/config.js';
@@ -23,8 +22,9 @@ import {
2322
type WorkContext,
2423
} from '../core/contracts.js';
2524
import { builtin } from '../lang/bundle.js';
26-
import { WorkerBundles } from './worker-bundles.js';
25+
import { WorkerBundles, type InstalledBundle } from './worker-bundles.js';
2726
import { ReasoningWorkspaces } from './reasoning-workspaces.js';
27+
import { SessionWorkspaces } from './session-workspaces.js';
2828
import { createModelDriver, providerApiKey, type ModelDriver } from '../providers/models.js';
2929
import { validateProviderState } from '../providers/provider-state.js';
3030
import {
@@ -95,8 +95,7 @@ export class WorkerRuntime implements Executor {
9595
private driverVersions = new Map<string, string>();
9696
private mcpConnections: McpConnections;
9797
private ajv = new JsonSchemas();
98-
private workspaces = new Map<string, { fingerprint: string; root: string }>();
99-
private workspaceInFlight = new Map<string, Promise<string>>();
98+
private workspaces: SessionWorkspaces;
10099
/** OS sandbox for `sandbox`-level scripts; advertised only after its self-check passes. */
101100
readonly sandbox?: SandboxLauncher;
102101
/** Settles when the sandbox self-check has finished (immediately without a sandbox). */
@@ -108,6 +107,7 @@ export class WorkerRuntime implements Executor {
108107
options: { sandbox?: SandboxLauncher } = {},
109108
) {
110109
this.bundles = new WorkerBundles(path.join(config.dataDir, 'bundles'));
110+
this.workspaces = new SessionWorkspaces(config);
111111
this.modelCatalogs = new AgentModelCatalogs(config);
112112
this.projects = new ProjectWorkspaces(config.dataDir, config.owner);
113113
this.drivers = drivers;
@@ -312,86 +312,31 @@ export class WorkerRuntime implements Executor {
312312
install(raw: AgentBundle, signal?: AbortSignal): Promise<void> {
313313
return this.bundles.install(raw, signal);
314314
}
315-
private async workspace(context: WorkContext): Promise<string> {
316-
if (!/^[A-Za-z0-9_-]+$/.test(context.sessionId) || context.owner !== this.config.owner)
317-
throw new Fault('invalid_context', 'Worker ownership or session does not match.', 403);
318-
const selected = new Map(
319-
context.files.map((f) => [f.workspacePath ?? `inputs/${f.id}/${f.name}`, f]),
320-
);
321-
for (const file of selected.values()) {
322-
if (file.allowedNodes && !file.allowedNodes.includes(this.config.nodeId))
323-
throw new Fault('data_placement_denied', 'Input file cannot be sent to this node.', 403);
324-
if (
325-
!/^[a-zA-Z0-9_-]+$/.test(file.id) ||
326-
(file.workspacePath && !file.workspacePath.startsWith('outputs/'))
327-
)
328-
throw new Fault('invalid_file', 'Invalid workspace file reference.');
329-
}
330-
const sessionKey = `${context.owner}:${context.sessionId}`;
331-
const fingerprint = sha(
332-
[...selected.entries()]
333-
.sort(([a], [b]) => a.localeCompare(b))
334-
.map(([k, f]) => `${k}:${f.id}:${f.sha256}`)
335-
.join(';'),
336-
);
337-
const cached = this.workspaces.get(sessionKey);
338-
// A pruned workspace (oaa prune) is rebuilt instead of reused from the cache.
339-
if (cached && cached.fingerprint === fingerprint && existsSync(cached.root)) return cached.root;
340-
const inFlight = this.workspaceInFlight.get(sessionKey);
341-
if (inFlight) return inFlight;
342-
343-
const task = (async () => {
344-
const root = path.join(
345-
this.config.dataDir,
346-
'sessions',
347-
sha(context.owner).slice(0, 16),
348-
context.sessionId,
349-
);
350-
await mkdir(root, { recursive: true, mode: 0o700 });
351-
for (const file of selected.values()) {
352-
const data = Buffer.from(file.content, 'base64');
353-
if (sha(data) !== file.sha256)
354-
throw new Fault('file_integrity', 'Input file digest mismatch.');
355-
const name = file.workspacePath
356-
? relativeName(file.workspacePath)
357-
: `inputs/${file.id}/${relativeName(file.name)}`;
358-
try {
359-
await writePrivate(root, name, data, !file.workspacePath);
360-
} catch (error) {
361-
if (
362-
(error as NodeJS.ErrnoException).code !== 'EEXIST' ||
363-
sha(await readBounded(root, name)) !== file.sha256
364-
)
365-
throw error;
366-
}
367-
}
368-
this.workspaces.set(sessionKey, { fingerprint, root });
369-
if (this.workspaces.size > 256) {
370-
this.workspaces.delete(this.workspaces.keys().next().value!);
371-
}
372-
return root;
373-
})();
374-
375-
this.workspaceInFlight.set(sessionKey, task);
376-
try {
377-
return await task;
378-
} finally {
379-
this.workspaceInFlight.delete(sessionKey);
380-
}
381-
}
382315
lookupA2ATask(receipt: A2ATaskReceipt, signal: AbortSignal): Promise<A2ATaskObservation> {
383316
return lookupA2ATask(this.config, receipt, signal);
384317
}
385318
async execute(work: Work, signal: AbortSignal, emit: Emit): Promise<WorkResult> {
386319
checkAbort(signal);
320+
const workspaces = this.workspaces;
387321
const reasoning =
388322
work.kind === 'native' && work.toolsDisabled ? this.reasoningWorkspaces : undefined;
389323
const digest = work.context.digest;
390324
const bundle = this.bundles.cached(digest) ?? (await this.bundles.load(digest));
391325
checkAbort(signal);
392326
if (!bundle)
393327
throw new Fault('bundle_not_loaded', 'Required immutable bundle is not installed.', 409);
394-
const root = await this.workspace(work.context);
328+
return workspaces.use(work.context, signal, (root) =>
329+
this.runWork(work, bundle, root, signal, emit, reasoning),
330+
);
331+
}
332+
private async runWork(
333+
work: Work,
334+
bundle: InstalledBundle,
335+
root: string,
336+
signal: AbortSignal,
337+
emit: Emit,
338+
reasoning?: ReasoningWorkspaces,
339+
): Promise<WorkResult> {
395340
if (work.kind === 'model' || work.kind === 'native') {
396341
const agent = validateModelWork(bundle, work, this.modelCatalogs.snapshot());
397342
if (work.kind === 'native') {
@@ -726,12 +671,14 @@ export class WorkerRuntime implements Executor {
726671
}
727672
close(): Promise<void> {
728673
return (this.closing ??= this.closeResources().finally(() => {
674+
this.workspaces = new SessionWorkspaces(this.config);
729675
this.reasoningWorkspaces = new ReasoningWorkspaces();
730676
this.closing = undefined;
731677
}));
732678
}
733679
private async closeResources(): Promise<void> {
734680
try {
681+
await this.workspaces.close();
735682
await this.reasoningWorkspaces.close().finally(async () => {
736683
await this.modelCatalogs.close();
737684
await this.projects.ready;

0 commit comments

Comments
 (0)