openclaw - ✅(Solved) Fix Cron sessions with deleteAfterRun: true not being deleted — causes context overflow [1 pull requests, 1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
openclaw/openclaw#67718Fetched 2026-04-17 08:29:36
View on GitHub
Comments
1
Participants
2
Timeline
2
Reactions
0
Timeline (top)
commented ×1cross-referenced ×1

Cron jobs configured with sessionTarget: "isolated" and deleteAfterRun: true are not being deleted after execution. Sessions accumulate in sessions.json, inherit context from previous runs, and eventually overflow with Context overflow: prompt too large for the model.

This breaks all cron-based automation: backups, health checks, scheduled tasks.

Error Message

request handler failed: TypeError: Cannot read properties of undefined (reading 'startsWith')

Root Cause

Cron jobs configured with sessionTarget: "isolated" and deleteAfterRun: true are not being deleted after execution. Sessions accumulate in sessions.json, inherit context from previous runs, and eventually overflow with Context overflow: prompt too large for the model.

This breaks all cron-based automation: backups, health checks, scheduled tasks.

Fix Action

Fix / Workaround

Workarounds

Recommendations

  1. Fix deleteAfterRun: true for cron sessions — ensure sessions are removed after execution
  2. Backport sessionTarget: "ephemeral" to 2026.4.12 — or provide it in a patch release
  3. Add automatic cron session cleanup — configurable retention for orphaned cron sessions

PR fix notes

PR #67807: fix(cron): clean up deleteAfterRun direct deliveries

Description (problem / solution / changelog)

Summary

  • Problem: direct cron deliveries only cleaned up deleteAfterRun sessions on the text-finalization path; structured payloads and threaded direct deliveries could leave isolated cron sessions behind.
  • Why it matters: deleteAfterRun jobs could accumulate transcript state and hit the context-overflow behavior reported in #67718.
  • What changed: direct delivery now routes through a shared cleanup wrapper, and session deletion is deduplicated per dispatch so silent direct deliveries only issue one sessions.delete call.
  • What did NOT change (scope boundary): this does not change cron retention policy, the session reaper, or job-store deletion rules.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #67718
  • Related #
  • This PR fixes a bug or regression

Root Cause (if applicable)

  • Root cause: cleanup for deleteAfterRun direct cron sessions was attached to the text finalization path, but the structured direct-delivery and threaded direct-delivery branches called deliverViaDirect without that cleanup.
  • Missing detection / guardrail: there was no regression test asserting cleanup for the raw useDirectDelivery branches, and no guard against duplicate deletion after refactoring cleanup into a shared wrapper.
  • Contributing context (if known): silent direct deliveries can return through the same direct path after payload normalization, which made duplicate cleanup easy to introduce.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts
  • Scenario the test should lock in: deleteAfterRun cleans up after threaded direct deliveries, structured direct deliveries, and structured silent replies without double-deleting the session.
  • Why this is the smallest reliable guardrail: the bug lives entirely inside dispatchCronDelivery branch selection and cleanup behavior, so the isolated dispatch test file exercises the exact control flow without extra cron runtime noise.
  • Existing test that already covers this (if any): existing text and silent cleanup assertions in the same file covered only the text-finalization path.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

Cron jobs using deleteAfterRun: true now reliably delete isolated direct-delivery sessions after structured payload sends and threaded direct sends. Silent direct deliveries still clean up the session, but only issue one delete call.

Diagram (if applicable)

Before:
[direct delivery with structured payload/thread target] -> [send succeeds] -> [session kept]

After:
[direct delivery with structured payload/thread target] -> [send succeeds] -> [shared cleanup wrapper] -> [session deleted once]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: local Node test lane
  • Model/provider: N/A
  • Integration/channel (if any): cron direct-delivery dispatch
  • Relevant config (redacted): deleteAfterRun: true, isolated cron session

Steps

  1. Run a cron agent turn that resolves to direct delivery through the structured-payload path or threaded direct-delivery path.
  2. Set deleteAfterRun: true on the job.
  3. Observe session cleanup behavior after delivery completes.

Expected

  • The isolated cron session is deleted after direct delivery finishes.
  • Silent direct deliveries delete the session exactly once.

Actual

  • Before this change, the structured/threaded direct-delivery branches could skip cleanup entirely.

Evidence

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

  • Verified scenarios: targeted dispatch tests for threaded direct delivery cleanup, structured direct delivery cleanup, and structured silent direct delivery single-delete behavior.
  • Edge cases checked: silent direct replies after payload normalization.
  • What you did not verify: full pnpm test / repo-wide gate in this shell, because the local environment lacks a pnpm binary on PATH; verification used the underlying Vitest cron config directly.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

  • Risk: cleanup now runs through a shared wrapper for direct deliveries, which could accidentally double-delete the session on silent direct replies.
    • Mitigation: the dispatch now tracks whether deletion already succeeded, and the regression test asserts a single sessions.delete call for the structured silent path.

Changed files

  • CHANGELOG.md (modified, +1/-0)
  • src/cron/isolated-agent/delivery-dispatch.double-announce.test.ts (modified, +57/-1)
  • src/cron/isolated-agent/delivery-dispatch.ts (modified, +16/-7)

Code Example

{
  "sessionTarget": "isolated",
  "deleteAfterRun": true
}

---

Context overflow: prompt too large for the model

---

Total sessions: 10

Cron sessions (not being deleted):
agent:<agent-id>:cron:<uuid>:run:<uuid>  (×6 entries)

---

{
  "lastRunStatus": "ok",
  "lastStatus": "ok",
  "lastDelivered": true,
  "lastDeliveryStatus": "delivered",
  "consecutiveErrors": 0
}

---

# Remove cron sessions from sessions.json
python3 -c "
import json
sessions = json.load(open('sessions.json'))
sessions = {k: v for k, v in sessions.items() if 'cron:' not in k}
json.dump(sessions, open('sessions.json', 'w'), indent=2)
"

---

request handler failed: TypeError: Cannot read properties of undefined (reading 'startsWith')
RAW_BUFFERClick to expand / collapse

Summary

Cron jobs configured with sessionTarget: "isolated" and deleteAfterRun: true are not being deleted after execution. Sessions accumulate in sessions.json, inherit context from previous runs, and eventually overflow with Context overflow: prompt too large for the model.

This breaks all cron-based automation: backups, health checks, scheduled tasks.

Environment

  • OpenClaw version: 2026.4.12
  • Platform: Linux x64
  • Node: v24.14.0

Cron Configuration

All jobs configured with:

{
  "sessionTarget": "isolated",
  "deleteAfterRun": true
}

Example jobs (various intervals):

  • Health check — every 6h
  • Session cleanup — every 1d
  • Skill updates — every 1d
  • Daily backup — every 1d

Expected Behavior

With deleteAfterRun: true:

  1. Cron job creates an isolated session key
  2. Cron job executes its payload
  3. Session entry is removed from sessions.json after execution
  4. No accumulation across runs

Actual Behavior (Bug)

  1. Cron job creates an isolated session key
  2. Cron job executes its payload
  3. Session entry remains in sessions.json after execution
  4. Sessions accumulate over time
  5. Each cron run loads history from previous cron sessions
  6. Context grows until overflow:
Context overflow: prompt too large for the model

Evidence

Session Accumulation

From the agent's sessions.json, cron sessions persist and accumulate:

Total sessions: 10

Cron sessions (not being deleted):
agent:<agent-id>:cron:<uuid>:run:<uuid>  (×6 entries)

Cron Job State

{
  "lastRunStatus": "ok",
  "lastStatus": "ok",
  "lastDelivered": true,
  "lastDeliveryStatus": "delivered",
  "consecutiveErrors": 0
}

Jobs complete successfully — but sessions are never cleaned up.

Related Version Notes

2026.4.14

  • Has sessionTarget: "ephemeral" which would prevent context loading for cron sessions
  • Would likely solve this issue
  • But we had to roll back due to a separate lossless-claw plugin bug (#67224)

2026.4.12 (Current)

  • No sessionTarget: "ephemeral" support
  • deleteAfterRun: true for cron sessions is not working

Impact

  • All cron automation broken
  • Cron jobs fail repeatedly with context overflow
  • Manual session cleanup required
  • Cannot schedule reliable automated tasks
  • Daily backups, health checks, and maintenance all failing

Workarounds

Manual Session Cleanup

# Remove cron sessions from sessions.json
python3 -c "
import json
sessions = json.load(open('sessions.json'))
sessions = {k: v for k, v in sessions.items() if 'cron:' not in k}
json.dump(sessions, open('sessions.json', 'w'), indent=2)
"

Periodic Reset

Running /reset on cron job sessions — temporary, not sustainable.

Additional Error

Gateway logs also show:

request handler failed: TypeError: Cannot read properties of undefined (reading 'startsWith')

This occurred when trying to manage cron jobs via CLI, suggesting broader cron system instability.

Recommendations

  1. Fix deleteAfterRun: true for cron sessions — ensure sessions are removed after execution
  2. Backport sessionTarget: "ephemeral" to 2026.4.12 — or provide it in a patch release
  3. Add automatic cron session cleanup — configurable retention for orphaned cron sessions

extent analysis

TL;DR

Implement a manual session cleanup script or upgrade to a version with a fixed deleteAfterRun: true for cron sessions to prevent context overflow.

Guidance

  • Verify that the deleteAfterRun: true configuration is correctly applied to all cron jobs and that there are no other configuration issues preventing session deletion.
  • Use the provided manual session cleanup script as a temporary workaround to remove accumulated cron sessions from sessions.json.
  • Consider implementing a periodic cleanup task to regularly remove orphaned cron sessions and prevent context overflow.
  • Investigate the TypeError: Cannot read properties of undefined (reading 'startsWith') error in the gateway logs to ensure it's not related to the cron session issue.

Example

The manual session cleanup script provided in the issue can be used as a temporary workaround:

python3 -c "
import json
sessions = json.load(open('sessions.json'))
sessions = {k: v for k, v in sessions.items() if 'cron:' not in k}
json.dump(sessions, open('sessions.json', 'w'), indent=2)
"

Notes

The issue is specific to OpenClaw version 2026.4.12, and upgrading to a version with a fixed deleteAfterRun: true or backporting sessionTarget: "ephemeral" may resolve the issue. However, the provided workaround can be used in the meantime.

Recommendation

Apply the manual session cleanup script as a temporary workaround until a fixed version with deleteAfterRun: true for cron sessions is available, as it provides a reliable way to prevent context overflow and ensure cron job execution.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

openclaw - ✅(Solved) Fix Cron sessions with deleteAfterRun: true not being deleted — causes context overflow [1 pull requests, 1 comments, 2 participants]