Skip to content

Commit 22f9230

Browse files
MrSwagatRathodobviyus
authored andcommitted
fix(settings): lock before concurrent first writes
Two processes could read an absent settings file before either acquired its lock. Each process then merged from an empty object, and the later write silently discarded the other process's setting. Keep missing-file reads lazy, but acquire the file lock before every read-modify-write callback. Existing custom settings stores keep using their shipped lock-based read contract.
1 parent f46f9b5 commit 22f9230

3 files changed

Lines changed: 141 additions & 19 deletions

File tree

‎src/agents/sessions/settings-manager.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,14 @@ export class SettingsManager {
9898
private static loadScope(storage: SettingsStorage, scope: SettingsScope): SettingsScopeState {
9999
let content: string | undefined;
100100
try {
101-
storage.withLock(scope, (current) => {
102-
content = current;
103-
return undefined;
104-
});
101+
if (storage.readSettingsScope) {
102+
content = storage.readSettingsScope(scope);
103+
} else {
104+
storage.withLock(scope, (current) => {
105+
content = current;
106+
return undefined;
107+
});
108+
}
105109
const settings = content
106110
? SettingsManager.migrateSettings(JSON.parse(content) as Record<string, unknown>)
107111
: {};
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import { spawn, type ChildProcess } from "node:child_process";
2+
import { existsSync, mkdirSync, readFileSync } from "node:fs";
3+
import { join, resolve } from "node:path";
4+
import { pathToFileURL } from "node:url";
5+
import { afterEach, describe, expect, it } from "vitest";
6+
import { waitForChildClose, waitForFile } from "../../../test/helpers/process-wait.js";
7+
import { useAutoCleanupTempDirTracker } from "../../../test/helpers/temp-dir.js";
8+
import { SettingsManager } from "./settings-manager.js";
9+
10+
const writerScript = String.raw`
11+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
12+
import { join } from "node:path";
13+
14+
const [moduleUrl, settingsDir, markerDir, field] = process.argv.slice(1);
15+
const { FileSettingsStorage } = await import(moduleUrl);
16+
const settingsPath = join(settingsDir, "settings.json");
17+
const otherEntered = join(markerDir, "theme.entered");
18+
const contenderSawLock = join(markerDir, "contender-saw-lock");
19+
20+
if (field === "theme" && existsSync(settingsPath + ".lock")) {
21+
writeFileSync(contenderSawLock, "ready");
22+
}
23+
24+
const storage = new FileSettingsStorage(settingsDir, settingsDir);
25+
storage.withLock("global", (current) => {
26+
writeFileSync(join(markerDir, field + ".entered"), "ready");
27+
if (field === "defaultModel") {
28+
const deadline = Date.now() + 5_000;
29+
const pause = new Int32Array(new SharedArrayBuffer(4));
30+
while (!existsSync(otherEntered) && !existsSync(contenderSawLock)) {
31+
if (Date.now() >= deadline) {
32+
throw new Error("contending writer did not reach the settings boundary");
33+
}
34+
Atomics.wait(pause, 0, 0, 10);
35+
}
36+
}
37+
const settings = current ? JSON.parse(current) : {};
38+
settings[field] = field === "theme" ? "dark" : "provider/model";
39+
return JSON.stringify(settings, null, 2);
40+
});
41+
`;
42+
43+
const children = new Map<ChildProcess, Promise<unknown>>();
44+
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
45+
46+
afterEach(async () => {
47+
for (const child of children.keys()) {
48+
child.kill("SIGKILL");
49+
}
50+
await Promise.allSettled(children.values());
51+
children.clear();
52+
});
53+
54+
function spawnWriter(settingsDir: string, markerDir: string, field: string) {
55+
const moduleUrl = pathToFileURL(resolve("src/agents/sessions/settings-storage.ts")).href;
56+
const child = spawn(
57+
process.execPath,
58+
[
59+
"--import",
60+
"tsx",
61+
"--input-type=module",
62+
"--eval",
63+
writerScript,
64+
moduleUrl,
65+
settingsDir,
66+
markerDir,
67+
field,
68+
],
69+
{ stdio: ["ignore", "pipe", "pipe"] },
70+
);
71+
const done = waitForChildClose(child, 10_000);
72+
children.set(child, done);
73+
let output = "";
74+
child.stdout?.setEncoding("utf8").on("data", (chunk) => (output += chunk));
75+
child.stderr?.setEncoding("utf8").on("data", (chunk) => (output += chunk));
76+
return { child, done, output: () => output };
77+
}
78+
79+
describe("FileSettingsStorage", () => {
80+
it("loads missing settings without creating their directories", () => {
81+
const root = tempDirs.make("openclaw-settings-read-");
82+
const settingsDir = join(root, "agent");
83+
84+
SettingsManager.create(root, settingsDir);
85+
86+
expect(existsSync(settingsDir)).toBe(false);
87+
expect(existsSync(join(root, ".openclaw"))).toBe(false);
88+
});
89+
90+
it("preserves concurrent first writes from separate processes", async () => {
91+
const root = tempDirs.make("openclaw-settings-first-write-");
92+
const settingsDir = join(root, "agent");
93+
const markerDir = join(root, "markers");
94+
mkdirSync(markerDir);
95+
96+
const first = spawnWriter(settingsDir, markerDir, "defaultModel");
97+
await waitForFile(join(markerDir, "defaultModel.entered"), 5_000);
98+
const contender = spawnWriter(settingsDir, markerDir, "theme");
99+
100+
for (const writer of [first, contender]) {
101+
const result = await writer.done;
102+
children.delete(writer.child);
103+
expect(result, writer.output()).toEqual({ code: 0, signal: null });
104+
}
105+
106+
expect(JSON.parse(readFileSync(join(settingsDir, "settings.json"), "utf8"))).toEqual({
107+
defaultModel: "provider/model",
108+
theme: "dark",
109+
});
110+
}, 15_000);
111+
});

‎src/agents/sessions/settings-storage.ts‎

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,8 @@ export type SettingsScope = "global" | "project";
118118
export const SETTINGS_SCOPES: SettingsScope[] = ["global", "project"];
119119

120120
export interface SettingsStorage {
121+
// Optional so shipped custom backends can keep serving reads through withLock.
122+
readSettingsScope?(scope: SettingsScope): string | undefined;
121123
withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void;
122124
}
123125

@@ -136,31 +138,36 @@ export class FileSettingsStorage implements SettingsStorage {
136138
};
137139
}
138140

141+
readSettingsScope(scope: SettingsScope): string | undefined {
142+
const path = this.paths[scope];
143+
if (!existsSync(path)) {
144+
return undefined;
145+
}
146+
const release = acquireFileLockSyncWithRetry(path);
147+
try {
148+
return readFileSync(path, "utf-8");
149+
} finally {
150+
release();
151+
}
152+
}
153+
139154
withLock(scope: SettingsScope, fn: (current: string | undefined) => string | undefined): void {
140155
const path = this.paths[scope];
141156
const dir = dirname(path);
142157

143-
let release: (() => void) | undefined;
158+
if (!existsSync(dir)) {
159+
mkdirSync(dir, { recursive: true });
160+
}
161+
// Lock before reading, or concurrent first writers can merge from the same empty state.
162+
const release = acquireFileLockSyncWithRetry(path);
144163
try {
145-
// Only create directory and lock if file exists or we need to write
146-
const fileExists = existsSync(path);
147-
if (fileExists) {
148-
release = acquireFileLockSyncWithRetry(path);
149-
}
150-
const current = fileExists ? readFileSync(path, "utf-8") : undefined;
164+
const current = existsSync(path) ? readFileSync(path, "utf-8") : undefined;
151165
const next = fn(current);
152166
if (next !== undefined) {
153-
// Only create directory when we actually need to write
154-
if (!existsSync(dir)) {
155-
mkdirSync(dir, { recursive: true });
156-
}
157-
if (!release) {
158-
release = acquireFileLockSyncWithRetry(path);
159-
}
160167
writeFileSync(path, next, "utf-8");
161168
}
162169
} finally {
163-
release?.();
170+
release();
164171
}
165172
}
166173
}

0 commit comments

Comments
 (0)