Skip to content

Commit 952b3ea

Browse files
author
hzq
committed
Bound worker bundle residency with sealed cold manifests
Keep a bounded cache of verified manifests without installed file bodies. Restore evicted manifests by digest for already prepared dispatches, preserving installed files and the existing execution protocol.
1 parent 0472c37 commit 952b3ea

7 files changed

Lines changed: 381 additions & 30 deletions

File tree

‎docs/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,8 @@ Opening a WebSocket is not node registration. The gateway allows one unfinished
388388

389389
Worker retry delays grow exponentially with jitter and are capped at five seconds. A connection resets the delay only after the worker sends a heartbeat and receives an acknowledgement within the lease. `welcome` alone does not reset it.
390390

391+
Workers keep up to 128 parsed bundle manifests warm, with a 16 MiB budget measured on their compact JSON representation. Installed files are not retained in this cache. Before evicting a manifest, the worker seals it in private temporary storage using a key held only by that runtime. An already installed digest can be read back during the same worker lifetime without resending or repeating an execution. Closing the worker removes its temporary index, not the installed files.
392+
391393
If `welcome.features` includes `artifact-chunks-v1`, a worker may deliver an output over its existing execution lease. Each `artifact_chunk` carries the RPC `id`, `leaseId`, zero-based artifact `index`, byte `offset`, total `bytes`, `name`, SHA-256 `sha256` and base64 `data` (up to 128 KiB decoded). Wait for `artifact_ack` with the matching lease, index and offset before the next chunk. The final result references the matching manifest entry with `transferIndex` and empty `content`; a worker path is never a wire reference. An interrupted transfer is discarded, not automatically replayed.
392394

393395
### Node lifecycle control

‎docs/zh-CN/protocol.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,8 @@ WebSocket 已连接不等于节点注册完成。每个节点 ID 最多有 1 个
408408

409409
worker 的重试等待按指数增长,并加随机抖动,最长 5 秒。只有发送心跳、且在租约内收到回执后才重置等待时间;单独收到 `welcome` 不会重置。
410410

411+
worker 最多保留 128 份已解析的热清单,按精简后的 JSON 大小计量,预算为 16 MiB。缓存不保留已安装文件的正文。淘汰清单前,worker 用仅当前运行时持有的密钥将它加密存入私有临时目录。同一个 worker 运行期间可按摘要读回已安装清单,不重发或重做任务。worker 关闭时只移除自己的临时索引,不删除已安装文件。
412+
411413
若 `welcome.features` 含 `artifact-chunks-v1`,节点可通过当前执行租约回传文件。`artifact_chunk` 包含 RPC 的 `id`、`leaseId`、从零开始的产物序号 `index`、字节偏移 `offset`、总大小 `bytes`、`name`、`sha256` 和 Base64 编码的 `data`(解码后最多 128 KiB)。收到相同租约、序号和偏移的 `artifact_ack` 后才发送下一块。最终结果用 `transferIndex` 与空 `content` 引用对应文件,不传节点本机路径。传输中断将丢弃未确认数据,不自动重放任务。
412414

413415
<a id="node-lifecycle-control"></a>

‎src/core/work-manifest.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { canonical, Fault } from './util.js';
44

55
/** A discovered model may extend a route pool, never any other published authority. */
66
export function validateModelWork(
7-
bundle: AgentBundle,
7+
bundle: Pick<AgentBundle, 'agent'>,
88
work: Extract<Work, { kind: 'model' | 'native' }>,
99
catalogs: Record<string, ModelCatalog>,
1010
) {

‎src/fabric/worker-bundles.ts‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2+
import { mkdtemp, rename, rm } from 'node:fs/promises';
3+
import os from 'node:os';
4+
import path from 'node:path';
5+
import type { AgentBundle } from '../core/contracts.js';
6+
import { checkAbort, Fault, readBounded, writePrivate } from '../core/util.js';
7+
import { installBundle } from '../lang/bundle.js';
8+
9+
export const WORKER_WARM_BUNDLES = 128;
10+
export const WORKER_WARM_BUNDLE_BYTES = 16 * 1024 * 1024;
11+
const MAX_MANIFEST_BYTES = 12 * 1024 * 1024;
12+
const DIGEST = /^[a-f0-9]{64}$/;
13+
const NONCE_BYTES = 12;
14+
const TAG_BYTES = 16;
15+
16+
export type InstalledBundle = Pick<AgentBundle, 'digest' | 'agent'> & {
17+
files: Pick<AgentBundle['files'][number], 'path' | 'sha256'>[];
18+
};
19+
type Entry = { manifest: InstalledBundle; bytes: number; sealed: boolean };
20+
21+
/** Keep parsed manifests hot. Before eviction, preserve trust in private runtime scratch. */
22+
export class WorkerBundles {
23+
private readonly hot = new Map<string, Entry>();
24+
private readonly installing = new Map<string, Promise<void>>();
25+
private readonly reading = new Map<string, Promise<Entry | undefined>>();
26+
private key?: Buffer;
27+
private directory?: Promise<string>;
28+
private serialized = Promise.resolve();
29+
private closing?: Promise<void>;
30+
private bytes = 0;
31+
32+
constructor(
33+
private readonly bundleRoot: string,
34+
private readonly capacity = WORKER_WARM_BUNDLES,
35+
private readonly byteBudget = WORKER_WARM_BUNDLE_BYTES,
36+
) {}
37+
38+
warm(): string[] {
39+
// Report membership, not recency. Merely using a digest must not churn advertisements.
40+
return [...this.hot.keys()].sort();
41+
}
42+
43+
cached(digest: string): InstalledBundle | undefined {
44+
if (this.closing) return undefined;
45+
const entry = this.hot.get(digest);
46+
if (!entry) return undefined;
47+
this.hot.delete(digest);
48+
this.hot.set(digest, entry);
49+
return entry.manifest;
50+
}
51+
52+
async load(digest: string): Promise<InstalledBundle | undefined> {
53+
// An admitted dispatch can read cold data without having to evict another entry first.
54+
return (await this.read(digest))?.manifest;
55+
}
56+
57+
async install(raw: AgentBundle, signal?: AbortSignal): Promise<void> {
58+
if (signal) checkAbort(signal);
59+
if (this.closing) throw new Fault('shutting_down', 'Worker is shutting down.', 503);
60+
const digest = raw?.digest;
61+
if (!DIGEST.test(digest ?? '')) throw new Fault('bundle_integrity', 'Invalid bundle digest.');
62+
if (this.cached(digest)) return;
63+
let pending = this.installing.get(digest);
64+
if (!pending) {
65+
pending = this.prepare(digest, raw).finally(() => this.installing.delete(digest));
66+
this.installing.set(digest, pending);
67+
}
68+
await pending;
69+
if (signal) checkAbort(signal);
70+
}
71+
72+
private async prepare(digest: string, raw: AgentBundle): Promise<void> {
73+
const cold = await this.read(digest);
74+
if (cold) return this.admit(cold);
75+
const bundle = await installBundle(this.bundleRoot, raw);
76+
const manifest: InstalledBundle = {
77+
digest: bundle.digest,
78+
agent: bundle.agent,
79+
files: bundle.files.map(({ path, sha256 }) => ({ path, sha256 })),
80+
};
81+
await this.admit({
82+
manifest,
83+
bytes: Buffer.byteLength(JSON.stringify(manifest)),
84+
sealed: false,
85+
});
86+
}
87+
88+
private admit(entry: Entry): Promise<void> {
89+
const publish = this.serialized.then(async () => {
90+
if (entry.bytes > this.byteBudget) return this.spill(entry);
91+
while (this.hot.size >= this.capacity || this.bytes + entry.bytes > this.byteBudget) {
92+
const victim = this.hot.values().next().value!;
93+
// A failed spill leaves the installed copy live and the new install unacknowledged.
94+
await this.spill(victim);
95+
this.hot.delete(victim.manifest.digest);
96+
this.bytes -= victim.bytes;
97+
}
98+
this.hot.set(entry.manifest.digest, entry);
99+
this.bytes += entry.bytes;
100+
});
101+
this.serialized = publish.catch(() => {});
102+
return publish;
103+
}
104+
105+
private scratch(): Promise<string> {
106+
if (!this.directory) {
107+
this.directory = mkdtemp(path.join(os.tmpdir(), 'oaa-worker-manifests-')).catch((error) => {
108+
this.directory = undefined;
109+
throw error;
110+
});
111+
}
112+
return this.directory;
113+
}
114+
115+
private async spill(entry: Entry): Promise<void> {
116+
if (entry.sealed) return;
117+
const dir = await this.scratch();
118+
const digest = entry.manifest.digest;
119+
const nonce = randomBytes(NONCE_BYTES);
120+
const cipher = createCipheriv('aes-256-gcm', (this.key ??= randomBytes(32)), nonce);
121+
cipher.setAAD(Buffer.from(digest));
122+
const ciphertext = [cipher.update(JSON.stringify(entry.manifest), 'utf8'), cipher.final()];
123+
const stage = `${digest}.part`;
124+
try {
125+
await writePrivate(
126+
dir,
127+
stage,
128+
Buffer.concat([nonce, cipher.getAuthTag(), ...ciphertext]),
129+
true,
130+
);
131+
await rename(path.join(dir, stage), path.join(dir, digest));
132+
entry.sealed = true;
133+
} catch (error) {
134+
await rm(path.join(dir, stage), { force: true }).catch(() => {});
135+
throw error;
136+
}
137+
}
138+
139+
private async read(digest: string): Promise<Entry | undefined> {
140+
const directory = this.directory;
141+
if (this.closing || !DIGEST.test(digest) || !directory) return undefined;
142+
let pending = this.reading.get(digest);
143+
if (!pending) {
144+
pending = directory
145+
.then((dir) => this.open(dir, digest))
146+
.finally(() => this.reading.delete(digest));
147+
this.reading.set(digest, pending);
148+
}
149+
return pending;
150+
}
151+
152+
private async open(dir: string, digest: string): Promise<Entry | undefined> {
153+
const key = this.key;
154+
if (!key) return undefined;
155+
try {
156+
const data = await readBounded(dir, digest, MAX_MANIFEST_BYTES + NONCE_BYTES + TAG_BYTES);
157+
const decipher = createDecipheriv('aes-256-gcm', key, data.subarray(0, NONCE_BYTES));
158+
decipher.setAAD(Buffer.from(digest));
159+
decipher.setAuthTag(data.subarray(NONCE_BYTES, NONCE_BYTES + TAG_BYTES));
160+
const body = Buffer.concat([
161+
decipher.update(data.subarray(NONCE_BYTES + TAG_BYTES)),
162+
decipher.final(),
163+
]);
164+
return {
165+
manifest: JSON.parse(body.toString('utf8')) as InstalledBundle,
166+
bytes: body.length,
167+
sealed: true,
168+
};
169+
} catch (error) {
170+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;
171+
throw new Fault('bundle_integrity', 'The installed bundle manifest could not be verified.');
172+
}
173+
}
174+
175+
close(): Promise<void> {
176+
return (this.closing ??= this.cleanup().finally(() => (this.closing = undefined)));
177+
}
178+
179+
private async cleanup(): Promise<void> {
180+
await Promise.allSettled([...this.installing.values(), ...this.reading.values()]);
181+
this.hot.clear();
182+
this.bytes = 0;
183+
this.key?.fill(0);
184+
this.key = undefined;
185+
const dir = await this.directory?.catch(() => undefined);
186+
this.directory = undefined;
187+
if (dir) await rm(dir, { recursive: true, force: true });
188+
}
189+
}

‎src/fabric/worker.ts‎

Lines changed: 21 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ import {
2323
type WorkResult,
2424
type WorkContext,
2525
} from '../core/contracts.js';
26-
import { installBundle, builtin } from '../lang/bundle.js';
26+
import { builtin } from '../lang/bundle.js';
27+
import { WorkerBundles } from './worker-bundles.js';
2728
import { createModelDriver, providerApiKey, type ModelDriver } from '../providers/models.js';
2829
import { validateProviderState } from '../providers/provider-state.js';
2930
import {
@@ -87,8 +88,7 @@ export class WorkerRuntime implements Executor {
8788
private reasoningRoots = new Map<string, string>();
8889
/** Protocol timing bounds for ACP agents; tests shorten them. */
8990
acpTimings: AcpTimings = {};
90-
private bundles = new Map<string, AgentBundle>();
91-
private installing = new Map<string, Promise<void>>();
91+
private readonly bundles: WorkerBundles;
9292
private drivers = new Map<string, ModelDriver>();
9393
private providedDrivers: Set<string>;
9494
private driverVersions = new Map<string, string>();
@@ -106,6 +106,7 @@ export class WorkerRuntime implements Executor {
106106
drivers = new Map<string, ModelDriver>(),
107107
options: { sandbox?: SandboxLauncher } = {},
108108
) {
109+
this.bundles = new WorkerBundles(path.join(config.dataDir, 'bundles'));
109110
this.modelCatalogs = new AgentModelCatalogs(config);
110111
this.projects = new ProjectWorkspaces(config.dataDir, config.owner);
111112
this.drivers = drivers;
@@ -171,7 +172,7 @@ export class WorkerRuntime implements Executor {
171172
mcpReady.get(t.handler.server),
172173
)
173174
.map((t) => t.capability),
174-
warm: [...this.bundles.keys()].slice(-500),
175+
warm: this.bundles.warm(),
175176
concurrency: this.config.concurrency,
176177
execution: {
177178
agentPolicyVersion: 1,
@@ -307,23 +308,8 @@ export class WorkerRuntime implements Executor {
307308
400,
308309
);
309310
}
310-
async install(raw: AgentBundle, signal?: AbortSignal): Promise<void> {
311-
if (signal) checkAbort(signal);
312-
if (this.bundles.has(raw.digest)) return;
313-
let pending = this.installing.get(raw.digest);
314-
if (!pending) {
315-
pending = (async () => {
316-
const bundle = await installBundle(path.join(this.config.dataDir, 'bundles'), raw);
317-
this.bundles.set(bundle.digest, bundle);
318-
})();
319-
this.installing.set(raw.digest, pending);
320-
}
321-
try {
322-
await pending;
323-
if (signal) checkAbort(signal);
324-
} finally {
325-
this.installing.delete(raw.digest);
326-
}
311+
install(raw: AgentBundle, signal?: AbortSignal): Promise<void> {
312+
return this.bundles.install(raw, signal);
327313
}
328314
private async workspace(context: WorkContext): Promise<string> {
329315
if (!/^[A-Za-z0-9_-]+$/.test(context.sessionId) || context.owner !== this.config.owner)
@@ -397,7 +383,9 @@ export class WorkerRuntime implements Executor {
397383
}
398384
async execute(work: Work, signal: AbortSignal, emit: Emit): Promise<WorkResult> {
399385
checkAbort(signal);
400-
const bundle = this.bundles.get(work.context.digest);
386+
const digest = work.context.digest;
387+
const bundle = this.bundles.cached(digest) ?? (await this.bundles.load(digest));
388+
checkAbort(signal);
401389
if (!bundle)
402390
throw new Fault('bundle_not_loaded', 'Required immutable bundle is not installed.', 409);
403391
const root = await this.workspace(work.context);
@@ -738,12 +726,16 @@ export class WorkerRuntime implements Executor {
738726
return result;
739727
}
740728
async close(): Promise<void> {
741-
await this.modelCatalogs.close();
742-
await this.projects.ready;
743-
for (const root of this.reasoningRoots.values())
744-
await rm(root, { recursive: true, force: true });
745-
this.reasoningRoots.clear();
746-
await this.mcpConnections.close();
747-
await this.sandbox?.close();
729+
try {
730+
await this.modelCatalogs.close();
731+
await this.projects.ready;
732+
for (const root of this.reasoningRoots.values())
733+
await rm(root, { recursive: true, force: true });
734+
this.reasoningRoots.clear();
735+
await this.mcpConnections.close();
736+
await this.sandbox?.close();
737+
} finally {
738+
await this.bundles.close();
739+
}
748740
}
749741
}

‎test/transport-lifecycle.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { WebSocket, WebSocketServer } from 'ws';
88
import { workerSchema } from '../src/config/config.js';
99
import { capabilitySchema, type ToolBinding, type Work } from '../src/core/contracts.js';
1010
import { WorkerRuntime, type LocalHandler } from '../src/fabric/worker.js';
11+
import { WORKER_WARM_BUNDLES } from '../src/fabric/worker-bundles.js';
1112
import { connectWorker } from '../src/fabric/network.js';
1213
import { rejectNodeUpgrade } from '../src/fabric/node-connections.js';
1314
import { makeBundle } from '../src/lang/bundle.js';
@@ -83,6 +84,63 @@ async function remoteSetup(handler: LocalHandler, leaseMs = 1200, timeoutMs = 60
8384
};
8485
}
8586

87+
for (const phase of ['before dispatch', 'during invocation'] as const)
88+
test(`remote writes complete once when the installed bundle leaves the hot cache ${phase}`, async (t) => {
89+
const gate = Promise.withResolvers<void>();
90+
let calls = 0;
91+
const s = await remoteSetup(async () => {
92+
calls++;
93+
if (phase === 'during invocation') await gate.promise;
94+
return { value: 'finished' };
95+
}, 15_000);
96+
try {
97+
const { digest } = s.store.bundle(principal.owner, 'agent/test');
98+
const evict = async () => {
99+
assert.ok(s.remote.advertisement().warm.includes(digest));
100+
for (let i = 0; i < WORKER_WARM_BUNDLES; i++)
101+
await s.remote.install(
102+
makeBundle(agent({ description: `Different fixture package ${i}` })),
103+
);
104+
const warm = s.remote.advertisement().warm;
105+
assert.equal(warm.includes(digest), false);
106+
assert.equal(warm.length, WORKER_WARM_BUNDLES);
107+
};
108+
if (phase === 'before dispatch') {
109+
const execute = s.hub.execute.bind(s.hub);
110+
t.mock.method(s.hub, 'execute', (...args: Parameters<typeof execute>) => {
111+
if (args[0].kind === 'tool') {
112+
const before = args[4]?.onStart;
113+
args[4] = {
114+
...args[4],
115+
onStart: async (...startArgs) => {
116+
await before?.(...startArgs);
117+
await evict();
118+
assert.equal(calls, 0);
119+
},
120+
};
121+
}
122+
return execute(...args);
123+
});
124+
}
125+
const run = s.submit('cache pressure fixture');
126+
if (phase === 'during invocation') {
127+
await waitFor(() => calls === 1);
128+
await evict();
129+
gate.resolve();
130+
}
131+
const result = await s.kernel.wait(run.id, false, AbortSignal.timeout(10_000));
132+
assert.equal(result.status, 'completed', JSON.stringify(result.error));
133+
assert.equal(calls, 1);
134+
assert.equal(
135+
s.store.history(run.id).filter((event) => event.type === 'tool.started').length,
136+
1,
137+
);
138+
} finally {
139+
gate.resolve();
140+
await s.cleanup();
141+
}
142+
});
143+
86144
test('remote cancellation retains the occupied slot until the tool has actually exited', async () => {
87145
const gate = Promise.withResolvers<void>();
88146
let active = 0;

0 commit comments

Comments
 (0)