Skip to content

Commit 9bb9d77

Browse files
committed
fix(openshell): preserve file writes during concurrent mirror commands
Lease complete mirror file operations through the workspace owner instead of locking only remote transport. Preserve successful writes across exec publication and share serialization across backend handles. Proven with a real Docker red/green reproduction, 128-workflow mirror/remote stress matrix, exact inventories, failure recovery, 170 focused tests, and updated operator docs. Related: #127441; follow-up to #130031.
1 parent 9afd058 commit 9bb9d77

9 files changed

Lines changed: 500 additions & 195 deletions

File tree

‎docs/gateway/openshell.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,10 @@ canonical**:
126126

127127
- Before `exec`, OpenClaw syncs the local workspace into the sandbox.
128128
- After `exec`, OpenClaw syncs the remote workspace back to local.
129-
- Concurrent operations sharing the same workspace wait for the current
130-
upload, command, and download to finish before starting their own sync.
129+
- Within one OpenClaw Gateway process, commands and file-tool operations sharing
130+
a workspace wait for the current operation to finish. The lock covers the
131+
complete upload, command, and download, or the complete file read/mutation and
132+
its synchronization; separate backend handles share the same lock.
131133
- File tools go through the sandbox bridge, but local stays source of truth
132134
between turns.
133135

@@ -136,6 +138,10 @@ next exec, and the sandbox behaves close to the Docker backend.
136138

137139
Tradeoff: upload + download cost on every exec turn.
138140

141+
External editors and other Gateway processes do not participate in that lock.
142+
Avoid changing the host workspace while a mirrored command is running, because
143+
its download can replace those external edits.
144+
139145
### remote
140146

141147
`mode: "remote"` makes the **OpenShell workspace canonical**:

‎docs/reference/test.md‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -168,14 +168,14 @@ Other behavior: the runner preflights Docker by default, cleans stale OpenClaw E
168168

169169
### Sandbox compatibility lanes
170170

171-
| Command | Verifies |
172-
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
173-
| `pnpm test:e2e:openshell` | Real OpenShell gateway, isolated control-plane workspace, custom image, remote and mirrored filesystems, nested mirror writes, protected host metadata, sandbox lifecycle, SSH, and deny/allow network policies. |
174-
| `pnpm test:docker:package-install` | Packed OpenClaw npm artifact installation into a clean global prefix, then CLI version and help startup from the installed package. |
175-
| `pnpm test:docker:openai-web-search-minimal` | Mocked TLS endpoint with a private test CA, isolated Gateway startup, and web-search request handling through the configured certificate trust path. |
176-
| `pnpm test:docker:browser-cdp-snapshot` | Chromium startup, raw CDP connectivity, isolated Gateway browser commands, doctor output, and accessibility snapshot roles. |
177-
| `pnpm test:docker:kitchen-sink-rpc` | Installed plugin commands and catalog tools, read-only Gateway RPC traversal, authentication boundaries, channel lifecycle, and resource ceilings. |
178-
| `pnpm test:docker:kitchen-sink-plugin` | Packaged and registry plugin install flows, plugin execution, expected unsupported-version failures, ClawHub fallback, and npm-to-ClawHub migration. |
171+
| Command | Verifies |
172+
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
173+
| `pnpm test:e2e:openshell` | Real OpenShell gateway, isolated control-plane workspace, custom image, remote and mirrored filesystems, eight-way mixed exec/file stress, exact host/remote inventories, failure recovery, SSH cleanup, protected host metadata, and deny/allow network policies. |
174+
| `pnpm test:docker:package-install` | Packed OpenClaw npm artifact installation into a clean global prefix, then CLI version and help startup from the installed package. |
175+
| `pnpm test:docker:openai-web-search-minimal` | Mocked TLS endpoint with a private test CA, isolated Gateway startup, and web-search request handling through the configured certificate trust path. |
176+
| `pnpm test:docker:browser-cdp-snapshot` | Chromium startup, raw CDP connectivity, isolated Gateway browser commands, doctor output, and accessibility snapshot roles. |
177+
| `pnpm test:docker:kitchen-sink-rpc` | Installed plugin commands and catalog tools, read-only Gateway RPC traversal, authentication boundaries, channel lifecycle, and resource ceilings. |
178+
| `pnpm test:docker:kitchen-sink-plugin` | Packaged and registry plugin install flows, plugin execution, expected unsupported-version failures, ClawHub fallback, and npm-to-ClawHub migration. |
179179

180180
## Local PR gate
181181

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { expect, it } from "vitest";
2+
import { runCommand } from "./backend.e2e.test-support.js";
3+
4+
it.runIf(process.platform !== "win32")("reports a signal-killed probe as failure", async () => {
5+
const result = await runCommand({
6+
command: process.execPath,
7+
args: ["-e", "process.kill(process.pid, 'SIGTERM')"],
8+
allowFailure: true,
9+
timeoutMs: 10_000,
10+
});
11+
expect(result.code).not.toBe(0);
12+
});
Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
import { spawn } from "node:child_process";
2+
import fs from "node:fs/promises";
3+
import path from "node:path";
4+
import { expectDefined } from "@openclaw/normalization-core";
5+
import type { SandboxBackendHandle, SandboxFsBridge } from "openclaw/plugin-sdk/sandbox";
6+
import { expect } from "vitest";
7+
8+
type ExecResult = {
9+
code: number;
10+
stdout: string;
11+
stderr: string;
12+
};
13+
14+
export async function runCommand(params: {
15+
command: string;
16+
args: string[];
17+
cwd?: string;
18+
env?: NodeJS.ProcessEnv;
19+
stdin?: string | Uint8Array;
20+
allowFailure?: boolean;
21+
timeoutMs?: number;
22+
}): Promise<ExecResult> {
23+
return await new Promise((resolve, reject) => {
24+
const child = spawn(params.command, params.args, {
25+
cwd: params.cwd,
26+
env: params.env,
27+
stdio: ["pipe", "pipe", "pipe"],
28+
});
29+
const stdoutChunks: Buffer[] = [];
30+
const stderrChunks: Buffer[] = [];
31+
let timedOut = false;
32+
const timeout =
33+
params.timeoutMs && params.timeoutMs > 0
34+
? setTimeout(() => {
35+
timedOut = true;
36+
child.kill("SIGKILL");
37+
}, params.timeoutMs)
38+
: null;
39+
40+
child.stdout.on("data", (chunk) => stdoutChunks.push(Buffer.from(chunk)));
41+
child.stderr.on("data", (chunk) => stderrChunks.push(Buffer.from(chunk)));
42+
child.on("error", reject);
43+
child.on("close", (code) => {
44+
if (timeout) {
45+
clearTimeout(timeout);
46+
}
47+
const stdout = Buffer.concat(stdoutChunks).toString("utf8");
48+
const stderr = Buffer.concat(stderrChunks).toString("utf8");
49+
if (timedOut) {
50+
reject(new Error(`command timed out: ${params.command} ${params.args.join(" ")}`));
51+
return;
52+
}
53+
const exitCode = code ?? 1;
54+
if (exitCode !== 0 && !params.allowFailure) {
55+
const message = [
56+
`command failed: ${params.command} ${params.args.join(" ")}`,
57+
`exit: ${exitCode}`,
58+
];
59+
const trimmedStdout = stdout.trim();
60+
if (trimmedStdout.length > 0) {
61+
message.push(`stdout:\n${stdout}`);
62+
}
63+
const trimmedStderr = stderr.trim();
64+
if (trimmedStderr.length > 0) {
65+
message.push(`stderr:\n${stderr}`);
66+
}
67+
reject(new Error(message.join("\n")));
68+
return;
69+
}
70+
resolve({ code: exitCode, stdout, stderr });
71+
});
72+
73+
child.stdin.end(params.stdin);
74+
});
75+
}
76+
77+
export async function runBackendExec(params: {
78+
backend: SandboxBackendHandle;
79+
command: string;
80+
env?: Record<string, string>;
81+
allowFailure?: boolean;
82+
timeoutMs?: number;
83+
}): Promise<ExecResult> {
84+
const execSpec = await params.backend.buildExecSpec({
85+
command: params.command,
86+
env: params.env ?? {},
87+
usePty: false,
88+
});
89+
return await runPreparedBackendExec({ ...params, execSpec });
90+
}
91+
92+
export async function runPreparedBackendExec(params: {
93+
backend: SandboxBackendHandle;
94+
execSpec: Awaited<ReturnType<SandboxBackendHandle["buildExecSpec"]>>;
95+
allowFailure?: boolean;
96+
timeoutMs?: number;
97+
}): Promise<ExecResult> {
98+
const { execSpec } = params;
99+
let result: ExecResult | null | undefined;
100+
try {
101+
result = await runCommand({
102+
command: execSpec.argv[0] ?? "ssh",
103+
args: execSpec.argv.slice(1),
104+
env: execSpec.env,
105+
allowFailure: params.allowFailure,
106+
timeoutMs: params.timeoutMs,
107+
});
108+
return result;
109+
} finally {
110+
await params.backend.finalizeExec?.({
111+
status: result?.code === 0 ? "completed" : "failed",
112+
exitCode: result?.code ?? 1,
113+
timedOut: false,
114+
token: execSpec.finalizeToken,
115+
});
116+
}
117+
}
118+
119+
export async function stressBackend(params: {
120+
backends: Array<Parameters<typeof runBackendExec>[0]["backend"]>;
121+
bridge: SandboxFsBridge;
122+
mode: "mirror" | "remote";
123+
workspaceDir: string;
124+
}): Promise<void> {
125+
const startedAt = Date.now();
126+
const expectedIds: string[] = [];
127+
const latencies: number[] = [];
128+
const waves = 8;
129+
const concurrency = 8;
130+
for (let wave = 0; wave < waves; wave++) {
131+
// Keep all writes under one directory so mirror upload cost stays independent of task count.
132+
const results = await Promise.allSettled(
133+
Array.from({ length: concurrency }, async (_, slot) => {
134+
const id = `${wave}-${slot}`;
135+
const started = Date.now();
136+
const backend = params.backends[(wave + Math.floor(slot / 2)) % params.backends.length]!;
137+
if (slot % 2 === 0) {
138+
expectedIds.push(id);
139+
const exitCode = slot === 0 ? 23 : 0;
140+
const result = await runBackendExec({
141+
backend,
142+
command: `mkdir -p stress; n=$(cat stress/count 2>/dev/null || echo 0); sleep 0.02; printf '%s\\n' "$((n + 1))" > stress/count; printf '%s\\n' '${id}' >> stress/ledger; printf '%s' "$STRESS_VALUE" > 'stress/@exec-${id}'; exit ${exitCode}`,
143+
env: { STRESS_VALUE: `value-${id}` },
144+
allowFailure: true,
145+
timeoutMs: 60_000,
146+
});
147+
expect(result.code).toBe(exitCode);
148+
} else {
149+
const filePath = `stress/@file-${id}`;
150+
await params.bridge.writeFile({ filePath, data: id, mkdir: true });
151+
const temporaryPath = `stress/tmp-${id}`;
152+
switch (slot) {
153+
case 1:
154+
await expect(
155+
params.bridge.createFileExclusive?.({ filePath, data: "overwrite" }),
156+
).resolves.toBe("exists");
157+
break;
158+
case 3:
159+
await expect(
160+
params.bridge.createFileExclusive?.({ filePath: temporaryPath, data: id }),
161+
).resolves.toBe("created");
162+
await params.bridge.rename({ from: temporaryPath, to: `stress/@renamed-${id}` });
163+
break;
164+
case 5:
165+
await params.bridge.mkdirp({ filePath: temporaryPath });
166+
await params.bridge.remove({ filePath: temporaryPath, recursive: true });
167+
break;
168+
case 7:
169+
await expect(params.bridge.stat({ filePath })).resolves.toMatchObject({
170+
type: "file",
171+
size: Buffer.byteLength(id),
172+
});
173+
break;
174+
}
175+
}
176+
latencies.push(Date.now() - started);
177+
}),
178+
);
179+
const failures = results.filter((result) => result.status === "rejected");
180+
if (failures.length > 0) {
181+
throw new AggregateError(
182+
failures.map((failure) => failure.reason),
183+
"OpenShell stress wave failed",
184+
);
185+
}
186+
await expect(params.bridge.readFile({ filePath: `stress/@file-${wave}-1` })).resolves.toEqual(
187+
Buffer.from(`${wave}-1`),
188+
);
189+
console.log(
190+
JSON.stringify({
191+
probe: "openshell-stress-progress",
192+
mode: params.mode,
193+
completedWorkflows: (wave + 1) * concurrency,
194+
elapsedMs: Date.now() - startedAt,
195+
}),
196+
);
197+
}
198+
// Read the remote tree without exec preparation: a fresh mirror upload could hide divergence.
199+
const inventory = await params.backends[0]!.runShellCommand({
200+
script: `python3 -c 'import json,pathlib,sys; root=pathlib.Path(sys.argv[1]); print(json.dumps({str(p.relative_to(root)):p.read_text() for p in root.rglob("*") if p.is_file()}))' "$1"`,
201+
args: [`${params.backends[0]!.workdir}/stress`],
202+
});
203+
const remoteFiles = JSON.parse(inventory.stdout.toString("utf8")) as Record<string, string>;
204+
const ledger = expectDefined(remoteFiles.ledger, "OpenShell remote command ledger");
205+
expect(ledger.trim().split("\n").toSorted()).toEqual(expectedIds.toSorted());
206+
const expectedFiles: Record<string, string> = {
207+
ledger,
208+
count: `${expectedIds.length}\n`,
209+
};
210+
for (let wave = 0; wave < waves; wave++) {
211+
for (let slot = 0; slot < concurrency; slot++) {
212+
const id = `${wave}-${slot}`;
213+
const filePath = `stress/@${slot % 2 === 0 ? "exec" : "file"}-${id}`;
214+
const expected = slot % 2 === 0 ? `value-${id}` : id;
215+
expectedFiles[path.posix.basename(filePath)] = expected;
216+
if (slot === 3) {
217+
expectedFiles[`@renamed-${id}`] = id;
218+
}
219+
}
220+
}
221+
expect(remoteFiles).toEqual(expectedFiles);
222+
if (params.mode === "mirror") {
223+
expect((await fs.readdir(path.join(params.workspaceDir, "stress"))).toSorted()).toEqual(
224+
Object.keys(expectedFiles).toSorted(),
225+
);
226+
for (const [file, expected] of Object.entries(expectedFiles)) {
227+
await expect(params.bridge.readFile({ filePath: `stress/${file}` })).resolves.toEqual(
228+
Buffer.from(expected),
229+
);
230+
}
231+
}
232+
if (params.mode === "remote") {
233+
await expect(fs.stat(path.join(params.workspaceDir, "stress"))).rejects.toMatchObject({
234+
code: "ENOENT",
235+
});
236+
}
237+
const orderedLatencies = latencies.toSorted((a, b) => a - b);
238+
console.log(
239+
JSON.stringify({
240+
probe: "openshell-stress",
241+
mode: params.mode,
242+
workflows: waves * concurrency,
243+
concurrency,
244+
commands: expectedIds.length,
245+
intentionalCommandFailures: waves,
246+
elapsedMs: Date.now() - startedAt,
247+
p50Ms: orderedLatencies[Math.floor(latencies.length / 2)],
248+
p95Ms: orderedLatencies[Math.floor(latencies.length * 0.95)],
249+
verifiedFiles: Object.keys(expectedFiles).length - 2,
250+
}),
251+
);
252+
}

0 commit comments

Comments
 (0)