Skip to content

Commit c62251f

Browse files
authored
perf(workers): reuse validated hashes during workspace activation (#134026)
* perf(workers): reuse validated workspace hashes * test(ui): release chat media fixture subscriptions
1 parent 61b5da5 commit c62251f

7 files changed

Lines changed: 188 additions & 69 deletions

File tree

‎src/gateway/worker-environments/workspace-actual-manifest.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export async function readWorkspaceFileSnapshotWithLimit(
5858
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
5959
);
6060
try {
61-
const { memo: hashMemo, metrics } = activeWorkspaceHashContext() ?? {};
61+
const { memo: hashMemo, metrics, owner = "gateway" } = activeWorkspaceHashContext() ?? {};
6262
const before = await handle.stat({ bigint: true });
6363
const realPath = await resolveOpenedFileRealPathForHandle(handle, expectedPath);
6464
if (!before.isFile() || (root && !isPathInside(root, realPath))) {
@@ -67,7 +67,7 @@ export async function readWorkspaceFileSnapshotWithLimit(
6767
if (before.size > BigInt(maxBytes)) {
6868
return { type: "unsupported" };
6969
}
70-
const identity = workspaceStatIdentity("gateway", before);
70+
const identity = workspaceStatIdentity(owner, before);
7171
let sha256 = hashMemo?.get(identity);
7272
let size = Number(before.size);
7373
if (sha256) {
@@ -97,7 +97,7 @@ export async function readWorkspaceFileSnapshotWithLimit(
9797
}
9898
}
9999
const after = await handle.stat({ bigint: true });
100-
if (after.size !== BigInt(size) || workspaceStatIdentity("gateway", after) !== identity) {
100+
if (after.size !== BigInt(size) || workspaceStatIdentity(owner, after) !== identity) {
101101
throw new Error("Gateway workspace file changed while it was being read");
102102
}
103103
hashMemo?.set(identity, sha256);

‎src/gateway/worker-environments/workspace-hash-memo.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
recordRemoteWorkspaceHashMetrics,
1212
serializeRemoteWorkspaceHashMemo,
1313
withWorkspaceHashMemo,
14+
withWorkerWorkspaceHashMemo,
1415
type WorkspaceHashMemo,
1516
} from "./workspace-hash-memo.js";
1617
import { MAX_RECONCILIATION_ENTRIES, type WorkerWorkspaceManifest } from "./workspace-manifest.js";
@@ -191,6 +192,11 @@ describe("workspace hash memo", () => {
191192
);
192193
expect(envelopeBytes).toBeLessThan(MAX_WORKSPACE_HASH_MEMO_BYTES);
193194
expect(MAX_WORKSPACE_HASH_MEMO_BYTES - envelopeBytes).toBeGreaterThan(3 * 1024 * 1024);
195+
const smallFile = "worker:0:0:1:0:0";
196+
memo.set(smallFile, "c".repeat(64));
197+
const bounded = JSON.parse(serializeRemoteWorkspaceHashMemo(memo)) as [string, string][];
198+
expect(bounded).toHaveLength(MAX_RECONCILIATION_ENTRIES);
199+
expect(bounded.some(([identity]) => identity === smallFile)).toBe(false);
194200
});
195201

196202
it("reuses hashes only for matching stat identities in one remote reconcile", async () => {
@@ -218,6 +224,13 @@ describe("workspace hash memo", () => {
218224

219225
const first = await capture([]);
220226
expect(first.metrics).toMatchObject({ contentHashCount: 1, memoHitCount: 0 });
227+
const nodeMemo: WorkspaceHashMemo = new Map();
228+
await withWorkerWorkspaceHashMemo(nodeMemo, () =>
229+
readActualWorkspaceManifest({ root: workspace, baseCommit: null }),
230+
);
231+
const nodeValidated = await capture([...nodeMemo]);
232+
expect(nodeValidated.manifestRef).toBe(first.manifestRef);
233+
expect(nodeValidated.metrics).toMatchObject({ contentHashCount: 0, memoHitCount: 1 });
221234
const unchanged = await capture(first.memo);
222235
expect(unchanged.manifestRef).toBe(first.manifestRef);
223236
expect(unchanged.metrics).toMatchObject({ contentHashCount: 0, memoHitCount: 1 });
@@ -238,6 +251,17 @@ describe("workspace hash memo", () => {
238251
const nextReconcile = await capture([]);
239252
expect(nextReconcile.manifestRef).toBe(replaced.manifestRef);
240253
expect(nextReconcile.metrics).toMatchObject({ contentHashCount: 1, memoHitCount: 0 });
254+
255+
await fs.chmod(target, 0o755);
256+
const executable = await capture(replaced.memo);
257+
if (process.platform !== "win32") {
258+
expect(executable.manifestRef).not.toBe(replaced.manifestRef);
259+
}
260+
await fs.unlink(target);
261+
await fs.symlink("other.txt", target);
262+
const symlink = await capture(executable.memo);
263+
expect(symlink.manifestRef).not.toBe(executable.manifestRef);
264+
expect(symlink.metrics).toMatchObject({ contentHashCount: 0, memoHitCount: 0 });
241265
});
242266

243267
it("bounds the remote memo to the largest files and reports truncation", async () => {

‎src/gateway/worker-environments/workspace-hash-memo.ts‎

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ export function replaceWorkerWorkspaceHashMemoEntries(
8080
type WorkspaceHashContext = {
8181
memo: WorkspaceHashMemo;
8282
metrics?: WorkspaceHashMetrics;
83+
owner: "gateway" | "worker";
8384
};
8485

8586
const workspaceHashContext = new AsyncLocalStorage<WorkspaceHashContext>();
@@ -116,7 +117,18 @@ export async function withWorkspaceHashMemo<T>(
116117
if (active?.memo === memo && active.metrics === inheritedMetrics) {
117118
return await operation();
118119
}
119-
return await workspaceHashContext.run({ memo, metrics: inheritedMetrics }, operation);
120+
return await workspaceHashContext.run(
121+
{ memo, metrics: inheritedMetrics, owner: active?.owner ?? "gateway" },
122+
operation,
123+
);
124+
}
125+
126+
/** Shares hashes validated on the node with its final manifest capture. */
127+
export async function withWorkerWorkspaceHashMemo<T>(
128+
memo: WorkspaceHashMemo,
129+
operation: () => Promise<T>,
130+
): Promise<T> {
131+
return await workspaceHashContext.run({ memo, owner: "worker" }, operation);
120132
}
121133

122134
export async function withWorkspaceHashContext<T>(operation: () => Promise<T>): Promise<T> {
@@ -151,16 +163,41 @@ export function takeWorkspaceHashMemo(
151163
return memo;
152164
}
153165

166+
/** Self-contained for the node script; preserve the largest hashes within both wire limits. */
167+
export function selectWorkerWorkspaceHashMemoEntries(
168+
memo: ReadonlyMap<string, string>,
169+
maxEntries: number,
170+
maxBytes: number,
171+
): Array<[string, string]> {
172+
const compareIdentity = ([left]: [string, string], [right]: [string, string]) =>
173+
left < right ? -1 : left > right ? 1 : 0;
174+
const candidates = [...memo]
175+
.filter(([identity]) => identity.startsWith("worker:"))
176+
.map((entry) => ({ entry, size: Number(entry[0].split(":")[3]) }))
177+
.toSorted((left, right) => right.size - left.size || compareIdentity(left.entry, right.entry));
178+
const selected: Array<[string, string]> = [];
179+
let bytes = 2;
180+
for (const { entry } of candidates) {
181+
if (selected.length === maxEntries) {
182+
break;
183+
}
184+
const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + (selected.length > 0 ? 1 : 0);
185+
if (bytes + entryBytes <= maxBytes) {
186+
selected.push(entry);
187+
bytes += entryBytes;
188+
}
189+
}
190+
return selected.toSorted(compareIdentity);
191+
}
192+
154193
export function serializeRemoteWorkspaceHashMemo(memo: WorkspaceHashMemo): string {
155-
const serialized = JSON.stringify(
156-
[...memo]
157-
.filter(([identity]) => identity.startsWith("worker:"))
158-
.toSorted(([left], [right]) => left.localeCompare(right)),
194+
return JSON.stringify(
195+
selectWorkerWorkspaceHashMemoEntries(
196+
memo,
197+
MAX_RECONCILIATION_ENTRIES,
198+
MAX_WORKSPACE_HASH_MEMO_BYTES,
199+
),
159200
);
160-
if (Buffer.byteLength(serialized) > MAX_WORKSPACE_HASH_MEMO_BYTES) {
161-
throw new Error("Workspace hash memo exceeds its byte limit");
162-
}
163-
return serialized;
164201
}
165202

166203
export function recordRemoteWorkspaceHashMetrics(

‎src/gateway/worker-environments/workspace-sync-scripts.ts‎

Lines changed: 12 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { STAGED_INPUT_GIT_PATHSPEC } from "../../media/staged-inputs.js";
2-
import { MAX_WORKSPACE_HASH_MEMO_BYTES, workspaceStatIdentity } from "./workspace-hash-memo.js";
2+
import {
3+
MAX_WORKSPACE_HASH_MEMO_BYTES,
4+
selectWorkerWorkspaceHashMemoEntries,
5+
workspaceStatIdentity,
6+
} from "./workspace-hash-memo.js";
37
import {
48
MAX_WORKSPACE_GIT_CANDIDATES,
59
MAX_WORKSPACE_INVENTORY_ENTRIES,
@@ -74,8 +78,9 @@ const fs = require("node:fs");
7478
const path = require("node:path");
7579
${WORKSPACE_PATH_EXCLUSIONS_JS}
7680
const workspaceStatIdentity = ${workspaceStatIdentity.toString()};
81+
const selectWorkerWorkspaceHashMemoEntries = ${selectWorkerWorkspaceHashMemoEntries.toString()};
7782
const MAX_RECONCILIATION_ENTRIES = ${MAX_RECONCILIATION_ENTRIES};
78-
const MAX_HASH_MEMO_BYTES = ${MAX_WORKSPACE_HASH_MEMO_BYTES};
83+
const MAX_WORKSPACE_HASH_MEMO_BYTES = ${MAX_WORKSPACE_HASH_MEMO_BYTES};
7984
const root = fs.realpathSync(process.argv[1]);
8085
${WORKSPACE_STAGED_INPUT_OWNERSHIP_JS}
8186
const requestedBaseCommit = process.argv[2] || null;
@@ -105,13 +110,10 @@ const startedAt = performance.now();
105110
function fail(message) {
106111
throw new Error(message);
107112
}
108-
function compareHashMemoIdentity(left, right) {
109-
return left < right ? -1 : left > right ? 1 : 0;
110-
}
111113
function readHashMemo() {
112114
if (!memoMode) return new Map();
113115
const raw = fs.readFileSync(0, "utf8");
114-
if (Buffer.byteLength(raw) > MAX_HASH_MEMO_BYTES) {
116+
if (Buffer.byteLength(raw) > MAX_WORKSPACE_HASH_MEMO_BYTES) {
115117
fail("workspace hash memo exceeds its byte limit");
116118
}
117119
let entries;
@@ -384,7 +386,7 @@ async function hashFiles(entries) {
384386
entry.mode = Number(after.mode & 0o777n);
385387
entry.size = Number(after.size);
386388
entry.sha256 = sha256;
387-
usedHashMemo.set(identity, { sha256, size: Number(after.size) });
389+
usedHashMemo.set(identity, sha256);
388390
} finally {
389391
await handle.close();
390392
}
@@ -485,16 +487,9 @@ async function main() {
485487
const digest = publishManifest(manifestRoot, manifest);
486488
const manifestRef = "sha256:" + digest;
487489
if (memoMode) {
488-
// Largest files preserve the most expensive hashes. Identity tie-breaking and
489-
// final ordering keep the bounded cache deterministic across captures.
490-
const memo = [...usedHashMemo]
491-
.sort(
492-
(left, right) =>
493-
right[1].size - left[1].size || compareHashMemoIdentity(left[0], right[0]),
494-
)
495-
.slice(0, MAX_RECONCILIATION_ENTRIES)
496-
.map(([identity, value]) => [identity, value.sha256])
497-
.sort((left, right) => compareHashMemoIdentity(left[0], right[0]));
490+
const memo = selectWorkerWorkspaceHashMemoEntries(
491+
usedHashMemo, MAX_RECONCILIATION_ENTRIES, MAX_WORKSPACE_HASH_MEMO_BYTES,
492+
);
498493
metrics.memoTruncatedCount = usedHashMemo.size - memo.length;
499494
const measured = { ...metrics, totalDurationMs: performance.now() - startedAt };
500495
process.stdout.write(JSON.stringify({

‎src/node-host/node-worker-transfer-client.git.test.ts‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,16 +114,25 @@ describe("node worker Git transfers", () => {
114114
description: "reuses Git-base tracked files without requesting unavailable blobs",
115115
changed: false,
116116
replaceSymlinkAncestor: false,
117+
lateWrite: false,
117118
},
118119
{
119120
description: "downloads changed and nested files without restoring deleted Git-base paths",
120121
changed: true,
121122
replaceSymlinkAncestor: false,
123+
lateWrite: false,
122124
},
123125
{
124126
description: "replaces a Git-base symlink ancestor without changing files outside staging",
125127
changed: false,
126128
replaceSymlinkAncestor: true,
129+
lateWrite: false,
130+
},
131+
{
132+
description: "preserves the prior workspace when a matched base file changes before capture",
133+
changed: true,
134+
replaceSymlinkAncestor: false,
135+
lateWrite: true,
127136
},
128137
];
129138
it.each([
@@ -135,11 +144,12 @@ describe("node worker Git transfers", () => {
135144
description: "handles a prepared project cache " + seedState,
136145
changed: false,
137146
replaceSymlinkAncestor: false,
147+
lateWrite: false,
138148
seedState,
139149
})),
140150
])(
141151
"$description (prepared project: $seedState)",
142-
async ({ changed, replaceSymlinkAncestor, seedState }) => {
152+
async ({ changed, replaceSymlinkAncestor, lateWrite, seedState }) => {
143153
transferDebug.mockClear();
144154
const root = tempDirs.make("node-worker-transfer-git-");
145155
const source = path.join(root, "source");
@@ -187,7 +197,7 @@ describe("node worker Git transfers", () => {
187197
}
188198
}
189199
}
190-
if (invalidSeed) {
200+
if (invalidSeed || lateWrite) {
191201
await fs.mkdir(workspaceDir);
192202
await fs.writeFile(path.join(workspaceDir, "previous.txt"), "preserve prior workspace\n");
193203
}
@@ -250,6 +260,16 @@ describe("node worker Git transfers", () => {
250260
requestedBlobs.push(sha256);
251261
const file = filesByHash.get(sha256);
252262
if (file) {
263+
if (lateWrite && sha256 === tracked.sha256) {
264+
const staging = (await fs.readdir(root)).find((name) =>
265+
name.startsWith(".workspace.workspace-transfer-"),
266+
);
267+
expect(staging).toBeDefined();
268+
const script = path.join(root, staging!, "script.sh");
269+
const original = await fs.stat(script);
270+
await fs.writeFile(script, "#!/bin/sh\nexit 1\n");
271+
await fs.utimes(script, original.atime, original.mtime);
272+
}
253273
const body = await fs.readFile(file);
254274
res.writeHead(200, { "content-length": String(body.byteLength) });
255275
res.end(body);
@@ -270,6 +290,7 @@ describe("node worker Git transfers", () => {
270290
environmentId: "environment-git",
271291
workspaceDir,
272292
manifestHome: root,
293+
hashMemo: new Map(),
273294
transfer: {
274295
direction: "download",
275296
token: "test-token",
@@ -285,6 +306,17 @@ describe("node worker Git transfers", () => {
285306
);
286307
return;
287308
}
309+
if (lateWrite) {
310+
await expect(transfer).rejects.toMatchObject({
311+
cause: expect.objectContaining({
312+
message: expect.stringContaining("materialized a different manifest"),
313+
}),
314+
});
315+
expect(await fs.readFile(path.join(workspaceDir, "previous.txt"), "utf8")).toBe(
316+
"preserve prior workspace\n",
317+
);
318+
return;
319+
}
288320
await expect(transfer).resolves.toBe(snapshot.manifestRef);
289321
expect(requestedPacks).toBe(seedState === "available" ? 0 : 1);
290322
await expect(fs.access(path.join(workspaceDir, "seed-only.txt"))).rejects.toMatchObject({
@@ -309,6 +341,15 @@ describe("node worker Git transfers", () => {
309341
changed ? "script.sh" : "tracked.txt",
310342
);
311343
expect(requestedBlobs).toEqual([...filesByHash.keys()]);
344+
expect(transferDebug).toHaveBeenCalledWith(
345+
"node worker manifest capture completed",
346+
expect.objectContaining({
347+
contentHashCount: downloadablePaths.size,
348+
memoHitCount:
349+
snapshot.manifest.entries.filter((entry) => entry.type === "file").length -
350+
downloadablePaths.size,
351+
}),
352+
);
312353
await expect(git(workspaceDir, ["rev-parse", "HEAD"])).resolves.toBe(commit);
313354
if (changed) {
314355
await expect(fs.access(path.join(workspaceDir, "deleted.txt"))).rejects.toMatchObject({

0 commit comments

Comments
 (0)