Skip to content

Commit a01d40b

Browse files
authored
fix(sessions): honor total entry cap with protected history (#123081)
* fix(sessions): count protected rows toward entry cap * perf(sessions): defer maintenance snapshot loading * test(sessions): assert total maintenance cap * fix(sessions): align warning preservation * fix(sessions): guard malformed maintenance rows
1 parent d913796 commit a01d40b

16 files changed

Lines changed: 332 additions & 267 deletions

‎docs/cli/sessions.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -222,10 +222,12 @@ openclaw sessions cleanup --json
222222
pressure-gated: it only removes stale probe rows when session-entry
223223
maintenance/cap pressure is reached. When it runs, model-run cleanup
224224
happens before global stale cleanup and capping.
225-
- `maxEntries` caps only eviction-eligible rows. Protected rows are reported as
226-
`keep` and stay outside the allowance, so the total row count can exceed the
227-
configured cap. `--enforce` does not remove that protection; unarchive,
228-
unpin, or explicitly delete sessions you no longer want to retain.
225+
- `maxEntries` caps the total live session row count. Protected rows are
226+
reported as `keep` and count toward the cap, but they are never automatic
227+
eviction targets. If protected rows prevent cleanup from reaching the cap,
228+
the store remains above it. `--enforce` does not remove that protection;
229+
unarchive, unpin, wait for active work to finish, or explicitly delete
230+
sessions you no longer want to retain.
229231

230232
Flags:
231233

@@ -235,7 +237,7 @@ Flags:
235237
| `--enforce` | Apply maintenance even when `session.maintenance.mode` is `warn`. |
236238
| `--fix-missing` | Remove legacy entries whose archived transcript artifacts are missing or header-only/empty, even if they would not normally age/count out yet. |
237239
| `--fix-dm-scope` | When `session.dmScope` is `main`, retire stale peer-keyed direct-DM rows left behind by earlier `per-peer`, `per-channel-peer`, or `per-account-channel-peer` routing. Use `--dry-run` first; applying removes those rows from SQLite and preserves their legacy transcript artifacts as deleted archives. |
238-
| `--active-key <key>` | Protect a specific active key from disk-budget eviction. Durable external conversation pointers, such as group sessions and thread-scoped chat sessions, are also kept by age/count/disk-budget maintenance. |
240+
| `--active-key <key>` | Protect a specific active key from automatic maintenance. It still counts toward `maxEntries`. Durable external conversation pointers, such as group sessions and thread-scoped chat sessions, are also kept by age/count/disk-budget maintenance. |
239241
| `--agent <id>` | Run cleanup for one configured agent store. |
240242
| `--all-agents` | Run cleanup for all configured agent stores. |
241243
| `--store <path>` | Run against a specific legacy store selector path. |

‎docs/concepts/session.md‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -196,12 +196,14 @@ Session store reads do not prune or cap entries during Gateway startup, so
196196
startup and isolated cron sessions do not pay for a full store cleanup.
197197
`openclaw sessions cleanup --enforce` applies the cap immediately.
198198

199-
`maxEntries` counts only eviction-eligible session rows. Protected rows -
200-
archived or pinned sessions, active or admitted work, model-locked sessions,
201-
and durable external conversation pointers - stay outside that allowance, so
202-
the total stored row count can exceed `maxEntries`. Cleanup does not unprotect
203-
those rows; unarchive, unpin, or explicitly delete sessions you no longer want
204-
to retain.
199+
`maxEntries` counts every live session row. Archived or pinned sessions, active
200+
or admitted work, model-locked sessions, and durable external conversation
201+
pointers are protected from automatic eviction, but still consume the cap.
202+
Cleanup removes the oldest unprotected rows until it reaches `maxEntries` or
203+
runs out of eligible victims. The total can therefore remain above the cap when
204+
protected rows alone exceed it or active work temporarily blocks eviction.
205+
Cleanup does not unprotect those rows; unarchive, unpin, wait for active work to
206+
finish, or explicitly delete sessions you no longer want to retain.
205207

206208
Gateway model-run probe sessions are short-lived by default. Rows matching
207209
`agent:*:explicit:model-run-<uuid>` use fixed `24h` retention, but cleanup is

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1263,7 +1263,7 @@ See [Multi-Agent Sandbox & Tools](/tools/multi-agent-sandbox-tools) for preceden
12631263
- **`maintenance`**: session-store cleanup + retention controls.
12641264
- `mode`: `enforce` applies cleanup and is the default; `warn` emits warnings only.
12651265
- `pruneAfter`: age cutoff for stale entries (default `30d`).
1266-
- `maxEntries`: maximum number of eviction-eligible SQLite session entries (default `500`). Archived or pinned sessions, active or admitted work, model-locked sessions, and durable external conversation pointers stay outside the allowance, so the total row count can exceed this value. Runtime writes batch cleanup with a small high-water buffer for production-sized caps; `openclaw sessions cleanup --enforce` applies the eligible-row cap immediately but does not unprotect rows. Unarchive, unpin, or explicitly delete protected sessions to reduce their count.
1266+
- `maxEntries`: maximum total number of live SQLite session entries (default `500`). Every row counts toward the cap, but archived or pinned sessions, active or admitted work, model-locked sessions, and durable external conversation pointers are never automatic eviction targets. Cleanup removes the oldest unprotected rows; if protection prevents reaching the cap, the store remains above it. Runtime writes batch cleanup with a small high-water buffer for production-sized caps; `openclaw sessions cleanup --enforce` applies the cap immediately but does not unprotect rows. Unarchive, unpin, wait for active work to finish, or explicitly delete protected sessions to reduce the total.
12671267
- Short-lived gateway model-run probe sessions use fixed `24h` retention, but cleanup is pressure-gated: it only removes stale strict model-run probe rows when session-entry maintenance/cap pressure is reached. Only strict explicit probe keys matching `agent:*:explicit:model-run-<uuid>` are eligible; normal direct, group, thread, cron, hook, heartbeat, ACP, and sub-agent sessions do not inherit this 24h retention. When model-run cleanup runs, it runs before the broader `pruneAfter` stale-entry cleanup and `maxEntries` cap.
12681268
- Legacy `rotateBytes` is rejected by the current schema; `openclaw doctor --fix` removes it from older configs.
12691269
- `resetArchiveRetention`: age-based retention for reset/deleted transcript archives. By default, archives remain until disk-budget eviction; set a duration to opt into wall-clock deletion, or `false` to disable it explicitly.

‎docs/reference/session-management-compaction.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ Per agent, on the Gateway host (resolved via `src/config/sessions.ts`):
4848
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------- |
4949
| `mode` | `"enforce"` | or `"warn"` (report only, no mutation) |
5050
| `pruneAfter` | `"30d"` | stale-entry age cutoff |
51-
| `maxEntries` | `500` | cap on eviction-eligible live session rows |
51+
| `maxEntries` | `500` | cap on total live session rows when protection permits |
5252
| `resetArchiveRetention` | keep (no age cutoff) | age cutoff for `*.reset.*`/`*.deleted.*` transcript archives; a duration opts into deletion |
5353
| `maxDiskBytes` | `10gb` | per-agent sessions disk budget; `false`, `0`, or `"0"` disables |
5454
| `highWaterBytes` | 80% of `maxDiskBytes` | target after cleanup; zero-resolving values use the default, and negatives are invalid |
@@ -70,11 +70,11 @@ openclaw sessions cleanup --dry-run
7070
openclaw sessions cleanup --enforce
7171
```
7272

73-
`maxEntries` excludes protected rows: archived or pinned sessions, active or admitted work, model-locked sessions, and durable external conversation pointers such as group sessions and thread-scoped chat sessions. Those rows do not consume the allowance, so the total live session row count can exceed `maxEntries`. Synthetic runtime entries (cron, hooks, heartbeat, ACP, sub-agents) can still be removed once they exceed the configured age, count, or disk budget. Isolated cron runs use a separate `cron.sessionRetention` control, independent of model-run probe retention.
73+
`maxEntries` counts every live session row. Archived or pinned sessions, active or admitted work, model-locked sessions, and durable external conversation pointers such as group sessions and thread-scoped chat sessions are never automatic eviction targets, but they still consume the cap. Cleanup removes the oldest unprotected rows until the total reaches `maxEntries` or no eligible victims remain. The store can therefore remain above the cap when protected rows alone exceed it or active work temporarily blocks eviction. Synthetic runtime entries (cron, hooks, heartbeat, ACP, sub-agents) can still be removed once they exceed the configured age, count, or disk budget. Isolated cron runs use a separate `cron.sessionRetention` control, independent of model-run probe retention.
7474

75-
`--dry-run` previews maintenance against the eligible population; `--enforce` applies that cleanup immediately but does not remove protection. To reduce protected history, unarchive, unpin, or explicitly delete sessions you no longer want to retain.
75+
`--dry-run` previews the total-row cap and identifies the unprotected rows that would satisfy it; `--enforce` applies that cleanup immediately but does not remove protection. To reduce protected history, unarchive, unpin, wait for active work to finish, or explicitly delete sessions you no longer want to retain.
7676

77-
Normal Gateway writes flow through the session accessor, which serializes per-agent SQLite mutations through the runtime writer path. Runtime code should prefer the accessor helpers in `src/config/sessions/session-accessor.ts`; legacy `sessions.json` helpers are migration and offline-maintenance tools. When a Gateway is reachable, non-dry-run `openclaw sessions cleanup` and `openclaw agents delete` delegate store mutations to the Gateway so cleanup joins the same writer queue; `--store <path>` is the explicit offline repair path for a selected legacy store and always stays local (as does `--dry-run`). `maxEntries` cleanup is batched for production-sized stores, so the eligible population may briefly exceed the configured cap before the next high-water cleanup rewrites it down. Reads never prune or cap entries during Gateway startup - only writes or `openclaw sessions cleanup --enforce` do, and the latter also applies the cap immediately and prunes old unreferenced legacy transcript, checkpoint, and trajectory artifacts even with no disk budget configured.
77+
Normal Gateway writes flow through the session accessor, which serializes per-agent SQLite mutations through the runtime writer path. Runtime code should prefer the accessor helpers in `src/config/sessions/session-accessor.ts`; legacy `sessions.json` helpers are migration and offline-maintenance tools. When a Gateway is reachable, non-dry-run `openclaw sessions cleanup` and `openclaw agents delete` delegate store mutations to the Gateway so cleanup joins the same writer queue; `--store <path>` is the explicit offline repair path for a selected legacy store and always stays local (as does `--dry-run`). `maxEntries` cleanup is batched for production-sized stores, so the total population may briefly exceed the configured cap before the next high-water cleanup rewrites it down. Reads never prune or cap entries during Gateway startup - only writes or `openclaw sessions cleanup --enforce` do, and the latter also applies the cap immediately and prunes old unreferenced legacy transcript, checkpoint, and trajectory artifacts even with no disk budget configured.
7878

7979
OpenClaw no longer creates automatic `sessions.json.bak.*` rotation backups during Gateway writes. The current schema rejects the legacy `session.maintenance.rotateBytes` key, and `openclaw doctor --fix` removes it from older configs.
8080

‎src/agents/command/session-store.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ describe("updateSessionStoreAfterAgentRun", () => {
385385
});
386386

387387
const persisted = loadPersistedSessionStore(storePath);
388-
expect(Object.keys(persisted).filter((key) => key !== sessionKey)).toHaveLength(42);
388+
expect(Object.keys(persisted)).toHaveLength(42);
389389
expect(persisted[sessionKey]?.sessionId).toBe(sessionId);
390390
expect(persisted["agent:main:stale:44"]).toBeUndefined();
391391
});

‎src/config/schema.help.automation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export const AUTOMATION_FIELD_HELP: Record<string, string> = {
7777
"session.maintenance.pruneAfter":
7878
"Removes entries older than this duration (for example `30d` or `12h`) during maintenance passes. Use this as the primary age-retention control and align it with data retention policy.",
7979
"session.maintenance.maxEntries":
80-
"Caps total session entry count retained in the store to prevent unbounded growth over time. Use lower limits for constrained environments, or higher limits when longer history is required.",
80+
"Caps total session entry count retained in the store to prevent unbounded growth over time. Protected entries count toward the limit but are never automatically removed, so the store can remain above the cap when protection alone exceeds it. Use lower limits for constrained environments, or higher limits when longer history is required.",
8181
"session.maintenance.resetArchiveRetention":
8282
"Age-based retention for archived transcripts (`*.reset.<timestamp>` and `*.deleted.<timestamp>`). Defaults to keeping archives until the disk budget evicts them oldest-first; set a duration (for example `30d`) to opt into wall-clock deletion, or `false` to disable it explicitly.",
8383
"session.maintenance.maxDiskBytes":

‎src/config/sessions/cleanup-service.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import {
2626
inspectSqliteSessionHistoryDiskBudget,
2727
} from "./session-history-eviction.js";
2828
import { resolveSqliteTargetFromSessionStorePath } from "./session-sqlite-target.js";
29-
import { countSessionEntryMaintenanceEligibleEntries } from "./store-maintenance-eligibility.js";
3029
import { collectSessionMaintenancePreserveKeysForStore } from "./store-maintenance-preserve.js";
3130
import { resolveMaintenanceConfig } from "./store-maintenance-runtime.js";
3231
import {
@@ -396,7 +395,7 @@ async function previewStoreCleanup(params: {
396395
});
397396
const modelRunPruned = shouldRunModelRunPrune({
398397
maintenance: params.maintenance,
399-
entryCount: countSessionEntryMaintenanceEligibleEntries(previewStore, preserveSessionKeys),
398+
entryCount: Object.keys(previewStore).length,
400399
// `sessions cleanup` applies the cap immediately (apply path forces maintenance and the
401400
// preview caps unconditionally below), so mirror that here: prune stale probes before the
402401
// forced cap can evict real sessions in their place.

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

Lines changed: 50 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,33 @@ describe("sqlite session normalization", () => {
13231323
).toEqual({ entry_valid: 0 });
13241324
});
13251325

1326+
it("writes a valid session beside an unrelated malformed legacy row", async () => {
1327+
const env = { ...process.env, OPENCLAW_STATE_DIR: paths.stateDir };
1328+
const database = openOpenClawAgentDatabase({ agentId: "main", env, path: paths.sqlitePath });
1329+
database.db
1330+
.prepare(
1331+
"INSERT INTO session_nodes (session_key, current_session_id, entry_json, entry_valid, updated_at) VALUES (?, ?, ?, -1, ?)",
1332+
)
1333+
.run("agent:main:malformed", "malformed-session", "{ malformed", 0);
1334+
1335+
await expect(
1336+
replaceSessionEntry(
1337+
{
1338+
agentId: "main",
1339+
env,
1340+
sessionKey: "agent:main:valid",
1341+
storePath: paths.sqlitePath,
1342+
},
1343+
{ sessionId: "valid-session", updatedAt: Date.now() },
1344+
),
1345+
).resolves.toMatchObject({ sessionId: "valid-session" });
1346+
expect(
1347+
database.db
1348+
.prepare("SELECT entry_json FROM session_nodes WHERE session_key = ?")
1349+
.get("agent:main:malformed"),
1350+
).toEqual({ entry_json: "{ malformed" });
1351+
});
1352+
13261353
it("exposes same-key rollover lineage when a killed session is replaced", async () => {
13271354
const env = { ...process.env, OPENCLAW_STATE_DIR: paths.stateDir };
13281355
const sessionKey = "agent:main:telegram:group:-1003774691294:topic:29020";
@@ -1657,10 +1684,10 @@ describe("sqlite session normalization", () => {
16571684
env,
16581685
storePath: paths.sqlitePath,
16591686
}).map((summary) => summary.sessionKey),
1660-
).toEqual(["agent:main:active", "agent:main:newer", "agent:main:newest"]);
1687+
).toEqual(["agent:main:newer", "agent:main:newest"]);
16611688
});
16621689

1663-
it("keeps protected SQLite rows outside the write-triggered entry allowance", async () => {
1690+
it("counts protected SQLite rows while preserving them during write-triggered capping", async () => {
16641691
vi.mocked(getRuntimeConfig).mockReturnValue({
16651692
session: {
16661693
maintenance: {
@@ -1685,20 +1712,19 @@ describe("sqlite session normalization", () => {
16851712
type: "metadata",
16861713
};
16871714

1688-
for (const [sessionKey, sessionId, updatedAt] of [
1689-
["agent:main:archived-1", "archived-session-1", now - 4],
1690-
["agent:main:archived-2", "archived-session-2", now - 3],
1691-
] as const) {
1692-
await patchSessionEntryCore(
1693-
scopeFor(sessionKey),
1694-
() => ({ archivedAt: updatedAt, sessionId, updatedAt }),
1695-
{
1696-
fallbackEntry: { archivedAt: updatedAt, sessionId, updatedAt },
1697-
replaceEntry: true,
1698-
skipMaintenance: true,
1715+
await patchSessionEntryCore(
1716+
scopeFor("agent:main:archived-1"),
1717+
() => ({ archivedAt: now - 4, sessionId: "archived-session-1", updatedAt: now - 4 }),
1718+
{
1719+
fallbackEntry: {
1720+
archivedAt: now - 4,
1721+
sessionId: "archived-session-1",
1722+
updatedAt: now - 4,
16991723
},
1700-
);
1701-
}
1724+
replaceEntry: true,
1725+
skipMaintenance: true,
1726+
},
1727+
);
17021728
await patchSessionEntryCore(
17031729
scopeFor("agent:main:recent-dashboard-1"),
17041730
() => ({ sessionId: recentSessionId, updatedAt: now - 2 }),
@@ -1737,21 +1763,15 @@ describe("sqlite session normalization", () => {
17371763
env,
17381764
storePath: paths.sqlitePath,
17391765
}).map((summary) => summary.sessionKey),
1740-
).toEqual([
1741-
"agent:main:archived-1",
1742-
"agent:main:archived-2",
1743-
"agent:main:maintenance-trigger",
1744-
"agent:main:recent-dashboard-1",
1745-
"agent:main:recent-dashboard-2",
1746-
]);
1766+
).toEqual(["agent:main:archived-1", "agent:main:maintenance-trigger"]);
17471767
await expect(
17481768
loadTranscriptEvents({
17491769
agentId: "main",
17501770
env,
17511771
sessionId: recentSessionId,
17521772
storePath: paths.sqlitePath,
17531773
}),
1754-
).resolves.toEqual([recentTranscriptEvent]);
1774+
).resolves.toEqual([]);
17551775
});
17561776

17571777
it("preserves pinned SQLite entries and transcripts during write-triggered capping", async () => {
@@ -1815,6 +1835,13 @@ describe("sqlite session normalization", () => {
18151835
pinnedAt: 2,
18161836
sessionId: pinnedSessionId,
18171837
});
1838+
expect(
1839+
listSessionEntryRows({
1840+
agentId: "main",
1841+
env,
1842+
storePath: paths.sqlitePath,
1843+
}).map((summary) => summary.sessionKey),
1844+
).toEqual(["agent:main:maintenance-trigger", pinnedKey]);
18181845
await expect(
18191846
loadTranscriptEvents({
18201847
agentId: "main",

0 commit comments

Comments
 (0)