Skip to content

Commit d7f4978

Browse files
committed
fix(agents): atomically seed fresh session identity
1 parent bf1606a commit d7f4978

7 files changed

Lines changed: 156 additions & 93 deletions

‎src/agents/sessions/session-manager-persistence.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
import {
22
appendTranscriptEventSync,
33
appendTranscriptMessageSync,
4-
loadSessionEntry,
5-
replaceSessionEntrySync,
4+
ensureSessionEntrySync,
65
} from "../../config/sessions/session-accessor.js";
76
import { isSessionTranscriptSideAppendEntry } from "../../config/sessions/transcript-tree.js";
87
import {
@@ -152,11 +151,13 @@ export class SessionManagerPersistence extends SessionManagerCore {
152151
}
153152
const scope = this.persistenceTarget;
154153
if (this.persistenceHeaderPending) {
155-
if (!loadSessionEntry(scope)) {
156-
replaceSessionEntrySync(scope, {
154+
if (
155+
!ensureSessionEntrySync(scope, {
157156
sessionId: scope.sessionId,
158157
updatedAt: Date.now(),
159-
});
158+
})
159+
) {
160+
throw new Error("Session transcript header was not persisted");
160161
}
161162
const header = this.fileEntries[0];
162163
if (!header || header.type !== "session" || !appendTranscriptEventSync(scope, header)) {

‎src/agents/sessions/session-manager.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -359,6 +359,28 @@ describe("SessionManager.open", () => {
359359
expect(loadSessionEntry(scope)).toEqual(before);
360360
});
361361

362+
it("does not overwrite a rebound session row when the first append seeds its header", async () => {
363+
const dir = await makeTempDir();
364+
const scope = {
365+
agentId: "main",
366+
sessionId: "sqlite-stale-appender",
367+
sessionKey: "agent:main:sqlite-rebound-before-header",
368+
storePath: path.join(dir, "sessions.json"),
369+
};
370+
await upsertSessionEntry(scope, {
371+
sessionId: "sqlite-current-owner",
372+
updatedAt: 456,
373+
label: "preserved",
374+
});
375+
const before = loadSessionEntry(scope);
376+
const manager = SessionManager.open(scope, dir);
377+
378+
expect(() =>
379+
manager.appendMessage({ role: "user", content: "stale message", timestamp: 1 }),
380+
).toThrow("Session transcript header was not persisted");
381+
expect(loadSessionEntry(scope)).toEqual(before);
382+
});
383+
362384
it("rejects invalid entries before mutating in-memory state", () => {
363385
const manager = SessionManager.inMemory("/tmp");
364386
const entriesBefore = manager.getEntries();

‎src/config/sessions/session-accessor.entry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { clearPluginOwnedSessionState } from "./plugin-host-cleanup.js";
1212
import {
1313
countSqliteSessionEntryRowsReadOnly as countSessionEntryRowsReadOnly,
1414
copySqliteSessionOwnedStateForCanonicalRepair as copySessionOwnedStateForCanonicalRepair,
15+
ensureSqliteSessionEntrySync,
1516
hasSqliteSessionEntriesByStatusReadOnly as hasSessionEntriesByStatusReadOnly,
1617
listSqliteSessionGenerationIdsForCanonicalRepair as listSessionGenerationIdsForCanonicalRepair,
1718
listSqliteSessionChildEntriesReadOnly as listSessionChildEntriesReadOnly,
@@ -62,6 +63,7 @@ export { clearPluginOwnedSessionState };
6263
export {
6364
countSessionEntryRowsReadOnly,
6465
copySessionOwnedStateForCanonicalRepair,
66+
ensureSqliteSessionEntrySync,
6567
hasSessionEntriesByStatusReadOnly,
6668
listSessionGenerationIdsForCanonicalRepair,
6769
listSessionChildEntriesReadOnly,

‎src/config/sessions/session-accessor.sqlite-entry.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,35 @@ export function replaceSqliteSessionEntrySync(
448448
emitCommittedSessionIdentityDiff(previous, current);
449449
}
450450

451+
/** Creates a missing session identity without replacing a concurrently owned row. */
452+
export function ensureSqliteSessionEntrySync(
453+
scope: SessionAccessScope,
454+
entry: SessionEntry,
455+
): boolean {
456+
const resolved = resolveSqliteScope(scope);
457+
assertCanonicalSessionWriteScope(resolved);
458+
let owned = false;
459+
let previous = new Map<string, SessionEntry>();
460+
let current = new Map<string, SessionEntry>();
461+
runOpenClawAgentWriteTransaction((database) => {
462+
const identityKeys = collectSessionEntryLookupKeys(database, resolved.sessionKey);
463+
previous = readSqliteSessionIdentitySnapshot(database, identityKeys);
464+
const existing = readSessionEntryRow(database, resolved.sessionKey)?.entry;
465+
if (existing) {
466+
owned = existing.sessionId === entry.sessionId;
467+
current = previous;
468+
return;
469+
}
470+
writeSessionEntry(database, resolved.sessionKey, entry);
471+
current = readSqliteSessionIdentitySnapshot(database, identityKeys);
472+
owned = current.get(resolved.sessionKey)?.sessionId === entry.sessionId;
473+
}, toDatabaseOptions(resolved));
474+
if (current.size !== previous.size || owned) {
475+
emitCommittedSessionIdentityDiff(previous, current);
476+
}
477+
return owned;
478+
}
479+
451480
/** Patches one entry in the additive SQLite session store. */
452481
export async function patchSqliteSessionEntry(
453482
scope: SessionAccessScope,

‎src/config/sessions/session-accessor.sqlite.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Stable SQLite accessor surface. Domain owners live in the focused modules below.
22
export {
33
countSqliteSessionEntryRowsReadOnly,
4+
ensureSqliteSessionEntrySync,
45
hasSqliteSessionEntriesByStatusReadOnly,
56
listSqliteSessionEntries,
67
listSqliteSessionChildEntriesReadOnly,

‎src/config/sessions/session-accessor.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ export type {
120120
} from "./session-accessor.entry-mutation.js";
121121
export {
122122
countSessionEntryRowsReadOnly,
123+
ensureSqliteSessionEntrySync as ensureSessionEntrySync,
123124
copySessionOwnedStateForCanonicalRepair,
124125
hasSessionEntriesByStatusReadOnly,
125126
listSessionGenerationIdsForCanonicalRepair,

‎test/pr119473-real-runtime-proof.e2e.test.ts‎

Lines changed: 95 additions & 88 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import os from "node:os";
44
import path from "node:path";
55
import { afterEach, describe, expect, it } from "vitest";
66
import { clearConfigCache, clearRuntimeConfigSnapshot } from "../src/config/config.js";
7+
import { clearSessionStoreCacheForTest } from "../src/config/sessions/store-writer-state.js";
78
import {
89
disconnectGatewayClient,
910
startGatewayWithClient,
@@ -40,96 +41,97 @@ describe("PR #119473 real gateway proof", () => {
4041
"persists the first turn of a fresh SQLite-backed session across gateway restart",
4142
{ timeout: 90_000 },
4243
async () => {
43-
const envSnapshot = captureEnv(envKeys);
44-
tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-pr119473-proof-"));
45-
const stateDir = path.join(tempHome, ".openclaw");
46-
const workspaceDir = path.join(tempHome, "workspace");
47-
const configPath = path.join(stateDir, "openclaw.json");
48-
const bundledPluginsDir = path.join(tempHome, "bundled-plugins");
49-
await Promise.all([
50-
fs.mkdir(workspaceDir, { recursive: true }),
51-
fs.mkdir(bundledPluginsDir, { recursive: true }),
52-
fs.mkdir(path.dirname(configPath), { recursive: true }),
53-
]);
54-
for (const [key, value] of Object.entries({
55-
HOME: tempHome,
56-
OPENCLAW_STATE_DIR: stateDir,
57-
OPENCLAW_CONFIG_PATH: configPath,
58-
OPENCLAW_GATEWAY_TOKEN: "pr119473-proof-token",
59-
OPENCLAW_SKIP_CHANNELS: "1",
60-
OPENCLAW_SKIP_GMAIL_WATCHER: "1",
61-
OPENCLAW_SKIP_CRON: "1",
62-
OPENCLAW_SKIP_CANVAS_HOST: "1",
63-
OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
64-
OPENCLAW_SKIP_PROVIDERS: "1",
65-
OPENCLAW_BUNDLED_PLUGINS_DIR: bundledPluginsDir,
66-
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
67-
})) {
68-
setTestEnvValue(key, value);
69-
}
44+
const envSnapshot = captureEnv([...envKeys]);
45+
let providerServer: ReturnType<typeof createServer> | undefined;
46+
let first: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
47+
let second: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
7048

71-
const providerServer = createServer((_request, response) => {
72-
response.writeHead(200, { "content-type": "text/event-stream" });
73-
const message = {
74-
type: "message",
75-
id: "pr119473-proof-message",
76-
role: "assistant",
77-
status: "completed",
78-
content: [{ type: "output_text", text: "PR119473_RUNTIME_OK", annotations: [] }],
79-
};
80-
response.end(
81-
[
82-
{
83-
type: "response.output_item.added",
84-
output_index: 0,
85-
item: { ...message, status: "in_progress", content: [] },
86-
},
87-
{ type: "response.output_item.done", output_index: 0, item: message },
88-
{
89-
type: "response.completed",
90-
response: {
91-
status: "completed",
92-
usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
49+
try {
50+
tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-pr119473-proof-"));
51+
const stateDir = path.join(tempHome, ".openclaw");
52+
const workspaceDir = path.join(tempHome, "workspace");
53+
const configPath = path.join(stateDir, "openclaw.json");
54+
const bundledPluginsDir = path.join(tempHome, "bundled-plugins");
55+
await Promise.all([
56+
fs.mkdir(workspaceDir, { recursive: true }),
57+
fs.mkdir(bundledPluginsDir, { recursive: true }),
58+
fs.mkdir(path.dirname(configPath), { recursive: true }),
59+
]);
60+
for (const [key, value] of Object.entries({
61+
HOME: tempHome,
62+
OPENCLAW_STATE_DIR: stateDir,
63+
OPENCLAW_CONFIG_PATH: configPath,
64+
OPENCLAW_GATEWAY_TOKEN: "pr119473-proof-token",
65+
OPENCLAW_SKIP_CHANNELS: "1",
66+
OPENCLAW_SKIP_GMAIL_WATCHER: "1",
67+
OPENCLAW_SKIP_CRON: "1",
68+
OPENCLAW_SKIP_CANVAS_HOST: "1",
69+
OPENCLAW_SKIP_BROWSER_CONTROL_SERVER: "1",
70+
OPENCLAW_SKIP_PROVIDERS: "1",
71+
OPENCLAW_BUNDLED_PLUGINS_DIR: bundledPluginsDir,
72+
OPENCLAW_DISABLE_BUNDLED_PLUGINS: "1",
73+
})) {
74+
setTestEnvValue(key, value);
75+
}
76+
77+
providerServer = createServer((_request, response) => {
78+
response.writeHead(200, { "content-type": "text/event-stream" });
79+
const message = {
80+
type: "message",
81+
id: "pr119473-proof-message",
82+
role: "assistant",
83+
status: "completed",
84+
content: [{ type: "output_text", text: "PR119473_RUNTIME_OK", annotations: [] }],
85+
};
86+
response.end(
87+
[
88+
{
89+
type: "response.output_item.added",
90+
output_index: 0,
91+
item: { ...message, status: "in_progress", content: [] },
9392
},
94-
},
95-
]
96-
.map((event) => `data: ${JSON.stringify(event)}\n\n`)
97-
.concat("data: [DONE]\n\n")
98-
.join(""),
93+
{ type: "response.output_item.done", output_index: 0, item: message },
94+
{
95+
type: "response.completed",
96+
response: {
97+
status: "completed",
98+
usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15 },
99+
},
100+
},
101+
]
102+
.map((event) => `data: ${JSON.stringify(event)}\n\n`)
103+
.concat("data: [DONE]\n\n")
104+
.join(""),
105+
);
106+
});
107+
await new Promise<void>((resolve, reject) => {
108+
providerServer?.once("error", reject);
109+
providerServer?.listen(0, "127.0.0.1", resolve);
110+
});
111+
const providerAddress = providerServer.address();
112+
if (!providerAddress || typeof providerAddress === "string") {
113+
throw new Error("proof provider did not bind a loopback port");
114+
}
115+
const provider = buildMockOpenAiResponsesProvider(
116+
`http://127.0.0.1:${providerAddress.port}/v1`,
99117
);
100-
});
101-
await new Promise<void>((resolve, reject) => {
102-
providerServer.once("error", reject);
103-
providerServer.listen(0, "127.0.0.1", resolve);
104-
});
105-
const providerAddress = providerServer.address();
106-
if (!providerAddress || typeof providerAddress === "string") {
107-
throw new Error("proof provider did not bind a loopback port");
108-
}
109-
const provider = buildMockOpenAiResponsesProvider(
110-
`http://127.0.0.1:${providerAddress.port}/v1`,
111-
);
112-
const cfg = {
113-
agents: {
114-
defaults: {
115-
workspace: workspaceDir,
116-
skipBootstrap: true,
117-
model: { primary: provider.modelRef },
118-
models: {
119-
[provider.modelRef]: { params: { transport: "sse", openaiWsWarmup: false } },
118+
const cfg = {
119+
agents: {
120+
defaults: {
121+
workspace: workspaceDir,
122+
skipBootstrap: true,
123+
model: { primary: provider.modelRef },
124+
models: {
125+
[provider.modelRef]: { params: { transport: "sse", openaiWsWarmup: false } },
126+
},
120127
},
128+
entries: { main: { default: true } },
121129
},
122-
entries: { main: { default: true } },
123-
},
124-
models: { mode: "replace", providers: { [provider.providerId]: provider.config } },
125-
gateway: { auth: { mode: "token", token: "pr119473-proof-token" } },
126-
};
127-
const sessionKey = "agent:main:pr119473-fresh-runtime";
128-
const marker = "PR119473_FIRST_USER_MESSAGE";
129-
let first: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
130-
let second: Awaited<ReturnType<typeof startGatewayWithClient>> | undefined;
131-
132-
try {
130+
models: { mode: "replace", providers: { [provider.providerId]: provider.config } },
131+
gateway: { auth: { mode: "token", token: "pr119473-proof-token" } },
132+
};
133+
const sessionKey = "agent:main:pr119473-fresh-runtime";
134+
const marker = "PR119473_FIRST_USER_MESSAGE";
133135
first = await startGatewayWithClient({
134136
cfg,
135137
configPath,
@@ -180,10 +182,15 @@ describe("PR #119473 real gateway proof", () => {
180182
await disconnectGatewayClient(second.client).catch(() => undefined);
181183
await second.server.close().catch(() => undefined);
182184
}
183-
await new Promise<void>((resolve) => {
184-
providerServer.close(() => resolve());
185-
});
185+
if (providerServer?.listening) {
186+
await new Promise<void>((resolve) => {
187+
providerServer?.close(() => resolve());
188+
});
189+
}
186190
envSnapshot.restore();
191+
clearRuntimeConfigSnapshot();
192+
clearConfigCache();
193+
clearSessionStoreCacheForTest();
187194
}
188195
},
189196
);

0 commit comments

Comments
 (0)