Skip to content

Commit 4ffcd97

Browse files
authored
fix(sessions): stop max-lines compaction backup leaks (#125183)
* fix(sessions): stop max-lines compaction backup leaks * fix(sessions): reclaim legacy compact backups
1 parent 076a8cc commit 4ffcd97

12 files changed

Lines changed: 29 additions & 134 deletions

‎docs/cli/sessions.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,8 @@ openclaw sessions compact "agent:work:main" --agent work --json
300300
- Without `--max-lines`, the Gateway LLM-summarizes the transcript. The CLI
301301
does not impose a client deadline by default; the Gateway owns the
302302
configured compaction lifecycle.
303-
- With `--max-lines <n>`, it truncates to the last `n` transcript lines and
304-
archives the prior transcript as a `.bak` sidecar.
303+
- With `--max-lines <n>`, it permanently truncates the SQLite transcript to the
304+
last `n` lines. This path does not create a backup archive.
305305
- `--agent <id>`: agent that owns the session; required for `global` keys.
306306
- `--url` / `--token` / `--password`: Gateway connection overrides.
307307
- `--timeout <ms>`: optional client-side RPC timeout in milliseconds.
@@ -345,7 +345,6 @@ Example truncate response (`--max-lines 200`):
345345
"ok": true,
346346
"key": "agent:main:main",
347347
"compacted": true,
348-
"archived": "/home/user/.openclaw/agents/main/sessions/transcripts/<id>.jsonl.bak",
349348
"kept": 200
350349
}
351350
```

‎src/commands/sessions-compact.test.ts‎

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -160,23 +160,6 @@ describe("sessionsCompactCommand", () => {
160160
expect(runtime.exit).toHaveBeenCalledWith(1);
161161
});
162162

163-
it("prints the archive path exactly as returned by the RPC", async () => {
164-
const archived = "/state/agents/main/sessions/sess-1.jsonl.bak.2026-07-19T00-00-00.000Z.zst";
165-
callGatewayCli.mockResolvedValue({
166-
ok: true,
167-
key: "agent:main:main",
168-
compacted: true,
169-
kept: 50,
170-
archived,
171-
});
172-
const runtime = createRuntime();
173-
174-
await sessionsCompactCommand({ key: "agent:main:main", maxLines: 50 }, runtime);
175-
176-
expect(runtime.exit).not.toHaveBeenCalled();
177-
expect(joinedArgs(runtime.log)).toContain(`Archived transcript: ${archived}`);
178-
});
179-
180163
it("forwards agentId and maxLines to the RPC params", async () => {
181164
callGatewayCli.mockResolvedValue({
182165
ok: true,

‎src/commands/sessions-compact.ts‎

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ type SessionsCompactResult = {
2828
compacted?: boolean;
2929
reason?: string;
3030
kept?: number;
31-
archived?: string;
3231
result?: {
3332
tokensBefore?: number;
3433
tokensAfter?: number;
@@ -125,7 +124,4 @@ export async function sessionsCompactCommand(
125124
}
126125

127126
runtime.log(describeCompaction(result ?? {}, opts.key));
128-
if (result?.archived) {
129-
runtime.log(`Archived transcript: ${result.archived}`);
130-
}
131127
}

‎src/config/sessions/artifacts.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,13 @@ export function isSessionArchiveArtifactName(fileName: string): boolean {
3939
);
4040
}
4141

42-
/** Returns true for retained reset/delete transcript archives counted by the session budget. */
42+
/** Returns true for retained archives and disposable legacy compact backups pruned at high water. */
4343
export function isRetainedSessionTranscriptArchiveName(fileName: string): boolean {
44-
return hasArchiveSuffix(fileName, "deleted") || hasArchiveSuffix(fileName, "reset");
44+
return (
45+
hasArchiveSuffix(fileName, "deleted") ||
46+
hasArchiveSuffix(fileName, "reset") ||
47+
hasArchiveSuffix(fileName, "bak")
48+
);
4549
}
4650

4751
/** Returns true for migration rollback archives retained beside their legacy source. */

‎src/config/sessions/disk-budget.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ export async function hasRetainedSessionTranscriptArchives(storePath: string): P
317317
return files.some((file) => isRetainedSessionTranscriptArchiveName(file.name));
318318
}
319319

320-
/** Removes oldest retained reset/delete archives, remeasuring physical usage after each file. */
320+
/** Removes oldest retained archives and legacy compact backups, remeasuring after each file. */
321321
export async function pruneSessionTranscriptArchivesToHighWater(params: {
322322
excludeNames?: ReadonlySet<string>;
323323
highWaterBytes: number;

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

Lines changed: 2 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
type OpenClawAgentDatabase,
77
} from "../../state/openclaw-agent-db.js";
88
import { clearAllCliSessions } from "./cli-session-binding.js";
9-
import { writeTranscriptArchive } from "./session-accessor.sqlite-archive.js";
109
import type {
1110
SessionTranscriptAccessScope,
1211
SessionTranscriptTurnMessageAppend,
@@ -36,7 +35,6 @@ import {
3635
} from "./session-accessor.sqlite-read.js";
3736
import {
3837
cloneSessionEntry,
39-
resolveSqliteTranscriptArchiveDirectory,
4038
resolveSqliteTranscriptScope,
4139
runExclusiveSqliteSessionWrite,
4240
toDatabaseOptions,
@@ -64,7 +62,6 @@ import {
6462
sessionMatchesExpectedTranscriptTurn,
6563
} from "./session-transcript-turn-state.js";
6664
import type { TranscriptEntryAnchor } from "./transcript-entry-anchor.js";
67-
import { serializeJsonlLines } from "./transcript-jsonl.js";
6865
import {
6966
SessionTranscriptWriterClaimReboundError,
7067
withOwnedSessionTranscriptWriterFence,
@@ -190,7 +187,7 @@ export async function trimTranscriptForManualCompact(
190187
scope: SessionTranscriptAccessScope,
191188
selectRetainedLines: (lines: readonly string[]) => readonly string[] | null,
192189
options: { nowMs?: number } = {},
193-
): Promise<{ trimmed: false } | { archivedPath: string; kept: number; trimmed: true }> {
190+
): Promise<{ trimmed: false } | { kept: number; trimmed: true }> {
194191
const resolved = resolveSqliteTranscriptScope(scope);
195192
return await runExclusiveSqliteSessionWrite(resolved, async () => {
196193
const database = openOpenClawAgentDatabase(toDatabaseOptions(resolved));
@@ -207,14 +204,6 @@ export async function trimTranscriptForManualCompact(
207204
);
208205
}
209206
const retainedEvents = retainedLines.map((line) => JSON.parse(line) as TranscriptEvent);
210-
const archivedPath = writeTranscriptArchive({
211-
archiveDirectory: resolveSqliteTranscriptArchiveDirectory(resolved),
212-
content: serializeJsonlLines(lines),
213-
reason: "bak",
214-
sessionId: resolved.sessionId,
215-
});
216-
// Published archives can be reused by another process before this commit.
217-
// Retain them on failure so a sibling operation never loses its durable proof.
218207
let previousIdentity = new Map<string, SessionEntry>();
219208
let currentIdentity = new Map<string, SessionEntry>();
220209
runOpenClawAgentWriteTransaction((writeDatabase) => {
@@ -253,7 +242,7 @@ export async function trimTranscriptForManualCompact(
253242
currentIdentity = readSessionIdentitySnapshot(writeDatabase, identityKeys);
254243
}, toDatabaseOptions(resolved));
255244
emitCommittedSessionIdentityDiff(previousIdentity, currentIdentity);
256-
return { archivedPath, kept: retainedLines.length, trimmed: true };
245+
return { kept: retainedLines.length, trimmed: true };
257246
});
258247
}
259248

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

Lines changed: 2 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ import {
2727
deliveryContextFromSession,
2828
sessionDeliveryRoute,
2929
} from "../../utils/delivery-context.shared.js";
30-
import { readSessionArchiveContentSync } from "./archive-compression.js";
3130
import {
3231
applySessionEntryReplacements,
3332
applySessionPatchProjections,
@@ -2815,17 +2814,6 @@ describe("session accessor seam", () => {
28152814

28162815
unsubscribe();
28172816
expect(result).toMatchObject({ compacted: true, kept: 3 });
2818-
const archived = result.compacted ? result.archived : "";
2819-
expect(path.basename(archived)).toMatch(
2820-
new RegExp(`^${sessionId}\\.jsonl\\.bak\\.\\d{4}-\\d{2}-\\d{2}T`),
2821-
);
2822-
expect(fs.realpathSync(path.dirname(archived))).toBe(fs.realpathSync(tempDir));
2823-
expect(fs.existsSync(archived)).toBe(true);
2824-
const archivedRecords = readSessionArchiveContentSync(archived)
2825-
.split("\n")
2826-
.filter((line) => line.length > 0)
2827-
.map((line) => JSON.parse(line) as Record<string, unknown>);
2828-
expect(archivedRecords).toEqual(transcriptRecords);
28292817
const trimmedRecords = (await loadTranscriptEvents(scope)) as Array<Record<string, unknown>>;
28302818
expect(trimmedRecords).toMatchObject([
28312819
{ type: "session", id: sessionId },
@@ -2845,27 +2833,6 @@ describe("session accessor seam", () => {
28452833
expect(updates).toEqual([]);
28462834
});
28472835

2848-
it("keeps every transcript row when the manual compact backup cannot be written", async () => {
2849-
const sessionId = "44444444-4444-4444-8444-444444444444";
2850-
const stateDir = path.join(tempDir, "state-root");
2851-
const scope = {
2852-
agentId: "main",
2853-
env: { ...process.env, OPENCLAW_STATE_DIR: stateDir },
2854-
sessionId,
2855-
sessionKey: "agent:main:main",
2856-
};
2857-
const records = createManualCompactRecords(sessionId);
2858-
await upsertSessionEntryCore(scope, { sessionId, updatedAt: 1 });
2859-
await replaceTranscriptEvents(scope, records as Parameters<typeof replaceTranscriptEvents>[1]);
2860-
const archiveDirPath = path.join(stateDir, "agents", "main", "sessions");
2861-
fs.writeFileSync(archiveDirPath, "not a directory");
2862-
2863-
await expect(trimSessionTranscriptForManualCompact(scope, { maxLines: 3 })).rejects.toThrow();
2864-
2865-
expect((await loadTranscriptEvents(scope)).length).toBe(5);
2866-
expect(await loadTranscriptEvents(scope)).toEqual(records);
2867-
});
2868-
28692836
it("keeps no-op manual compaction tolerant of a missing current session entry", async () => {
28702837
await expect(
28712838
trimTranscriptForManualCompact(
@@ -2921,49 +2888,29 @@ describe("session accessor seam", () => {
29212888

29222889
expect(await loadTranscriptEvents(scope)).toEqual(records);
29232890
expect(loadSessionEntry(scope)).toEqual(entryBeforeCompact);
2924-
const archiveNames = fs.readdirSync(tempDir).filter((name) => name.includes(".bak."));
2925-
expect(archiveNames).toHaveLength(1);
2926-
expect(
2927-
readSessionArchiveContentSync(
2928-
path.join(tempDir, expectDefined(archiveNames[0], "manual compact archive name")),
2929-
),
2930-
).toBe(`${records.map((record) => JSON.stringify(record)).join("\n")}\n`);
29312891
});
29322892

29332893
it.each([
29342894
{
29352895
name: "rejects a manual compact when session metadata changes after its snapshot",
29362896
sessionId: "88888888-8888-4888-8888-888888888888",
29372897
conflict: "metadata",
2938-
reuseArchive: false,
29392898
},
29402899
{
2941-
name: "preserves the backup and rows written after the manual compact snapshot",
2900+
name: "preserves rows written after the manual compact snapshot",
29422901
sessionId: "55555555-5555-4555-8555-555555555555",
29432902
conflict: "transcript",
2944-
reuseArchive: false,
2945-
},
2946-
{
2947-
name: "preserves a reused manual compact backup when the rewrite conflicts",
2948-
sessionId: "66666666-6666-4666-8666-666666666666",
2949-
conflict: "transcript",
2950-
reuseArchive: true,
29512903
},
2952-
] as const)("$name", async ({ sessionId, conflict, reuseArchive }) => {
2904+
] as const)("$name", async ({ sessionId, conflict }) => {
29532905
const scope = { agentId: "main", sessionId, sessionKey: "agent:main:main", storePath };
29542906
const records = createManualCompactRecords(sessionId);
2955-
const archiveContent = `${records.map((record) => JSON.stringify(record)).join("\n")}\n`;
29562907
await upsertSessionEntryCore(
29572908
scope,
29582909
conflict === "metadata"
29592910
? { sessionId, totalTokens: 30, totalTokensFresh: true, updatedAt: 100 }
29602911
: { sessionId, updatedAt: 1 },
29612912
);
29622913
await replaceTranscriptEvents(scope, records as Parameters<typeof replaceTranscriptEvents>[1]);
2963-
const existingArchive = path.join(tempDir, `${sessionId}.jsonl.bak.preexisting`);
2964-
if (reuseArchive) {
2965-
fs.writeFileSync(existingArchive, archiveContent);
2966-
}
29672914

29682915
const expectedError =
29692916
conflict === "metadata"
@@ -3008,18 +2955,6 @@ describe("session accessor seam", () => {
30082955
expect(remaining.slice(0, 5)).toEqual(records);
30092956
expect(remaining[5]).toMatchObject({ id: "late-append" });
30102957
}
3011-
if (reuseArchive) {
3012-
expect(fs.existsSync(existingArchive)).toBe(true);
3013-
expect(readSessionArchiveContentSync(existingArchive)).toBe(archiveContent);
3014-
} else {
3015-
const archiveNames = fs.readdirSync(tempDir).filter((name) => name.includes(".bak."));
3016-
expect(archiveNames).toHaveLength(1);
3017-
expect(
3018-
readSessionArchiveContentSync(
3019-
path.join(tempDir, expectDefined(archiveNames[0], "manual compact archive name")),
3020-
),
3021-
).toBe(archiveContent);
3022-
}
30232958
});
30242959

30252960
it("repairs a retained compaction boundary when its first kept entry was trimmed", async () => {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ export async function trimSessionTranscriptForManualCompact(
116116
return declined;
117117
}
118118

119-
return { archived: trimmed.archivedPath, compacted: true, kept: trimmed.kept };
119+
return { compacted: true, kept: trimmed.kept };
120120
}
121121

122122
function parseManualCompactTranscriptRecord(line: string): Record<string, unknown> | null {

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

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,6 @@ export type SessionTranscriptManualTrimResult =
440440
kept: number;
441441
}
442442
| {
443-
archived: string;
444443
compacted: true;
445444
kept: number;
446445
};

‎src/config/sessions/session-history-eviction.test.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,16 @@ describe("SQLite historical session disk budget", () => {
143143
expect(sessionExists(sessionId)).toBe(false);
144144
});
145145

146-
it("removes counted archives before evicting searchable history", async () => {
146+
it.each([
147+
{
148+
archiveName: "already-extracted.jsonl.deleted.2026-01-01T00-00-00.000Z",
149+
kind: "deleted transcript archive",
150+
},
151+
{
152+
archiveName: `legacy-compact.jsonl.bak.2026-01-01T00-00-00.000Z.${"a".repeat(32)}.zst`,
153+
kind: "legacy compact backup",
154+
},
155+
])("removes a $kind before evicting searchable history", async ({ archiveName }) => {
147156
await createHistoricalTranscript({
148157
content: "keep searchable history",
149158
nextSessionId: "archive-live",
@@ -152,10 +161,7 @@ describe("SQLite historical session disk budget", () => {
152161
updatedAt: 1,
153162
});
154163
database().walMaintenance.checkpoint();
155-
const oldArchive = path.join(
156-
tempDir,
157-
"already-extracted.jsonl.deleted.2026-01-01T00-00-00.000Z",
158-
);
164+
const oldArchive = path.join(tempDir, archiveName);
159165
fs.writeFileSync(oldArchive, Buffer.alloc(256 * 1024));
160166
const before = await measureSessionPhysicalDiskUsage(storePath);
161167

0 commit comments

Comments
 (0)