Skip to content

Commit d7cdb2e

Browse files
authored
fix(sessions): fence lifecycle transcript writers (#121284)
1 parent 1fb5d4f commit d7cdb2e

14 files changed

Lines changed: 653 additions & 184 deletions

‎docs/.generated/plugin-sdk-api-baseline.sha256‎

Lines changed: 44 additions & 44 deletions
Large diffs are not rendered by default.

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

Lines changed: 59 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import {
22
loadSessionEntry,
33
replaceSessionEntrySync,
4+
replaceTranscriptEventsSync,
5+
withTranscriptWriteTransaction,
46
} from "../../config/sessions/session-accessor.js";
57
import { projectCanonicalSessionEntryShape } from "../../config/sessions/store-entry-shape.js";
68
import { CURRENT_SESSION_VERSION } from "../../config/sessions/version.js";
@@ -102,7 +104,7 @@ export class SessionManagerBranching extends SessionManagerEntries {
102104
return { entries, opaqueEntries, tailId, usedIds };
103105
}
104106

105-
createBranchedSession(leafId: string): string | undefined {
107+
async createBranchedSession(leafId: string): Promise<string | undefined> {
106108
const previousSessionId = this.sessionId;
107109
const branchPath = this.collectBranchedSessionPath(leafId);
108110
if (branchPath.entries.length === 0) {
@@ -152,35 +154,63 @@ export class SessionManagerBranching extends SessionManagerEntries {
152154
this.fileEntries = [header, ...branchPath.entries, ...labelEntries];
153155
this.opaqueFileEntries = branchPath.opaqueEntries;
154156
this.sessionId = newSessionId;
155-
if (persistenceTarget) {
156-
const updatedAt = Date.now();
157-
const previousEntry = loadSessionEntry({
158-
agentId: persistenceTarget.agentId,
159-
sessionKey: persistenceTarget.sessionKey,
160-
storePath: persistenceTarget.storePath,
161-
});
162-
const canonicalPreviousEntry = previousEntry
163-
? projectCanonicalSessionEntryShape(previousEntry as unknown as Record<string, unknown>)
164-
: { updatedAt };
165-
this.persistenceTarget = { ...persistenceTarget, sessionId: newSessionId };
166-
replaceSessionEntrySync(
167-
{
168-
agentId: persistenceTarget.agentId,
169-
sessionKey: persistenceTarget.sessionKey,
170-
storePath: persistenceTarget.storePath,
171-
},
172-
{
173-
...canonicalPreviousEntry,
174-
sessionId: newSessionId,
175-
updatedAt,
176-
},
177-
);
178-
this.buildIndex();
179-
this.replacePersistedTranscript();
180-
return newSessionId;
157+
this.buildIndex();
158+
if (!persistenceTarget) {
159+
return undefined;
181160
}
182161

183-
this.buildIndex();
184-
return undefined;
162+
const entryScope = {
163+
agentId: persistenceTarget.agentId,
164+
sessionKey: persistenceTarget.sessionKey,
165+
storePath: persistenceTarget.storePath,
166+
};
167+
const previousEntry = loadSessionEntry(entryScope);
168+
const updatedAt = Date.now();
169+
const nextTarget = { ...persistenceTarget, sessionId: newSessionId };
170+
const nextEntry = {
171+
...(previousEntry
172+
? projectCanonicalSessionEntryShape(previousEntry as unknown as Record<string, unknown>)
173+
: { updatedAt }),
174+
sessionId: newSessionId,
175+
updatedAt,
176+
};
177+
try {
178+
const persisted = await withTranscriptWriteTransaction(persistenceTarget, () => {
179+
const currentEntry = loadSessionEntry(entryScope);
180+
if (
181+
currentEntry?.sessionId !== previousSessionId ||
182+
currentEntry.lifecycleRevision !== previousEntry?.lifecycleRevision
183+
) {
184+
return false;
185+
}
186+
replaceSessionEntrySync(entryScope, nextEntry);
187+
if (!replaceTranscriptEventsSync(nextTarget, this.getPersistedFileEntries())) {
188+
throw new Error("Branched session transcript was not persisted");
189+
}
190+
return true;
191+
});
192+
if (!persisted) {
193+
const actualEntry = loadSessionEntry(entryScope);
194+
const cause = actualEntry
195+
? {
196+
actualSessionId: actualEntry.sessionId,
197+
code: "session-rebound" as const,
198+
expectedSessionId: previousSessionId,
199+
sessionKey: persistenceTarget.sessionKey,
200+
}
201+
: {
202+
code: "session-entry-missing" as const,
203+
expectedSessionId: previousSessionId,
204+
sessionKey: persistenceTarget.sessionKey,
205+
};
206+
throw new Error(`Branched session was not persisted: ${cause.code}`, { cause });
207+
}
208+
} catch (error) {
209+
this.setSessionTarget(persistenceTarget);
210+
throw error;
211+
}
212+
this.persistenceTarget = nextTarget;
213+
this.persistenceHeaderPending = false;
214+
return newSessionId;
185215
}
186216
}

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

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
loadTranscriptEvents,
1414
readTranscriptRawDelta,
1515
replaceTranscriptEventsSync,
16+
updateSessionEntry,
1617
upsertSessionEntry,
1718
} from "../../config/sessions/session-accessor.js";
1819
import {
@@ -891,7 +892,7 @@ describe("SessionManager.open", () => {
891892
});
892893

893894
const sessionManager = openMarker(marker, sessionKey, dir);
894-
const branchedMarker = sessionManager.createBranchedSession(assistant.messageId);
895+
const branchedMarker = await sessionManager.createBranchedSession(assistant.messageId);
895896
const branchedSessionId = sessionManager.getSessionId();
896897

897898
expect(branchedMarker).toBe(branchedSessionId);
@@ -923,6 +924,73 @@ describe("SessionManager.open", () => {
923924
]);
924925
});
925926

927+
it("rejects a queued branch when lifecycle ownership changes before persistence", async () => {
928+
const dir = tempDirs.make("openclaw-session-manager-");
929+
const storePath = path.join(dir, "sessions.json");
930+
const sessionId = "sqlite-branch-race-source";
931+
const sessionKey = "agent:main:dashboard:sqlite-branch-race-source";
932+
const marker = formatSqliteSessionFileMarker({ agentId: "main", sessionId, storePath });
933+
const scope = { agentId: "main", sessionId, sessionKey, storePath };
934+
await upsertSessionEntry(scope, {
935+
lifecycleRevision: "branch-original-revision",
936+
sessionFile: marker,
937+
sessionId,
938+
updatedAt: 10,
939+
});
940+
const user = await appendTranscriptMessage(scope, {
941+
cwd: dir,
942+
eventId: "branch-race-user",
943+
message: { role: "user", content: "question before raced branch" },
944+
});
945+
const assistant = await appendTranscriptMessage(scope, {
946+
cwd: dir,
947+
eventId: "branch-race-assistant",
948+
message: buildAssistantMessage("answer before raced branch"),
949+
parentId: user.messageId,
950+
});
951+
const sessionManager = openMarker(marker, sessionKey, dir);
952+
953+
let releaseOwnerChange = () => {};
954+
const ownerChangeGate = new Promise<void>((resolve) => {
955+
releaseOwnerChange = resolve;
956+
});
957+
let markOwnerChangeStarted = () => {};
958+
const ownerChangeStarted = new Promise<void>((resolve) => {
959+
markOwnerChangeStarted = resolve;
960+
});
961+
const ownerChange = updateSessionEntry(scope, async () => {
962+
markOwnerChangeStarted();
963+
await ownerChangeGate;
964+
return { lifecycleRevision: "branch-replacement-revision" };
965+
});
966+
await ownerChangeStarted;
967+
968+
const branch = sessionManager.createBranchedSession(assistant.messageId);
969+
await new Promise<void>((resolve) => {
970+
setImmediate(resolve);
971+
});
972+
releaseOwnerChange();
973+
974+
await ownerChange;
975+
await expect(branch).rejects.toMatchObject({
976+
cause: {
977+
code: "session-rebound",
978+
expectedSessionId: sessionId,
979+
sessionKey,
980+
},
981+
});
982+
expect(loadSessionEntry(scope)).toMatchObject({
983+
lifecycleRevision: "branch-replacement-revision",
984+
sessionId,
985+
});
986+
expect(sessionManager.getSessionId()).toBe(sessionId);
987+
await expect(loadTranscriptEvents(scope)).resolves.toEqual([
988+
expect.objectContaining({ id: sessionId, type: "session" }),
989+
expect.objectContaining({ id: user.messageId, type: "message" }),
990+
expect.objectContaining({ id: assistant.messageId, type: "message" }),
991+
]);
992+
});
993+
926994
it("persists user turns when a SQLite marker has no external recorder", async () => {
927995
const dir = tempDirs.make("openclaw-session-manager-");
928996
const storePath = path.join(dir, "sessions.json");

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2144,6 +2144,7 @@ describe("sqlite session normalization", () => {
21442144
const result = await branchSqliteCompactionCheckpointSession({
21452145
agentId: "main",
21462146
env,
2147+
expectedState: sourceEntry,
21472148
storePath: paths.sqlitePath,
21482149
sourceKey: sourceEntryScope.sessionKey,
21492150
nextKey: branchKey,
@@ -2232,6 +2233,7 @@ describe("sqlite session normalization", () => {
22322233
const result = await branchSqliteCompactionCheckpointSession({
22332234
agentId: "main",
22342235
env,
2236+
expectedState: { sessionId: "source-session", lifecycleRevision: undefined },
22352237
storePath: paths.sqlitePath,
22362238
sourceKey: sourceEntryScope.sessionKey,
22372239
nextKey: "agent:main:checkpoint-post-fallback",
@@ -2312,6 +2314,7 @@ describe("sqlite session normalization", () => {
23122314
const result = await restoreSqliteCompactionCheckpointSession({
23132315
agentId: "main",
23142316
env,
2317+
expectedState: { sessionId: "current-session", lifecycleRevision: undefined },
23152318
storePath: paths.sqlitePath,
23162319
sessionKey: sourceEntryScope.sessionKey,
23172320
checkpointId: checkpoint.checkpointId,

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

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,20 @@ export function resolveSessionTranscriptActiveLeafEntryId(
3030
export async function rewindSessionToMessage(
3131
params: SessionMessageCutMutationParams,
3232
): Promise<SessionMessageCutMutationResult> {
33-
return await rewindSqliteSessionToMessage(params);
33+
const result = await rewindSqliteSessionToMessage(params);
34+
return result.status === "conflict" ? { status: "failed" } : result;
3435
}
3536

3637
export async function forkSessionAtMessage(
3738
params: SessionMessageCutMutationParams & { targetKey: string },
3839
): Promise<SessionMessageCutMutationResult> {
39-
return await forkSqliteSessionAtMessage(params);
40+
const result = await forkSqliteSessionAtMessage(params);
41+
return result.status === "conflict" ? { status: "failed" } : result;
4042
}
4143

4244
export async function switchSessionBranch(
4345
params: SessionBranchSwitchMutationParams,
4446
): Promise<SessionBranchSwitchMutationResult> {
45-
return await switchSqliteSessionBranch(params);
47+
const result = await switchSqliteSessionBranch(params);
48+
return result.status === "conflict" ? { status: "failed" } : result;
4649
}

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ type SqliteCompactionCheckpointLegacySource = {
4949
totalTokens?: number;
5050
};
5151

52+
type SessionEntryExpectedState = Pick<SessionEntry, "lifecycleRevision" | "sessionId">;
53+
5254
/** Result from SQLite compaction checkpoint branch or restore operations. */
5355
type SqliteCompactionCheckpointSessionMutationResult =
5456
| {
@@ -61,6 +63,7 @@ type SqliteCompactionCheckpointSessionMutationResult =
6163
| { status: "missing-checkpoint" }
6264
| { status: "missing-boundary" }
6365
| { status: "model-selection-locked" }
66+
| { status: "conflict" }
6467
| { status: "failed" };
6568

6669
/** Parameters for branching a SQLite session from a compaction checkpoint. */
@@ -72,6 +75,7 @@ type SqliteBranchCheckpointSessionParams = {
7275
sourceStoreKey?: string;
7376
nextKey: string;
7477
checkpointId: string;
78+
expectedState: SessionEntryExpectedState;
7579
legacySource?: SqliteCompactionCheckpointLegacySource;
7680
};
7781

@@ -83,6 +87,7 @@ type SqliteRestoreCheckpointSessionParams = {
8387
sessionKey: string;
8488
sessionStoreKey?: string;
8589
checkpointId: string;
90+
expectedState: SessionEntryExpectedState;
8691
legacySource?: SqliteCompactionCheckpointLegacySource;
8792
};
8893

@@ -110,6 +115,7 @@ export async function branchSqliteCompactionCheckpointSession(
110115
previousIdentity = readSqliteSessionIdentitySnapshot(database, identityKeys);
111116
result = branchSqliteCompactionCheckpointSessionInTransaction(database, {
112117
checkpointId: params.checkpointId,
118+
expectedState: params.expectedState,
113119
parentSessionKey: requestedSourceKey,
114120
legacySource: params.legacySource,
115121
resolved,
@@ -147,6 +153,7 @@ export async function restoreSqliteCompactionCheckpointSession(
147153
previousIdentity = readSqliteSessionIdentitySnapshot(database, identityKeys);
148154
result = restoreSqliteCompactionCheckpointSessionInTransaction(database, {
149155
checkpointId: params.checkpointId,
156+
expectedState: params.expectedState,
150157
legacySource: params.legacySource,
151158
resolved,
152159
sourceKey: sessionKey,
@@ -165,6 +172,7 @@ function branchSqliteCompactionCheckpointSessionInTransaction(
165172
database: OpenClawAgentDatabase,
166173
params: {
167174
checkpointId: string;
175+
expectedState: SessionEntryExpectedState;
168176
legacySource?: SqliteCompactionCheckpointLegacySource;
169177
parentSessionKey: string;
170178
resolved: ResolvedSqliteScope;
@@ -176,6 +184,12 @@ function branchSqliteCompactionCheckpointSessionInTransaction(
176184
if (!currentEntry?.sessionId) {
177185
return { status: "missing-session" };
178186
}
187+
if (
188+
currentEntry.sessionId !== params.expectedState.sessionId ||
189+
currentEntry.lifecycleRevision !== params.expectedState.lifecycleRevision
190+
) {
191+
return { status: "conflict" };
192+
}
179193
if (currentEntry.modelSelectionLocked === true) {
180194
return { status: "model-selection-locked" };
181195
}
@@ -215,6 +229,7 @@ function restoreSqliteCompactionCheckpointSessionInTransaction(
215229
database: OpenClawAgentDatabase,
216230
params: {
217231
checkpointId: string;
232+
expectedState: SessionEntryExpectedState;
218233
legacySource?: SqliteCompactionCheckpointLegacySource;
219234
resolved: ResolvedSqliteScope;
220235
sourceKey: string;
@@ -225,6 +240,12 @@ function restoreSqliteCompactionCheckpointSessionInTransaction(
225240
if (!currentEntry?.sessionId) {
226241
return { status: "missing-session" };
227242
}
243+
if (
244+
currentEntry.sessionId !== params.expectedState.sessionId ||
245+
currentEntry.lifecycleRevision !== params.expectedState.lifecycleRevision
246+
) {
247+
return { status: "conflict" };
248+
}
228249
if (currentEntry.modelSelectionLocked === true) {
229250
return { status: "model-selection-locked" };
230251
}

0 commit comments

Comments
 (0)