Skip to content

Commit eff3c5c

Browse files
Session/Cron maintenance hardening and cleanup UX (#24753)
Merged via /review-pr -> /prepare-pr -> /merge-pr. Prepared head SHA: 7533b85 Co-authored-by: gumadeiras <[email protected]> Co-authored-by: shakkernerd <[email protected]> Reviewed-by: @shakkernerd
1 parent 29b1945 commit eff3c5c

49 files changed

Lines changed: 3179 additions & 234 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Docs: https://docs.openclaw.ai
1111
- Providers/Vercel AI Gateway: accept Claude shorthand model refs (`vercel-ai-gateway/claude-*`) by normalizing to canonical Anthropic-routed model ids. (#23985) Thanks @sallyom, @markbooch, and @vincentkoc.
1212
- Docs/Prompt caching: add a dedicated prompt-caching reference covering `cacheRetention`, per-agent `params` merge precedence, Bedrock/OpenRouter behavior, and cache-ttl + heartbeat tuning. Thanks @svenssonaxel.
1313
- Gateway/HTTP security headers: add optional `gateway.http.securityHeaders.strictTransportSecurity` support to emit `Strict-Transport-Security` for direct HTTPS deployments, with runtime wiring, validation, tests, and hardening docs.
14+
- Sessions/Cron: harden session maintenance with `openclaw sessions cleanup`, per-agent store targeting, disk-budget controls (`session.maintenance.maxDiskBytes` / `highWaterBytes`), and safer transcript/archive cleanup + run-log retention behavior. (#24753) thanks @gumadeiras.
1415

1516
### Breaking
1617

‎docs/automation/cron-jobs.md‎

Lines changed: 92 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,8 @@ Notes:
349349
## Storage & history
350350

351351
- Job store: `~/.openclaw/cron/jobs.json` (Gateway-managed JSON).
352-
- Run history: `~/.openclaw/cron/runs/<jobId>.jsonl` (JSONL, auto-pruned).
352+
- Run history: `~/.openclaw/cron/runs/<jobId>.jsonl` (JSONL, auto-pruned by size and line count).
353+
- Isolated cron run sessions in `sessions.json` are pruned by `cron.sessionRetention` (default `24h`; set `false` to disable).
353354
- Override store path: `cron.store` in config.
354355

355356
## Configuration
@@ -362,10 +363,21 @@ Notes:
362363
maxConcurrentRuns: 1, // default 1
363364
webhook: "https://example.invalid/legacy", // deprecated fallback for stored notify:true jobs
364365
webhookToken: "replace-with-dedicated-webhook-token", // optional bearer token for webhook mode
366+
sessionRetention: "24h", // duration string or false
367+
runLog: {
368+
maxBytes: "2mb", // default 2_000_000 bytes
369+
keepLines: 2000, // default 2000
370+
},
365371
},
366372
}
367373
```
368374

375+
Run-log pruning behavior:
376+
377+
- `cron.runLog.maxBytes`: max run-log file size before pruning.
378+
- `cron.runLog.keepLines`: when pruning, keep only the newest N lines.
379+
- Both apply to `cron/runs/<jobId>.jsonl` files.
380+
369381
Webhook behavior:
370382

371383
- Preferred: set `delivery.mode: "webhook"` with `delivery.to: "https://..."` per job.
@@ -380,6 +392,85 @@ Disable cron entirely:
380392
- `cron.enabled: false` (config)
381393
- `OPENCLAW_SKIP_CRON=1` (env)
382394

395+
## Maintenance
396+
397+
Cron has two built-in maintenance paths: isolated run-session retention and run-log pruning.
398+
399+
### Defaults
400+
401+
- `cron.sessionRetention`: `24h` (set `false` to disable run-session pruning)
402+
- `cron.runLog.maxBytes`: `2_000_000` bytes
403+
- `cron.runLog.keepLines`: `2000`
404+
405+
### How it works
406+
407+
- Isolated runs create session entries (`...:cron:<jobId>:run:<uuid>`) and transcript files.
408+
- The reaper removes expired run-session entries older than `cron.sessionRetention`.
409+
- For removed run sessions no longer referenced by the session store, OpenClaw archives transcript files and purges old deleted archives on the same retention window.
410+
- After each run append, `cron/runs/<jobId>.jsonl` is size-checked:
411+
- if file size exceeds `runLog.maxBytes`, it is trimmed to the newest `runLog.keepLines` lines.
412+
413+
### Performance caveat for high volume schedulers
414+
415+
High-frequency cron setups can generate large run-session and run-log footprints. Maintenance is built in, but loose limits can still create avoidable IO and cleanup work.
416+
417+
What to watch:
418+
419+
- long `cron.sessionRetention` windows with many isolated runs
420+
- high `cron.runLog.keepLines` combined with large `runLog.maxBytes`
421+
- many noisy recurring jobs writing to the same `cron/runs/<jobId>.jsonl`
422+
423+
What to do:
424+
425+
- keep `cron.sessionRetention` as short as your debugging/audit needs allow
426+
- keep run logs bounded with moderate `runLog.maxBytes` and `runLog.keepLines`
427+
- move noisy background jobs to isolated mode with delivery rules that avoid unnecessary chatter
428+
- review growth periodically with `openclaw cron runs` and adjust retention before logs become large
429+
430+
### Customize examples
431+
432+
Keep run sessions for a week and allow bigger run logs:
433+
434+
```json5
435+
{
436+
cron: {
437+
sessionRetention: "7d",
438+
runLog: {
439+
maxBytes: "10mb",
440+
keepLines: 5000,
441+
},
442+
},
443+
}
444+
```
445+
446+
Disable isolated run-session pruning but keep run-log pruning:
447+
448+
```json5
449+
{
450+
cron: {
451+
sessionRetention: false,
452+
runLog: {
453+
maxBytes: "5mb",
454+
keepLines: 3000,
455+
},
456+
},
457+
}
458+
```
459+
460+
Tune for high-volume cron usage (example):
461+
462+
```json5
463+
{
464+
cron: {
465+
sessionRetention: "12h",
466+
runLog: {
467+
maxBytes: "3mb",
468+
keepLines: 1500,
469+
},
470+
},
471+
}
472+
```
473+
383474
## CLI quickstart
384475

385476
One-shot reminder (UTC ISO, auto-delete after success):

‎docs/cli/cron.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,11 @@ Note: one-shot (`--at`) jobs delete after success by default. Use `--keep-after-
2323

2424
Note: recurring jobs now use exponential retry backoff after consecutive errors (30s → 1m → 5m → 15m → 60m), then return to normal schedule after the next successful run.
2525

26+
Note: retention/pruning is controlled in config:
27+
28+
- `cron.sessionRetention` (default `24h`) prunes completed isolated run sessions.
29+
- `cron.runLog.maxBytes` + `cron.runLog.keepLines` prune `~/.openclaw/cron/runs/<jobId>.jsonl`.
30+
2631
## Common edits
2732

2833
Update delivery settings without changing the message:

‎docs/cli/doctor.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Notes:
2727

2828
- Interactive prompts (like keychain/OAuth fixes) only run when stdin is a TTY and `--non-interactive` is **not** set. Headless runs (cron, Telegram, no terminal) will skip prompts.
2929
- `--fix` (alias for `--repair`) writes a backup to `~/.openclaw/openclaw.json.bak` and drops unknown config keys, listing each removal.
30+
- State integrity checks now detect orphan transcript files in the sessions directory and can archive them as `.deleted.<timestamp>` to reclaim space safely.
3031

3132
## macOS: `launchctl` env overrides
3233

‎docs/cli/sessions.md‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,94 @@ List stored conversation sessions.
1111

1212
```bash
1313
openclaw sessions
14+
openclaw sessions --agent work
15+
openclaw sessions --all-agents
1416
openclaw sessions --active 120
1517
openclaw sessions --json
1618
```
19+
20+
Scope selection:
21+
22+
- default: configured default agent store
23+
- `--agent <id>`: one configured agent store
24+
- `--all-agents`: aggregate all configured agent stores
25+
- `--store <path>`: explicit store path (cannot be combined with `--agent` or `--all-agents`)
26+
27+
JSON examples:
28+
29+
`openclaw sessions --all-agents --json`:
30+
31+
```json
32+
{
33+
"path": null,
34+
"stores": [
35+
{ "agentId": "main", "path": "/home/user/.openclaw/agents/main/sessions/sessions.json" },
36+
{ "agentId": "work", "path": "/home/user/.openclaw/agents/work/sessions/sessions.json" }
37+
],
38+
"allAgents": true,
39+
"count": 2,
40+
"activeMinutes": null,
41+
"sessions": [
42+
{ "agentId": "main", "key": "agent:main:main", "model": "gpt-5" },
43+
{ "agentId": "work", "key": "agent:work:main", "model": "claude-opus-4-5" }
44+
]
45+
}
46+
```
47+
48+
## Cleanup maintenance
49+
50+
Run maintenance now (instead of waiting for the next write cycle):
51+
52+
```bash
53+
openclaw sessions cleanup --dry-run
54+
openclaw sessions cleanup --agent work --dry-run
55+
openclaw sessions cleanup --all-agents --dry-run
56+
openclaw sessions cleanup --enforce
57+
openclaw sessions cleanup --enforce --active-key "agent:main:telegram:dm:123"
58+
openclaw sessions cleanup --json
59+
```
60+
61+
`openclaw sessions cleanup` uses `session.maintenance` settings from config:
62+
63+
- Scope note: `openclaw sessions cleanup` maintains session stores/transcripts only. It does not prune cron run logs (`cron/runs/<jobId>.jsonl`), which are managed by `cron.runLog.maxBytes` and `cron.runLog.keepLines` in [Cron configuration](/automation/cron-jobs#configuration) and explained in [Cron maintenance](/automation/cron-jobs#maintenance).
64+
65+
- `--dry-run`: preview how many entries would be pruned/capped without writing.
66+
- In text mode, dry-run prints a per-session action table (`Action`, `Key`, `Age`, `Model`, `Flags`) so you can see what would be kept vs removed.
67+
- `--enforce`: apply maintenance even when `session.maintenance.mode` is `warn`.
68+
- `--active-key <key>`: protect a specific active key from disk-budget eviction.
69+
- `--agent <id>`: run cleanup for one configured agent store.
70+
- `--all-agents`: run cleanup for all configured agent stores.
71+
- `--store <path>`: run against a specific `sessions.json` file.
72+
- `--json`: print a JSON summary. With `--all-agents`, output includes one summary per store.
73+
74+
`openclaw sessions cleanup --all-agents --dry-run --json`:
75+
76+
```json
77+
{
78+
"allAgents": true,
79+
"mode": "warn",
80+
"dryRun": true,
81+
"stores": [
82+
{
83+
"agentId": "main",
84+
"storePath": "/home/user/.openclaw/agents/main/sessions/sessions.json",
85+
"beforeCount": 120,
86+
"afterCount": 80,
87+
"pruned": 40,
88+
"capped": 0
89+
},
90+
{
91+
"agentId": "work",
92+
"storePath": "/home/user/.openclaw/agents/work/sessions/sessions.json",
93+
"beforeCount": 18,
94+
"afterCount": 18,
95+
"pruned": 0,
96+
"capped": 0
97+
}
98+
]
99+
}
100+
```
101+
102+
Related:
103+
104+
- Session config: [Configuration reference](/gateway/configuration-reference#session)

‎docs/concepts/session.md‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,109 @@ All session state is **owned by the gateway** (the “master” OpenClaw). UI cl
7171
- Session entries include `origin` metadata (label + routing hints) so UIs can explain where a session came from.
7272
- OpenClaw does **not** read legacy Pi/Tau session folders.
7373

74+
## Maintenance
75+
76+
OpenClaw applies session-store maintenance to keep `sessions.json` and transcript artifacts bounded over time.
77+
78+
### Defaults
79+
80+
- `session.maintenance.mode`: `warn`
81+
- `session.maintenance.pruneAfter`: `30d`
82+
- `session.maintenance.maxEntries`: `500`
83+
- `session.maintenance.rotateBytes`: `10mb`
84+
- `session.maintenance.resetArchiveRetention`: defaults to `pruneAfter` (`30d`)
85+
- `session.maintenance.maxDiskBytes`: unset (disabled)
86+
- `session.maintenance.highWaterBytes`: defaults to `80%` of `maxDiskBytes` when budgeting is enabled
87+
88+
### How it works
89+
90+
Maintenance runs during session-store writes, and you can trigger it on demand with `openclaw sessions cleanup`.
91+
92+
- `mode: "warn"`: reports what would be evicted but does not mutate entries/transcripts.
93+
- `mode: "enforce"`: applies cleanup in this order:
94+
1. prune stale entries older than `pruneAfter`
95+
2. cap entry count to `maxEntries` (oldest first)
96+
3. archive transcript files for removed entries that are no longer referenced
97+
4. purge old `*.deleted.<timestamp>` and `*.reset.<timestamp>` archives by retention policy
98+
5. rotate `sessions.json` when it exceeds `rotateBytes`
99+
6. if `maxDiskBytes` is set, enforce disk budget toward `highWaterBytes` (oldest artifacts first, then oldest sessions)
100+
101+
### Performance caveat for large stores
102+
103+
Large session stores are common in high-volume setups. Maintenance work is write-path work, so very large stores can increase write latency.
104+
105+
What increases cost most:
106+
107+
- very high `session.maintenance.maxEntries` values
108+
- long `pruneAfter` windows that keep stale entries around
109+
- many transcript/archive artifacts in `~/.openclaw/agents/<agentId>/sessions/`
110+
- enabling disk budgets (`maxDiskBytes`) without reasonable pruning/cap limits
111+
112+
What to do:
113+
114+
- use `mode: "enforce"` in production so growth is bounded automatically
115+
- set both time and count limits (`pruneAfter` + `maxEntries`), not just one
116+
- set `maxDiskBytes` + `highWaterBytes` for hard upper bounds in large deployments
117+
- keep `highWaterBytes` meaningfully below `maxDiskBytes` (default is 80%)
118+
- run `openclaw sessions cleanup --dry-run --json` after config changes to verify projected impact before enforcing
119+
- for frequent active sessions, pass `--active-key` when running manual cleanup
120+
121+
### Customize examples
122+
123+
Use a conservative enforce policy:
124+
125+
```json5
126+
{
127+
session: {
128+
maintenance: {
129+
mode: "enforce",
130+
pruneAfter: "45d",
131+
maxEntries: 800,
132+
rotateBytes: "20mb",
133+
resetArchiveRetention: "14d",
134+
},
135+
},
136+
}
137+
```
138+
139+
Enable a hard disk budget for the sessions directory:
140+
141+
```json5
142+
{
143+
session: {
144+
maintenance: {
145+
mode: "enforce",
146+
maxDiskBytes: "1gb",
147+
highWaterBytes: "800mb",
148+
},
149+
},
150+
}
151+
```
152+
153+
Tune for larger installs (example):
154+
155+
```json5
156+
{
157+
session: {
158+
maintenance: {
159+
mode: "enforce",
160+
pruneAfter: "14d",
161+
maxEntries: 2000,
162+
rotateBytes: "25mb",
163+
maxDiskBytes: "2gb",
164+
highWaterBytes: "1.6gb",
165+
},
166+
},
167+
}
168+
```
169+
170+
Preview or force maintenance from CLI:
171+
172+
```bash
173+
openclaw sessions cleanup --dry-run
174+
openclaw sessions cleanup --enforce
175+
```
176+
74177
## Session pruning
75178

76179
OpenClaw trims **old tool results** from the in-memory context right before LLM calls by default.

‎docs/gateway/configuration-examples.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ Save to `~/.openclaw/openclaw.json` and you can DM the bot from that number.
169169
pruneAfter: "30d",
170170
maxEntries: 500,
171171
rotateBytes: "10mb",
172+
resetArchiveRetention: "30d", // duration or false
173+
maxDiskBytes: "500mb", // optional
174+
highWaterBytes: "400mb", // optional (defaults to 80% of maxDiskBytes)
172175
},
173176
typingIntervalSeconds: 5,
174177
sendPolicy: {
@@ -355,6 +358,10 @@ Save to `~/.openclaw/openclaw.json` and you can DM the bot from that number.
355358
store: "~/.openclaw/cron/cron.json",
356359
maxConcurrentRuns: 2,
357360
sessionRetention: "24h",
361+
runLog: {
362+
maxBytes: "2mb",
363+
keepLines: 2000,
364+
},
358365
},
359366

360367
// Webhooks

0 commit comments

Comments
 (0)