Skip to content

fix(cron): stop warning forever for deleted agents - #124566

Merged
steipete merged 1 commit into
mainfrom
steipete/cron-reaper-deleted-agents
Aug 16, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/cron-reaper-deleted-agents

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where operators who deleted agents accumulated a permanent cron warning loop. The observed gateway emitted 715 cron-reaper: failed to sweep session store warnings in one day: 13 deleted agents multiplied by 55 sweep attempts each. Every attempt tried to open a database that the deletion journal correctly fences, so no expired session was pruned and the warning could not resolve without code changes.

The target set was seeded from every persisted session-store owner in timer-scheduler.ts, but unlike cron mutations and run receipts, the reaper never consulted the existing isAgentAvailable owner before resolving and opening the store.

Why This Change Was Made

The reaper now applies isAgentAvailable to the complete, normalized target set after persisted owners, cron-job owners, and the default owner have been combined. This is the owning boundary: filtering listKnownSessionStoreAgentIds would break its other caller, the combined Gateway session view, and filtering only the discovery callback would let stale job/default owners re-add the unavailable agent.

Unavailable targets are re-evaluated on every tick and recorded once per unavailable transition at debug level. The diagnostic Set only bounds emission; it is not an agent-existence or deletion cache. The database fence and five-minute reaper throttle are unchanged.

Agent deletion remains the cleanup owner. Shared-store session rows are purged during deletion; per-agent rows disappear with the deleted database. An interrupted cleanup retains its journal and database fence for an explicit delete retry. Completed deleteFiles:false tombstones intentionally retain the database behind the fence until identity recreation, so the cron reaper must not access it.

The JSON-looking cron path still selects a logical SQLite partition, but it is not a file. Cron logger bindings now call it storeKey instead of the misleading storePath.

AI-assisted change; the implementation, ownership boundaries, and evidence below were reviewed before publication.

User Impact

Deleted and blocked-delete agents no longer cause a failed database open and WARN every five minutes. Live agents—including agents with no cron jobs—continue to have expired cron-run sessions pruned. Operators debugging cron logs see the logical SQLite partition labeled as storeKey, not as a nonexistent JSON file.

Evidence

Before / regression

  • Production log, 2026-08-16: 715 warnings/day = 13 deleted agents x 55 attempts. Several tombstones dated back to 2026-08-14 and did not decay.
  • The regression failed before the production change for both a deleted persisted owner and a blocked-delete owner re-added by an unfinished stale job. Across two timer ticks, each unavailable owner reached store resolution twice; the live no-job owner was also swept.

After

  • node scripts/run-vitest.mjs src/cron/service.session-reaper-in-finally.test.ts src/cron/service/state.test.ts src/config/sessions/targets-known-owners.test.ts src/gateway/server-cron.test.ts src/gateway/local-request-context.test.ts
    • 87 tests passed across three Vitest shards.
    • Deleted and blocked targets never reached store resolution.
    • The live persisted owner with no cron jobs was still swept.
    • WARN count was zero; the skip debug record appeared once across two ticks.
  • Blacksmith Testbox build: tbx_01m056bs44sm009704ppmmknf3, Actions run https://github.com/openclaw/openclaw/actions/runs/31945286828
    • pnpm build passed.
  • Live scratch gateway on port 19888 with isolated OPENCLAW_STATE_DIR and OPENCLAW_SKIP_CHANNELS=1:
    • Created agent victim and an expired cron-run session.
    • Deleted the roster entry with deleteFiles:false, leaving cleanupCompleted:true and the database intentionally retained behind its tombstone.
    • Kept the gateway running from 11:55:51Z to 12:06:16Z, crossing two full five-minute reaper intervals while enabled cron jobs kept the timer active.
    • After: reaper_warning_count=0, reaper_skip_debug_count=1.
    • Logger proof: zero stale storePath bindings for the cron partition; 39 storeKey bindings. The one skip record carried agentId=victim and storeKey=/tmp/openclaw-cron-reaper-r18/cron/jobs.json.
  • node scripts/check-changed.mjs
  • .agents/skills/autoreview/scripts/autoreview --mode uncommitted --stream-engine-output
    • Clean: no accepted/actionable findings; patch judged correct with 0.99 confidence.

Production LOC: +13/-2 (net +11) | Tests/test support: +67/-0

Sweep result: listKnownSessionStoreAgentIds remains intentionally broad for combined session views. Gateway startup temp cleanup may encounter a tombstone once per startup, and explicit task/plugin maintenance may report one visible failure, but no other recurring maintenance loop derives a forever-retried target set from persisted owners. Transcript-index startup and memory/index maintenance are configured/active-agent scoped.

@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@steipete
steipete marked this pull request as ready for review August 16, 2026 12:30
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S maintainer Maintainer-authored PR labels Aug 16, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 16, 2026
@clawsweeper

clawsweeper Bot commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 16, 2026, 8:36 AM ET / 12:36 UTC.

ClawSweeper review

What this changes

The PR skips unavailable agents before cron session-store cleanup and renames the cron logger’s store field to storeKey.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep open: the generic availability check also rejects unfenced retired owners, contradicting the existing reaper contract to prune their expired sessions. Likely related people: @steipete (high confidence).

Priority: P1
Reviewed head: 0b87dd00146d7e60add410279caf122a0810c6b6

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The supplied live behavior evidence is useful, but the patch has a concrete persisted-session cleanup regression.
Proof confidence 🌊 off-meta tidepool Not applicable: Not applicable to this maintainer-authored PR; its body nevertheless records an isolated live gateway run across two reaper intervals with an observed zero-warning result.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Not applicable to this maintainer-authored PR; its body nevertheless records an isolated live gateway run across two reaper intervals with an observed zero-warning result.
Evidence reviewed 6 items Retired-owner cleanup contract: Current coverage explicitly requires the reaper to sweep a persisted owner after it leaves both the roster and cron store.
Discovery intentionally retains retired owners: Known session-store owner discovery retains configured and persisted owners, including retired durable owners, so periodic cleanup can still reach their session rows.
Broader predicate on the PR head: The proposed condition treats any agent absent from the current roster as unavailable before store resolution; Gateway supplies that predicate as both deletion-fence and roster-membership validation.
Findings 1 actionable finding [P1] Gate only deletion-fenced owners
Security None None.

How this fits together

The cron service periodically gathers persisted and scheduled agent owners, resolves each session store, and removes expired cron-run sessions. Gateway construction supplies both the owner list and lifecycle availability checks.

flowchart LR
A[Persisted session owners] --> C[Cron reaper target set]
B[Cron jobs and default owner] --> C
C --> D{Deletion fence?}
D -->|no| E[Resolve session store]
E --> F[Prune expired cron sessions]
D -->|yes| G[Log one skip]
Loading

Before merge

  • Gate only deletion-fenced owners (P1) - isAgentAvailable is false for every owner removed from the current roster, not only a deletion-journal-fenced owner. The reaper deliberately discovers persisted retired owners, and existing coverage requires their expired cron sessions to be pruned; this new guard therefore leaves those rows indefinitely. Use a reaper-specific deletion-fence predicate and cover the unfenced retired-owner path through the Gateway builder.
  • Resolve merge risk (P1) - As written, removing an owner from the roster without a deletion-journal fence stops periodic pruning of that owner’s expired cron-run sessions, despite the existing persisted-owner contract.
  • Resolve merge risk (P1) - The bug fix adds 11 net production lines; the diagnostic state is useful, but it should remain only after the reaper predicate is narrowed to the deletion boundary.
  • Complete next step (P2) - The concrete P1 finding needs an updated maintainer-owned PR; the protected maintainer label keeps it out of the automated repair queue.

Findings

  • [P1] Gate only deletion-fenced owners — src/cron/service/timer-scheduler.ts:469
Agent review details

Security

None.

PR surface

Source +12, Tests +66. Total +78 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 5 14 2 +12
Tests 1 66 0 +66
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 80 2 +78

Review metrics

Metric Value Why it matters
Production versus test LOC production +13/-2 (net +11); tests/test support +67/-0 The production growth is acceptable only if the new diagnostic state supports a deletion-fence-only repair rather than replacing persisted-owner cleanup.

Stored data model

Persistent data-model change detected: serialized state: src/cron/service.session-reaper-in-finally.test.ts, serialized state: src/cron/service/state.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Narrow the skip boundary (recommended)
    Skip only agents with an active deletion-journal fence, then add Gateway-composed coverage that an unfenced retired owner is still reaped.

Technical review

Best possible solution:

Inject a reaper-specific deletion-fence predicate from Gateway, preserve cleanup for unfenced persisted owners, and prove both cases through the real Gateway composition.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: a persisted owner absent from the roster is discovered for cleanup, but Gateway’s availability callback returns false and the proposed line skips it before session-store resolution.

Is this the best way to solve the issue?

No. The best fix is to gate only the deletion-journal fence, because generic roster availability intentionally has a broader meaning for cron mutations and run authority.

Full review comments:

  • [P1] Gate only deletion-fenced owners — src/cron/service/timer-scheduler.ts:469
    isAgentAvailable is false for every owner removed from the current roster, not only a deletion-journal-fenced owner. The reaper deliberately discovers persisted retired owners, and existing coverage requires their expired cron sessions to be pruned; this new guard therefore leaves those rows indefinitely. Use a reaper-specific deletion-fence predicate and cover the unfenced retired-owner path through the Gateway builder.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c1622d08f50f.

Labels

Label changes:

  • add P1: The proposed merge would regress established cleanup of expired cron-run sessions for persisted owners removed from the roster.
  • add merge-risk: 🚨 session-state: The broad availability predicate can leave expired session rows for unfenced retired owners indefinitely.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Not applicable to this maintainer-authored PR; its body nevertheless records an isolated live gateway run across two reaper intervals with an observed zero-warning result.

Label justifications:

  • P1: The proposed merge would regress established cleanup of expired cron-run sessions for persisted owners removed from the roster.
  • merge-risk: 🚨 session-state: The broad availability predicate can leave expired session rows for unfenced retired owners indefinitely.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: Not applicable to this maintainer-authored PR; its body nevertheless records an isolated live gateway run across two reaper intervals with an observed zero-warning result.

Evidence

What I checked:

  • Retired-owner cleanup contract: Current coverage explicitly requires the reaper to sweep a persisted owner after it leaves both the roster and cron store. (src/cron/service.session-reaper-in-finally.test.ts:336, f1ca5e20d8a4)
  • Discovery intentionally retains retired owners: Known session-store owner discovery retains configured and persisted owners, including retired durable owners, so periodic cleanup can still reach their session rows. (src/config/sessions/targets.ts:79, f43544f752a3)
  • Broader predicate on the PR head: The proposed condition treats any agent absent from the current roster as unavailable before store resolution; Gateway supplies that predicate as both deletion-fence and roster-membership validation. (src/cron/service/timer-scheduler.ts:469, 0b87dd00146d)
  • Lifecycle owner is narrower: The deletion journal already exposes a dedicated fence whose meaning is only whether the process must refuse new authority for that agent. (src/agents/agent-lifecycle-registry.ts:115, f43544f752a3)
  • Feature provenance: Blame ties the current reaper target loop and Gateway availability callback to the recent cron refactor; the file move/refactor history is insufficient to attribute the regression to that commit conclusively. (src/cron/service/timer-scheduler.ts:468, f1ca5e20d8a4)
  • After-fix behavior evidence: The PR body records an isolated live gateway run across two reaper intervals with zero warnings and one skip diagnostic for a tombstoned agent. (0b87dd00146d)

Likely related people:

  • steipete: Git blame attributes the current reaper loop and Gateway callback to the cron refactor authored by steipete; the same person authored this focused follow-up. (role: recent cron-service refactor author and current patch author; confidence: high; commits: f1ca5e20d8a4, 0b87dd00146d; files: src/cron/service/timer-scheduler.ts, src/gateway/server-cron.ts, src/cron/service.session-reaper-in-finally.test.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Replace the generic availability check with a deletion-fence-only reaper predicate.
  • Add Gateway-composed coverage for both a tombstoned agent skip and an unfenced retired owner sweep.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit 91a3b9b into main Aug 16, 2026
255 checks passed
@steipete
steipete deleted the steipete/cron-reaper-deleted-agents branch August 16, 2026 12:38
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 17, 2026
obviyus added a commit that referenced this pull request Sep 15, 2026
…8920)

## What Problem This Solves

Cron starts a journal write transaction for every agent on every admitted tick, even when session pruning is disabled or throttled.

Closes #145394. Refs #124566.

## Why This Change Was Made

The reaper now checks fresh availability after its retention and agent/store throttle decision, before reading sessions. This state has one writer. Its existing attempt throttle also bounds skip logs, replacing the separate diagnostic set.

## User Impact

Idle pruning avoids per-agent journal writes. Unavailable agents stay excluded. Recovered agents can run scheduled jobs immediately; maintenance can wait until its existing five-minute cooldown expires.

## Evidence

A real Gateway with 632 synthetic agents ran `/usr/bin/true` every 10 seconds via `cron.add`, launched with `pnpm openclaw gateway run`. Native SQLite tracing counted maintenance transaction starts separately from job execution.

| Maintenance | Before | After |
| --- | ---: | ---: |
| Disabled, each of 3 ticks | 632 writes | 0 |
| Throttled, each of 2 ticks | 632 writes | 0 |
| Eligible pass | 632 checks/sweeps | 632 checks/sweeps |

All command runs succeeded. Health probes still timed out around reload in both runs; this does not claim to remove all fleet stalls.

On a fresh merge with main, 210 tests passed across six owner and sibling files. Both new scheduler regressions fail with the original code. Type-aware lint, production/test types, formatting, protocol checks, architecture, and ratchets passed.

Thanks @609NFT for the journal stack evidence and @zachisfine for separating the session-listing cost. Other fleet health stalls remain outside this fix.

## Compatibility

No schema, config, retention-rule, shared journal reader, or deletion-fence change.

## Consumers

Timer maintenance uses the same reaper as before. Job execution retains its fresh availability checks.

## Invalidation

The existing agent/store cooldown records attempts. Disabled retention records none; clock rollback admits a fresh attempt.

## Tests

Scheduler entry tests cover disabled/re-enabled pruning, throttling, rollback, unavailable-owner exclusion, and job execution during recovery cooldown.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 16, 2026
…nclaw#148920)

## What Problem This Solves

Cron starts a journal write transaction for every agent on every admitted tick, even when session pruning is disabled or throttled.

Closes openclaw#145394. Refs openclaw#124566.

## Why This Change Was Made

The reaper now checks fresh availability after its retention and agent/store throttle decision, before reading sessions. This state has one writer. Its existing attempt throttle also bounds skip logs, replacing the separate diagnostic set.

## User Impact

Idle pruning avoids per-agent journal writes. Unavailable agents stay excluded. Recovered agents can run scheduled jobs immediately; maintenance can wait until its existing five-minute cooldown expires.

## Evidence

A real Gateway with 632 synthetic agents ran `/usr/bin/true` every 10 seconds via `cron.add`, launched with `pnpm openclaw gateway run`. Native SQLite tracing counted maintenance transaction starts separately from job execution.

| Maintenance | Before | After |
| --- | ---: | ---: |
| Disabled, each of 3 ticks | 632 writes | 0 |
| Throttled, each of 2 ticks | 632 writes | 0 |
| Eligible pass | 632 checks/sweeps | 632 checks/sweeps |

All command runs succeeded. Health probes still timed out around reload in both runs; this does not claim to remove all fleet stalls.

On a fresh merge with main, 210 tests passed across six owner and sibling files. Both new scheduler regressions fail with the original code. Type-aware lint, production/test types, formatting, protocol checks, architecture, and ratchets passed.

Thanks @609NFT for the journal stack evidence and @zachisfine for separating the session-listing cost. Other fleet health stalls remain outside this fix.

## Compatibility

No schema, config, retention-rule, shared journal reader, or deletion-fence change.

## Consumers

Timer maintenance uses the same reaper as before. Job execution retains its fresh availability checks.

## Invalidation

The existing agent/store cooldown records attempts. Disabled retention records none; clock rollback admits a fresh attempt.

## Tests

Scheduler entry tests cover disabled/re-enabled pruning, throttling, rollback, unavailable-owner exclusion, and job execution during recovery cooldown.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant