Skip to content

Commit d3e0151

Browse files
committed
fix(sandbox): preserve queue admission order
1 parent 1a54662 commit d3e0151

10 files changed

Lines changed: 162 additions & 57 deletions

File tree

‎src/agents/agent-tools.read.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1243,7 +1243,8 @@ export function wrapReadToolWithSkillContent(
12431243

12441244
function createSandboxReadOperations(params: SandboxToolParams) {
12451245
return {
1246-
resolveQueueKey: (absolutePath: string) => resolveSandboxFileQueueKey(params, absolutePath),
1246+
resolveQueueKey: (absolutePath: string, signal?: AbortSignal) =>
1247+
resolveSandboxFileQueueKey(params, absolutePath, signal),
12471248
resolvePath: (filePath: string) => {
12481249
const normalizedMediaSource = normalizeMediaReferenceSource(filePath);
12491250
if (classifyMediaReferenceSource(normalizedMediaSource).isMediaStoreUrl) {
@@ -1268,7 +1269,8 @@ function createSandboxReadOperations(params: SandboxToolParams) {
12681269
function createSandboxWriteOperations(params: SandboxToolParams) {
12691270
return withMemoryWriteProvenance(
12701271
{
1271-
resolveQueueKey: (absolutePath: string) => resolveSandboxFileQueueKey(params, absolutePath),
1272+
resolveQueueKey: (absolutePath: string, signal?: AbortSignal) =>
1273+
resolveSandboxFileQueueKey(params, absolutePath, signal),
12721274
mkdir: async (dir: string) => {
12731275
await params.bridge.mkdirp({ filePath: dir, cwd: params.root });
12741276
},
@@ -1287,7 +1289,8 @@ function createSandboxWriteOperations(params: SandboxToolParams) {
12871289
function createSandboxEditOperations(params: SandboxToolParams) {
12881290
return withMemoryWriteProvenance(
12891291
{
1290-
resolveQueueKey: (absolutePath: string) => resolveSandboxFileQueueKey(params, absolutePath),
1292+
resolveQueueKey: (absolutePath: string, signal?: AbortSignal) =>
1293+
resolveSandboxFileQueueKey(params, absolutePath, signal),
12911294
readFile: (absolutePath: string) =>
12921295
params.bridge.readFile({ filePath: absolutePath, cwd: params.root }),
12931296
writeFile: (absolutePath: string, content: string) =>
@@ -1300,12 +1303,17 @@ function createSandboxEditOperations(params: SandboxToolParams) {
13001303
);
13011304
}
13021305

1303-
async function resolveSandboxFileQueueKey(params: SandboxToolParams, absolutePath: string) {
1306+
async function resolveSandboxFileQueueKey(
1307+
params: SandboxToolParams,
1308+
absolutePath: string,
1309+
signal?: AbortSignal,
1310+
) {
13041311
return await resolveSandboxFileMutationQueueKey({
13051312
bridge: params.bridge,
13061313
root: params.root,
13071314
filePath: absolutePath,
13081315
cwd: params.root,
1316+
signal,
13091317
});
13101318
}
13111319

‎src/agents/apply-patch.ts‎

Lines changed: 45 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ import { assertSandboxPath } from "./sandbox-paths.js";
2323
import { resolveSandboxFileMutationQueueKey } from "./sandbox/file-mutation-identity.js";
2424
import {
2525
resolveFileMutationQueueKey,
26-
withFileMutationQueueKey,
27-
withFileMutationQueueKeys,
26+
withFileMutationQueueKeyResolution,
27+
withFileMutationQueueKeyResolutions,
2828
} from "./sessions/tools/file-mutation-queue.js";
2929

3030
const BEGIN_PATCH_MARKER = "*** Begin Patch";
@@ -188,33 +188,58 @@ async function applyPatch(input: string, options: ApplyPatchOptions): Promise<Ap
188188
}
189189

190190
if (hunk.kind === "add") {
191-
const target = await resolvePatchPath(hunk.path, options);
192-
await withFileMutationQueueKey(target.queueKey, async () => {
193-
await assertPatchParentPath(hunk.path, options);
194-
await ensureDir(target.resolved, fileOps);
195-
await createPatchTarget({
196-
target,
197-
contents: hunk.contents,
198-
ops: fileOps,
199-
hint: `Use "*** Update File: ${target.display}" to change it, or delete it earlier in the same patch.`,
200-
});
201-
});
191+
const targetResolution = resolvePatchPath(hunk.path, options);
192+
await withFileMutationQueueKeyResolution(
193+
targetResolution.then((target) => target.queueKey),
194+
async () => {
195+
const target = await targetResolution;
196+
await assertPatchParentPath(hunk.path, options);
197+
await ensureDir(target.resolved, fileOps);
198+
await createPatchTarget({
199+
target,
200+
contents: hunk.contents,
201+
ops: fileOps,
202+
hint: `Use "*** Update File: ${target.display}" to change it, or delete it earlier in the same patch.`,
203+
});
204+
},
205+
);
206+
const target = await targetResolution;
202207
recordSummary(summary, seen, "added", target.display);
203208
continue;
204209
}
205210

206211
if (hunk.kind === "delete") {
207-
const target = await resolvePatchPath(hunk.path, options, PATH_ALIAS_POLICIES.unlinkTarget);
208-
await withFileMutationQueueKey(target.queueKey, () => fileOps.remove(target.resolved));
212+
const targetResolution = resolvePatchPath(
213+
hunk.path,
214+
options,
215+
PATH_ALIAS_POLICIES.unlinkTarget,
216+
);
217+
await withFileMutationQueueKeyResolution(
218+
targetResolution.then((target) => target.queueKey),
219+
async () => {
220+
const target = await targetResolution;
221+
await fileOps.remove(target.resolved);
222+
},
223+
);
224+
const target = await targetResolution;
209225
recordSummary(summary, seen, "deleted", target.display);
210226
continue;
211227
}
212228

213-
const target = await resolvePatchPath(hunk.path, options);
214-
const moveTarget = hunk.movePath ? await resolvePatchPath(hunk.movePath, options) : undefined;
215-
await withFileMutationQueueKeys(
216-
[target.queueKey, ...(moveTarget ? [moveTarget.queueKey] : [])],
229+
const targetResolution = resolvePatchPath(hunk.path, options);
230+
const moveTargetResolution = hunk.movePath
231+
? resolvePatchPath(hunk.movePath, options)
232+
: undefined;
233+
await withFileMutationQueueKeyResolutions(
234+
[
235+
targetResolution.then((target) => target.queueKey),
236+
...(moveTargetResolution
237+
? [moveTargetResolution.then((moveTarget) => moveTarget.queueKey)]
238+
: []),
239+
],
217240
async () => {
241+
const target = await targetResolution;
242+
const moveTarget = moveTargetResolution ? await moveTargetResolution : undefined;
218243
const applied = await applyUpdateHunk(target.resolved, hunk.chunks, {
219244
readFile: (pathLocal) => fileOps.readFile(pathLocal),
220245
});
@@ -391,6 +416,7 @@ async function resolvePatchPath(
391416
root: options.sandbox.root,
392417
filePath,
393418
cwd: options.cwd,
419+
signal: options.signal,
394420
}),
395421
display: resolved.relativePath || resolved.containerPath,
396422
};

‎src/agents/sandbox/file-mutation-identity.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,14 @@ export async function resolveSandboxFileMutationQueueKey(params: {
66
root: string;
77
filePath: string;
88
cwd?: string;
9+
signal?: AbortSignal;
910
}): Promise<string> {
1011
let identity: string;
1112
if (params.bridge.resolveFileIdentity) {
1213
identity = await params.bridge.resolveFileIdentity({
1314
filePath: params.filePath,
1415
cwd: params.cwd,
16+
signal: params.signal,
1517
});
1618
} else {
1719
// Shipped plugin bridges may predate physical identity support. Their resolved bridge path

‎src/agents/sandbox/fs-bridge.types.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ export type SandboxFsBridge = {
2525
* Returns one backend-owned physical identity for file-operation ordering.
2626
* Optional to preserve the shipped plugin bridge contract; older bridges use resolvePath identity.
2727
*/
28-
resolveFileIdentity?(params: { filePath: string; cwd?: string }): Promise<string>;
28+
resolveFileIdentity?(params: {
29+
filePath: string;
30+
cwd?: string;
31+
signal?: AbortSignal;
32+
}): Promise<string>;
2933
/** Reads a safely opened regular file, rejecting growth beyond an optional byte limit. */
3034
readFile(params: {
3135
filePath: string;

‎src/agents/sandbox/remote-fs-bridge.test.ts‎

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import path from "node:path";
55
import { describe, expect, it, vi } from "vitest";
66
import { createDeferred } from "../../../test/helpers/promise.js";
77
import { createSandboxedReadTool, createSandboxedWriteTool } from "../agent-tools.read.js";
8-
import { withFileMutationQueueKey } from "../sessions/tools/file-mutation-queue.js";
98
import { SANDBOX_CREATE_EXISTS_EXIT_CODE } from "./fs-bridge-mutation-helper.js";
109
import { createSandbox } from "./fs-bridge.test-helpers.js";
1110
import {
@@ -129,29 +128,38 @@ describe("remote sandbox fs bridge", () => {
129128
bridge.resolveFileIdentity!({ filePath: hostPath, cwd: workspaceDir }),
130129
).resolves.toBe(aliasIdentity);
131130

132-
const blockerStarted = createDeferred();
133-
const releaseBlocker = createDeferred();
134-
const blocker = withFileMutationQueueKey(`${workspaceDir}\0${aliasIdentity}`, async () => {
135-
blockerStarted.resolve();
136-
await releaseBlocker.promise;
131+
const resolveFileIdentity = bridge.resolveFileIdentity!.bind(bridge);
132+
const writeIdentityStarted = createDeferred();
133+
const releaseWriteIdentity = createDeferred();
134+
const readIdentityResolved = createDeferred();
135+
vi.spyOn(bridge, "resolveFileIdentity").mockImplementation(async (params) => {
136+
if (params.filePath === remotePath) {
137+
writeIdentityStarted.resolve();
138+
await releaseWriteIdentity.promise;
139+
}
140+
const identity = await resolveFileIdentity(params);
141+
if (params.filePath === hostPath) {
142+
readIdentityResolved.resolve();
143+
}
144+
return identity;
137145
});
138-
await blockerStarted.promise;
139146
const statSpy = vi.spyOn(bridge, "stat");
140147
const writeTool = createSandboxedWriteTool({ root: workspaceDir, bridge });
141148
const readTool = createSandboxedReadTool({ root: workspaceDir, bridge });
142149
const writeResult = writeTool.execute("write", {
143150
path: remotePath,
144151
content: "remote snapshot",
145152
});
153+
await writeIdentityStarted.promise;
146154
const readResult = readTool.execute("read", { path: hostPath });
147155
void readResult.catch(() => {});
156+
await readIdentityResolved.promise;
148157
await new Promise<void>((resolve) => {
149158
setImmediate(resolve);
150159
});
151160
expect(statSpy).not.toHaveBeenCalled();
152161

153-
releaseBlocker.resolve();
154-
await blocker;
162+
releaseWriteIdentity.resolve();
155163
const [, result] = await Promise.all([writeResult, readResult]);
156164
expect(statSpy).toHaveBeenCalled();
157165
expect(result.content).toEqual(

‎src/agents/sandbox/remote-fs-bridge.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,12 +65,17 @@ class RemoteShellSandboxFsBridge implements SandboxFsBridge {
6565
};
6666
}
6767

68-
async resolveFileIdentity(params: { filePath: string; cwd?: string }): Promise<string> {
68+
async resolveFileIdentity(params: {
69+
filePath: string;
70+
cwd?: string;
71+
signal?: AbortSignal;
72+
}): Promise<string> {
6973
const target = this.resolveTarget(params);
7074
const { canonicalPath } = await this.resolveCanonicalPath({
7175
containerPath: target.containerPath,
7276
mountRootPath: target.mountRootPath,
7377
action: "identify files",
78+
signal: params.signal,
7479
});
7580
return canonicalPath;
7681
}

‎src/agents/sessions/tools/edit.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,10 @@ import {
3232
stripBom,
3333
validateNoOpEditTargets,
3434
} from "./edit-diff.js";
35-
import { resolveFileMutationQueueKey, withFileMutationQueueKey } from "./file-mutation-queue.js";
35+
import {
36+
resolveFileMutationQueueKey,
37+
withFileMutationQueueKeyResolution,
38+
} from "./file-mutation-queue.js";
3639
import { type PersistedFileStat, verifyPersistedUtf8File } from "./file-write-verification.js";
3740
import { resolveToCwd } from "./path-utils.js";
3841
import { invalidArgText, shortenPath, str } from "./render-utils.js";
@@ -97,7 +100,7 @@ const EDIT_MISMATCH_HINT_LIMIT = 800;
97100
*/
98101
export interface EditOperations {
99102
/** Resolve the physical identity used to order this backend's file operations. */
100-
resolveQueueKey?: (absolutePath: string) => string | Promise<string>;
103+
resolveQueueKey?: (absolutePath: string, signal?: AbortSignal) => string | Promise<string>;
101104
/** Read file contents as a Buffer */
102105
readFile: (absolutePath: string) => Promise<Buffer>;
103106
/** Write content to a file */
@@ -409,9 +412,9 @@ export function createEditToolDefinition(
409412
void ctx;
410413
const { path, edits: originalEdits } = validateEditInput(input);
411414
const absolutePath = resolveToCwd(path, cwd);
412-
const queueKey = await resolveFileMutationQueueKey(absolutePath, ops.resolveQueueKey);
415+
const queueKey = resolveFileMutationQueueKey(absolutePath, ops.resolveQueueKey, signal);
413416

414-
return withFileMutationQueueKey(queueKey, async () => {
417+
return withFileMutationQueueKeyResolution(queueKey, async () => {
415418
if (signal?.aborted) {
416419
throw new Error("Operation aborted");
417420
}

‎src/agents/sessions/tools/file-mutation-queue.ts‎

Lines changed: 53 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,71 @@
1+
import { getAgentToolExecutionContext } from "../../../../packages/agent-core/src/tool-execution-context.js";
12
/**
23
* Per-file mutation queue.
34
*
4-
* Serializes edits/writes targeting the same real file while allowing independent files to mutate in parallel.
5+
* Serializes reads and mutations targeting the same real file while allowing independent files to run in parallel.
56
*/
67
import { resolveIdentityPathViaExistingAncestorSync } from "../../../infra/boundary-path.js";
7-
import { resolveGlobalMap } from "../../../shared/global-singleton.js";
8+
import { resolveGlobalMap, resolveGlobalSingleton } from "../../../shared/global-singleton.js";
89

910
const fileMutationTails = resolveGlobalMap<string, Promise<void>>(
1011
Symbol.for("openclaw.fileMutationTails"),
1112
"close-only",
1213
);
14+
const keyAdmissions = resolveGlobalSingleton(
15+
Symbol.for("openclaw.fileMutationKeyAdmissions"),
16+
() => ({ fallbackScope: {}, tails: new WeakMap<object, Promise<void>>() }),
17+
);
1318

1419
function resolveLocalFileMutationQueueKey(filePath: string): string {
1520
return resolveIdentityPathViaExistingAncestorSync(filePath);
1621
}
1722

1823
export async function resolveFileMutationQueueKey(
1924
filePath: string,
20-
resolveQueueKey?: (absolutePath: string) => string | Promise<string>,
25+
resolveQueueKey?: (absolutePath: string, signal?: AbortSignal) => string | Promise<string>,
26+
signal?: AbortSignal,
2127
): Promise<string> {
22-
return await (resolveQueueKey?.(filePath) ?? resolveLocalFileMutationQueueKey(filePath));
28+
return await (resolveQueueKey?.(filePath, signal) ?? resolveLocalFileMutationQueueKey(filePath));
29+
}
30+
31+
/**
32+
* Preserve source-call admission while backend-owned physical identities resolve concurrently.
33+
* Registration is ordered per assistant message; file operations still use only fileMutationTails.
34+
*/
35+
export async function withFileMutationQueueKeyResolution<T>(
36+
keyResolution: Promise<string>,
37+
fn: () => Promise<T>,
38+
): Promise<T> {
39+
return await withFileMutationQueueKeyResolutions([keyResolution], fn);
40+
}
41+
42+
export async function withFileMutationQueueKeyResolutions<T>(
43+
keyResolutions: readonly Promise<string>[],
44+
fn: () => Promise<T>,
45+
): Promise<T> {
46+
const scope = getAgentToolExecutionContext()?.assistantMessage ?? keyAdmissions.fallbackScope;
47+
const previousAdmission = keyAdmissions.tails.get(scope) ?? Promise.resolve();
48+
for (const keyResolution of keyResolutions) {
49+
void keyResolution.catch(() => undefined);
50+
}
51+
let operation!: Promise<T>;
52+
const admission = previousAdmission.then(async () => {
53+
const keys = await Promise.all(keyResolutions);
54+
operation = enqueueFileMutationQueueKeys(keys, fn);
55+
});
56+
const tail = admission.then(
57+
() => undefined,
58+
() => undefined,
59+
);
60+
keyAdmissions.tails.set(scope, tail);
61+
const cleanup = () => {
62+
if (keyAdmissions.tails.get(scope) === tail) {
63+
keyAdmissions.tails.delete(scope);
64+
}
65+
};
66+
tail.then(cleanup, cleanup);
67+
await admission;
68+
return await operation;
2369
}
2470

2571
/**
@@ -30,18 +76,14 @@ export async function withFileMutationQueue<T>(filePath: string, fn: () => Promi
3076
return await withFileMutationQueues([filePath], fn);
3177
}
3278

33-
export async function withFileMutationQueueKey<T>(key: string, fn: () => Promise<T>): Promise<T> {
34-
return await withFileMutationQueueKeys([key], fn);
35-
}
36-
3779
async function withFileMutationQueues<T>(
3880
filePaths: readonly string[],
3981
fn: () => Promise<T>,
4082
): Promise<T> {
41-
return await withFileMutationQueueKeys(filePaths.map(resolveLocalFileMutationQueueKey), fn);
83+
return await enqueueFileMutationQueueKeys(filePaths.map(resolveLocalFileMutationQueueKey), fn);
4284
}
4385

44-
export async function withFileMutationQueueKeys<T>(
86+
function enqueueFileMutationQueueKeys<T>(
4587
queueKeys: readonly string[],
4688
fn: () => Promise<T>,
4789
): Promise<T> {
@@ -64,5 +106,5 @@ export async function withFileMutationQueueKeys<T>(
64106
}
65107
};
66108
tail.then(cleanup, cleanup);
67-
return await current;
109+
return current;
68110
}

0 commit comments

Comments
 (0)