Skip to content

Commit 5ec4d9f

Browse files
authored
fix(agents): seed fresh session identity before transcript append (#119473)
* fix(agents): seed fresh session identity before transcript append * test(agents): prove fresh session persistence through gateway * fix(agents): seed session identity on first transcript write * fix(agents): atomically seed fresh session identity
1 parent 6d2ba0d commit 5ec4d9f

7 files changed

Lines changed: 314 additions & 0 deletions

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import {
22
appendTranscriptEventSync,
33
appendTranscriptMessageSync,
4+
ensureSessionEntrySync,
45
} from "../../config/sessions/session-accessor.js";
56
import { isSessionTranscriptSideAppendEntry } from "../../config/sessions/transcript-tree.js";
67
import {
@@ -150,6 +151,14 @@ export class SessionManagerPersistence extends SessionManagerCore {
150151
}
151152
const scope = this.persistenceTarget;
152153
if (this.persistenceHeaderPending) {
154+
if (
155+
!ensureSessionEntrySync(scope, {
156+
sessionId: scope.sessionId,
157+
updatedAt: Date.now(),
158+
})
159+
) {
160+
throw new Error("Session transcript header was not persisted");
161+
}
153162
const header = this.fileEntries[0];
154163
if (!header || header.type !== "session" || !appendTranscriptEventSync(scope, header)) {
155164
throw new Error("Session transcript header was not persisted");

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

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -306,6 +306,81 @@ describe("SessionManager.open", () => {
306306
expect(() => SessionManager.open(scope, dir)).not.toThrow();
307307
});
308308

309+
it("persists a fresh SQLite session header and first message", async () => {
310+
const dir = await makeTempDir();
311+
const scope = {
312+
agentId: "main",
313+
sessionId: "sqlite-fresh-session",
314+
sessionKey: "agent:main:sqlite-fresh-session",
315+
storePath: path.join(dir, "sessions.json"),
316+
};
317+
318+
expect(loadSessionEntry(scope)).toBeUndefined();
319+
const manager = SessionManager.open(scope, dir);
320+
expect(loadSessionEntry(scope)).toBeUndefined();
321+
const messageId = manager.appendMessage({
322+
role: "user",
323+
content: "first message",
324+
timestamp: 1,
325+
});
326+
327+
await expect(loadTranscriptEvents(scope)).resolves.toEqual([
328+
expect.objectContaining({
329+
id: scope.sessionId,
330+
type: "session",
331+
version: CURRENT_SESSION_VERSION,
332+
}),
333+
expect.objectContaining({
334+
id: messageId,
335+
message: expect.objectContaining({ content: "first message", role: "user" }),
336+
type: "message",
337+
}),
338+
]);
339+
expect(loadSessionEntry(scope)).toMatchObject({ sessionId: scope.sessionId });
340+
});
341+
342+
it("does not rewrite an existing session row when opening an empty transcript", async () => {
343+
const dir = await makeTempDir();
344+
const scope = {
345+
agentId: "main",
346+
sessionId: "sqlite-empty-existing-row-target",
347+
sessionKey: "agent:main:sqlite-empty-existing-row",
348+
storePath: path.join(dir, "sessions.json"),
349+
};
350+
await upsertSessionEntry(scope, {
351+
sessionId: "sqlite-existing-row",
352+
updatedAt: 123,
353+
label: "preserved",
354+
});
355+
const before = loadSessionEntry(scope);
356+
357+
SessionManager.open(scope, dir);
358+
359+
expect(loadSessionEntry(scope)).toEqual(before);
360+
});
361+
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+
309384
it("rejects invalid entries before mutating in-memory state", () => {
310385
const manager = SessionManager.inMemory("/tmp");
311386
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,
Lines changed: 197 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,197 @@
1+
import fs from "node:fs/promises";
2+
import { createServer } from "node:http";
3+
import os from "node:os";
4+
import path from "node:path";
5+
import { afterEach, describe, expect, it } from "vitest";
6+
import { clearConfigCache, clearRuntimeConfigSnapshot } from "../src/config/config.js";
7+
import { clearSessionStoreCacheForTest } from "../src/config/sessions/store-writer-state.js";
8+
import {
9+
disconnectGatewayClient,
10+
startGatewayWithClient,
11+
} from "../src/gateway/test-helpers.e2e.js";
12+
import { buildMockOpenAiResponsesProvider } from "../src/gateway/test-openai-responses-model.js";
13+
import { captureEnv, setTestEnvValue } from "../src/test-utils/env.js";
14+
15+
const envKeys = [
16+
"HOME",
17+
"OPENCLAW_STATE_DIR",
18+
"OPENCLAW_CONFIG_PATH",
19+
"OPENCLAW_GATEWAY_TOKEN",
20+
"OPENCLAW_SKIP_CHANNELS",
21+
"OPENCLAW_SKIP_GMAIL_WATCHER",
22+
"OPENCLAW_SKIP_CRON",
23+
"OPENCLAW_SKIP_CANVAS_HOST",
24+
"OPENCLAW_SKIP_BROWSER_CONTROL_SERVER",
25+
"OPENCLAW_SKIP_PROVIDERS",
26+
"OPENCLAW_BUNDLED_PLUGINS_DIR",
27+
"OPENCLAW_DISABLE_BUNDLED_PLUGINS",
28+
] as const;
29+
30+
describe("PR #119473 real gateway proof", () => {
31+
let tempHome: string | undefined;
32+
33+
afterEach(async () => {
34+
if (tempHome) {
35+
await fs.rm(tempHome, { recursive: true, force: true });
36+
tempHome = undefined;
37+
}
38+
});
39+
40+
it(
41+
"persists the first turn of a fresh SQLite-backed session across gateway restart",
42+
{ timeout: 90_000 },
43+
async () => {
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;
48+
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: [] },
92+
},
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`,
117+
);
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+
},
127+
},
128+
entries: { main: { default: true } },
129+
},
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";
135+
first = await startGatewayWithClient({
136+
cfg,
137+
configPath,
138+
token: "pr119473-proof-token",
139+
clientDisplayName: "pr119473-proof-first-start",
140+
});
141+
const started = await first.client.request<{ runId?: string; status?: string }>(
142+
"chat.send",
143+
{
144+
sessionKey,
145+
message: marker,
146+
deliver: false,
147+
idempotencyKey: "pr119473-proof-first-turn",
148+
},
149+
);
150+
expect(started.status).toBe("started");
151+
expect(started.runId).toEqual(expect.any(String));
152+
await expect(
153+
first.client.request(
154+
"agent.wait",
155+
{ runId: started.runId, timeoutMs: 30_000 },
156+
{ timeoutMs: 35_000 },
157+
),
158+
).resolves.toMatchObject({ status: "ok" });
159+
await disconnectGatewayClient(first.client);
160+
await first.server.close({ reason: "PR #119473 proof restart" });
161+
first = undefined;
162+
163+
clearRuntimeConfigSnapshot();
164+
clearConfigCache();
165+
second = await startGatewayWithClient({
166+
cfg,
167+
configPath,
168+
token: "pr119473-proof-token",
169+
clientDisplayName: "pr119473-proof-after-restart",
170+
});
171+
const history = await second.client.request<{ messages?: unknown[] }>("chat.history", {
172+
sessionKey,
173+
limit: 20,
174+
});
175+
expect(JSON.stringify(history.messages ?? [])).toContain(marker);
176+
} finally {
177+
if (first) {
178+
await disconnectGatewayClient(first.client).catch(() => undefined);
179+
await first.server.close().catch(() => undefined);
180+
}
181+
if (second) {
182+
await disconnectGatewayClient(second.client).catch(() => undefined);
183+
await second.server.close().catch(() => undefined);
184+
}
185+
if (providerServer?.listening) {
186+
await new Promise<void>((resolve) => {
187+
providerServer?.close(() => resolve());
188+
});
189+
}
190+
envSnapshot.restore();
191+
clearRuntimeConfigSnapshot();
192+
clearConfigCache();
193+
clearSessionStoreCacheForTest();
194+
}
195+
},
196+
);
197+
});

0 commit comments

Comments
 (0)