Skip to content

Commit 4afccbd

Browse files
authored
fix(sessions): exclude protected sessions from entry cap (#123014)
1 parent fce5b66 commit 4afccbd

14 files changed

Lines changed: 369 additions & 137 deletions

‎docs/cli/sessions.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,10 @@ 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.
225229

226230
Flags:
227231

‎docs/concepts/session.md‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,13 @@ 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.
205+
199206
Gateway model-run probe sessions are short-lived by default. Rows matching
200207
`agent:*:explicit:model-run-<uuid>` use fixed `24h` retention, but cleanup is
201208
pressure-gated: it only removes stale probe rows when session-entry
@@ -207,10 +214,10 @@ Maintenance preserves durable external conversation pointers, including group
207214
sessions and thread-scoped chat sessions, while still allowing synthetic cron,
208215
hook, heartbeat, ACP, and sub-agent entries to age out.
209216

210-
Archived sessions are user-shelved and exempt from every automatic maintenance
211-
path, including age pruning, entry caps, model-run cleanup, and disk-budget
212-
eviction. They remain archived until you unarchive them or explicitly delete
213-
them.
217+
Archived and pinned sessions are user-protected and exempt from every automatic
218+
maintenance path, including age pruning, entry caps, model-run cleanup, and
219+
disk-budget eviction. They remain protected until you unarchive, unpin, or
220+
explicitly delete them.
214221

215222
If you previously used DM isolation and later returned `session.dmScope` to
216223
`main`, preview stale peer-keyed DM rows with

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1248,7 +1248,7 @@ See [Multi-Agent Sandbox & Tools](/tools/multi-agent-sandbox-tools) for preceden
12481248
- **`maintenance`**: session-store cleanup + retention controls.
12491249
- `mode`: `enforce` applies cleanup and is the default; `warn` emits warnings only.
12501250
- `pruneAfter`: age cutoff for stale entries (default `30d`).
1251-
- `maxEntries`: maximum number of SQLite session entries (default `500`). Runtime writes batch cleanup with a small high-water buffer for production-sized caps; `openclaw sessions cleanup --enforce` applies the cap immediately.
1251+
- `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.
12521252
- 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.
12531253
- Legacy `rotateBytes` is rejected by the current schema; `openclaw doctor --fix` removes it from older configs.
12541254
- `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: 5 additions & 3 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 session entries |
51+
| `maxEntries` | `500` | cap on eviction-eligible live session rows |
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,9 +70,11 @@ openclaw sessions cleanup --dry-run
7070
openclaw sessions cleanup --enforce
7171
```
7272

73-
Maintenance keeps durable external conversation pointers such as group sessions and thread-scoped chat sessions, but 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` 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.
7474

75-
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 a store 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.
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.
76+
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.
7678

7779
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.
7880

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

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

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

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ 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";
2930
import { collectSessionMaintenancePreserveKeysForStore } from "./store-maintenance-preserve.js";
3031
import { resolveMaintenanceConfig } from "./store-maintenance-runtime.js";
3132
import {
@@ -395,7 +396,7 @@ async function previewStoreCleanup(params: {
395396
});
396397
const modelRunPruned = shouldRunModelRunPrune({
397398
maintenance: params.maintenance,
398-
entryCount: Object.keys(previewStore).length,
399+
entryCount: countSessionEntryMaintenanceEligibleEntries(previewStore, preserveSessionKeys),
399400
// `sessions cleanup` applies the cap immediately (apply path forces maintenance and the
400401
// preview caps unconditionally below), so mirror that here: prune stale probes before the
401402
// forced cap can evict real sessions in their place.

‎src/config/sessions/incognito-session-transcript.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,14 @@ describe("incognito transcript access", () => {
112112
storePath,
113113
};
114114
const now = Date.now();
115+
const staleUpdatedAt = now - 366 * 24 * 60 * 60 * 1000;
115116

116117
try {
117118
await patchSessionEntryCore(
118119
staleScope,
119-
() => ({ sessionId: "incognito-stale-session", updatedAt: now }),
120+
() => ({ sessionId: "incognito-stale-session", updatedAt: staleUpdatedAt }),
120121
{
121-
fallbackEntry: { sessionId: "incognito-stale-session", updatedAt: now },
122+
fallbackEntry: { sessionId: "incognito-stale-session", updatedAt: staleUpdatedAt },
122123
replaceEntry: true,
123124
skipMaintenance: true,
124125
},

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

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1657,7 +1657,101 @@ describe("sqlite session normalization", () => {
16571657
env,
16581658
storePath: paths.sqlitePath,
16591659
}).map((summary) => summary.sessionKey),
1660-
).toEqual(["agent:main:newer", "agent:main:newest"]);
1660+
).toEqual(["agent:main:active", "agent:main:newer", "agent:main:newest"]);
1661+
});
1662+
1663+
it("keeps protected SQLite rows outside the write-triggered entry allowance", async () => {
1664+
vi.mocked(getRuntimeConfig).mockReturnValue({
1665+
session: {
1666+
maintenance: {
1667+
mode: "enforce",
1668+
pruneAfter: "365d",
1669+
maxEntries: 2,
1670+
},
1671+
},
1672+
});
1673+
const env = { ...process.env, OPENCLAW_STATE_DIR: paths.stateDir };
1674+
const now = Date.now();
1675+
const scopeFor = (sessionKey: string) => ({
1676+
agentId: "main",
1677+
env,
1678+
sessionKey,
1679+
storePath: paths.sqlitePath,
1680+
});
1681+
const recentSessionId = "recent-dashboard-session-1";
1682+
const recentTranscriptEvent = {
1683+
id: "recent-dashboard-event",
1684+
timestamp: new Date().toISOString(),
1685+
type: "metadata",
1686+
};
1687+
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,
1699+
},
1700+
);
1701+
}
1702+
await patchSessionEntryCore(
1703+
scopeFor("agent:main:recent-dashboard-1"),
1704+
() => ({ sessionId: recentSessionId, updatedAt: now - 2 }),
1705+
{
1706+
fallbackEntry: { sessionId: recentSessionId, updatedAt: now - 2 },
1707+
replaceEntry: true,
1708+
skipMaintenance: true,
1709+
},
1710+
);
1711+
await appendTranscriptEvent(
1712+
{ ...scopeFor("agent:main:recent-dashboard-1"), sessionId: recentSessionId },
1713+
recentTranscriptEvent,
1714+
);
1715+
await patchSessionEntryCore(
1716+
scopeFor("agent:main:recent-dashboard-2"),
1717+
() => ({ sessionId: "recent-dashboard-session-2", updatedAt: now - 1 }),
1718+
{
1719+
fallbackEntry: { sessionId: "recent-dashboard-session-2", updatedAt: now - 1 },
1720+
replaceEntry: true,
1721+
skipMaintenance: true,
1722+
},
1723+
);
1724+
1725+
await patchSessionEntryCore(
1726+
scopeFor("agent:main:maintenance-trigger"),
1727+
() => ({ sessionId: "maintenance-trigger-session", updatedAt: now }),
1728+
{
1729+
fallbackEntry: { sessionId: "maintenance-trigger-session", updatedAt: now },
1730+
replaceEntry: true,
1731+
},
1732+
);
1733+
1734+
expect(
1735+
listSessionEntryRows({
1736+
agentId: "main",
1737+
env,
1738+
storePath: paths.sqlitePath,
1739+
}).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+
]);
1747+
await expect(
1748+
loadTranscriptEvents({
1749+
agentId: "main",
1750+
env,
1751+
sessionId: recentSessionId,
1752+
storePath: paths.sqlitePath,
1753+
}),
1754+
).resolves.toEqual([recentTranscriptEvent]);
16611755
});
16621756

16631757
it("preserves pinned SQLite entries and transcripts during write-triggered capping", async () => {

0 commit comments

Comments
 (0)