Skip to content

fix(heartbeat): avoid timeouts for busy scheduled polls - #148333

Merged
vincentkoc merged 2 commits into
mainfrom
fix/heartbeat-busy-polls-f8223af4
Sep 22, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
fix/heartbeat-busy-polls-f8223af4

Conversation

@roboclaw-bot

@roboclaw-bot roboclaw-bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #148332

What Problem This Solves

Fixes: periodic heartbeat monitors can stay running behind foreground work, delay shutdown, and be recorded as failed after an ordinary Gateway restart.

User Impact

User impact: a plain, event-free monitor poll that has not started preparation finishes as skipped and waits for its next scheduled tick. Busy foreground work no longer creates a false heartbeat failure.

Queued events, scheduled tasks, direct manual wakes, and work already prepared or admitted keep their retries and eventual success/failure accounting. Genuine execution deadlines remain errors. No configuration change, migration, permission change, or SDK contract change is required.

Why This Change Was Made

The existing wake owner settles a poll only when the heartbeat runner proves it carries no pending work. Eligibility is conservative across coalescing, and a sticky work-started fact prevents later busy attempts from discarding admitted work.

This refresh preserves RoboClaw's original implementation and commit ancestry, incorporates the current scheduler/recovery ownership, and adds real-flow coverage for skipped monitors across restart. It updates this canonical PR without replacing its author credit.

Evidence

  • Baseline regression on 2d3dd99f5642: idle/no-route settles, but a busy monitor fails to produce a finished event. The candidate proves prompt settlement, persisted next-tick cadence, unchanged restart state, zero error backoff, immediate cron drain, and no model/notification calls for skipped polls.
  • 213 distinct affected/owner/sibling tests passed across 10 suites on the refreshed sources (175 infra; 29 existing real-flow/payload cron cases; all 9 busy-poll cases after the fixture corrections below). The affected and sibling test selection covers queued payloads, coalesced task success/failure, late admission, handler replacement, cancellation, module identity, store replacement, and genuine execution timeouts.
  • Core source types, infra and services-cron test graphs, all changed-file formatting/lint, and relevant ownership/schema/import guards passed; the full repository suite and all test type graphs were not run locally.
  • Fresh AutoReview completed on the exact final patch with no actionable P0–P2 findings; independent source review also found no actionable correctness issue. AutoReview used a sanitized source-only export with the exact selected diff and relevant owner/caller/dependency context. Exact-head hosted CI remains required before merge.
  • The scheduler refresh exposed a fixture-only cross-thread clock mismatch: fake process.hrtime in the parent was incompatible with real SQLite-worker admission deadlines. The fixture keeps native hrtime while still simulating heartbeat cadence and watchdog timers; no production guard or assertion was weakened.

Tests use fake scheduling timers, isolated SQLite state, real command-lane blocking, and injected model/channel boundaries. This is deterministic scheduler/runner proof, not a live provider or deployed Gateway test. No Gateway restart, live schedule/configuration change, deployment, or merge is part of this update.

Regression cost

Earlier single-worker pnpm test <file> --maxWorkers=1 wall measurements: private disposition 4.56 s (67 tests), module identity 9.16 s (1 test), real heartbeat flow 29.05 s (19 tests). Their test-time portions were below 30 seconds per file. Final refreshed busy-poll suite: 43.22 s wall (9 tests), with test execution 63% of the 39.67 s Vitest duration, below the 30-second per-file test-time budget. The real-flow suites retain CronService, wake ownership, heartbeat preflight/admission, and SQLite composition because fabricated busy results miss the original defect. CI timing will be available on the pushed revision.

Settle untouched, event-free native polls at pre-execution busy guards without retaining an unowned child. Preserve queued tasks/events, admitted work, and genuine execution deadlines.

Co-authored-by: vincentkoc <[email protected]>
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL maintainer Maintainer-authored PR labels Sep 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 22, 2026, 5:50 AM ET / 09:50 UTC (Revision 2).

ClawSweeper review

What this changes

The PR makes untouched, event-free scheduled heartbeat polls finish as skipped when busy, with regression coverage and documentation for waiting until the next scheduled tick.

Merge readiness

✅ Ready for maintainer review

This PR remains useful: current main pauses queue-wait deadlines but still retains untouched busy monitor occurrences. The proposed settlement change preserves payload-bearing and started work, and no actionable introduced defect was found.

Priority: P2
Reviewed head: 275c6fe0bd4c21194d2fff0c79165bf712f65a71

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level repair with substantial lifecycle coverage and no actionable correctness findings; reported validation was not rerun in this read-only review.
Proof confidence 🌊 off-meta tidepool Not applicable: The ordinary external-contributor proof gate does not apply to this maintainer/bot PR. Its reported deterministic tests exercise CronService through the real wake and heartbeat owners with held command-lane work, persisted cadence, and service restart; they are not a deployed Gateway or live-provider run. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary external-contributor proof gate does not apply to this maintainer/bot PR. Its reported deterministic tests exercise CronService through the real wake and heartbeat owners with held command-lane work, persisted cadence, and service restart; they are not a deployed Gateway or live-provider run. No stored-data contract changes.
Evidence reviewed 7 items Pinned introduction scope: Reviewed the introduced delta from 0883394 to the exact head. Broad endpoint drift and labels do not describe this PR's edits; the supplied stale test merge was not used to infer removals.
Conservative settlement boundary: Busy guards request terminal settlement only after preflight finds no events or tasks. The wake owner additionally requires a targeted scheduled interval with valid cadence, intersects eligibility across coalescing, and permanently excludes work whose preparation has started. Aborted attempts cannot set the disposition.
Current main still retains busy polls: Current main retries skipped wakes through shouldRetain without the proposed terminal-poll exception. Its cron watchdog already pauses on queue entry, so the remaining value is prompt settlement and next-cadence behavior, rather than duplicating that timeout repair.
Findings None None.
Security None None.

How this fits together

Cron schedules heartbeat monitors and waits for the heartbeat wake queue to report their outcome. The heartbeat runner checks pending work and activity before preparation; its result determines automation completion and the next scheduled opportunity.

flowchart TD
  A[Scheduled monitor tick] --> B[Heartbeat wake queue]
  C[Events and scheduled tasks] --> B
  B --> D[Runner checks pending work and activity]
  D --> E{Untouched plain poll and busy?}
  E -->|Yes| F[Record skipped and await next tick]
  E -->|No| G[Retain retry or execute work]
  G --> H[Report eventual outcome to cron]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +85, Tests +1238, Docs 0. Total +1323 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 4 99 14 +85
Tests 4 1240 2 +1238
Docs 1 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 1341 18 +1323

Review metrics

Metric Value Why it matters
Production versus regression coverage Production net +85 lines; tests net +1,238 lines Production growth implements coalesced eligibility and sticky preparation state; most growth covers settlement and lifecycle regressions.

Technical review

Best possible solution:

Keep settlement in the existing wake owner, retiring only untouched plain monitor occurrences while preserving eventual outcomes for events, tasks, and prepared work.

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

Yes, source establishes that a scheduled poll behind held foreground work remains queued on current main; the supplied regression exercises that boundary. The original queue-wait timeout is already mitigated, and this review did not execute a reproduction.

Is this the best way to solve the issue?

Yes, the change extends the existing settlement owner without changing public result types, SDK contracts, configuration, or stored formats, and conservatively preserves work that must retry.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 41f119f66004.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded heartbeat scheduling repair that prevents idle monitor occurrences from remaining open behind busy work.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The ordinary external-contributor proof gate does not apply to this maintainer/bot PR. Its reported deterministic tests exercise CronService through the real wake and heartbeat owners with held command-lane work, persisted cadence, and service restart; they are not a deployed Gateway or live-provider run. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction scope: Reviewed the introduced delta from 0883394 to the exact head. Broad endpoint drift and labels do not describe this PR's edits; the supplied stale test merge was not used to infer removals. (275c6fe0bd4c)
  • Conservative settlement boundary: Busy guards request terminal settlement only after preflight finds no events or tasks. The wake owner additionally requires a targeted scheduled interval with valid cadence, intersects eligibility across coalescing, and permanently excludes work whose preparation has started. Aborted attempts cannot set the disposition. (src/infra/session-event-wake.ts:653, 275c6fe0bd4c)
  • Current main still retains busy polls: Current main retries skipped wakes through shouldRetain without the proposed terminal-poll exception. Its cron watchdog already pauses on queue entry, so the remaining value is prompt settlement and next-cadence behavior, rather than duplicating that timeout repair. (src/infra/session-event-wake.ts:437, 41f119f66004)
  • Latest supplied release check: The v2026.9.5 source also retains retryable skipped wakes without a terminal-poll exception. GitHub's contents API supplied the release source after the local historical blob read failed. (src/infra/session-event-wake.ts:379, ec9c1a13db89)
  • Regression coverage and proof limits: Inspected the real CronService, wake-owner, runner, command-lane and SQLite test composition. Cases cover actionable/missing scratch, persisted cadence, manual wakes, queued events, task coalescing, late preparation and genuine execution timeouts; the companion suite checks completed-state preservation across service restart. The captured PR body reports 213 passing tests and explicitly identifies injected model/channel boundaries and fake scheduling timers. No tests or target code were executed during this review. (src/cron/service.heartbeat-busy-poll.test.ts:237, 275c6fe0bd4c)
  • Review continuity and maintainer context: The prior completed review retained no findings or published rank-up moves. The current human discussion requests re-review, and vincentkoc is assigned. No maintainer-notes directory exists in this checkout. The protected maintainer/security labels preclude automatic cleanup but do not establish a defect in the introduced patch. (275c6fe0bd4c)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-14T16:06:38.577Z sha f8223af :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 14, 2026
obviyus added a commit that referenced this pull request Sep 15, 2026
Closes #148874

## What Problem This Solves
Heartbeat cron jobs report execution timeouts while queued behind foreground work.

## Why This Change Was Made
Queue entry pauses the cron watchdog; attempt start arms it. This state has one writer. Retries retain their final outcome, including after handler replacement.

Growth: `timer-job-runner.ts` +7 (deadline), `timer-execution.ts` +1 (handoff), `timer-execution-timeout.ts` +5 (type), `session-event-wake.ts` +18 (notifications).

Growth accepted under the owner's standing acceptance (2026-09-15).

## User Impact
Queue waits no longer create false errors. Actual failures and execution deadlines remain effective.

## Evidence
Real Gateway: hold a `chat.send` response for five seconds; call `cron.run` with a two-second heartbeat timeout; read `cron.runs`/`cron.get`.

Main expired at 2,010 ms before any heartbeat request, with one consecutive error. The fix stayed pending, then recorded the retained retry's success at 60.4 seconds. Separate controls recorded a failed retry and an executing timeout, each with one consecutive error.

## Compatibility
Preserves #134464 outcome accounting. No config, schema, protocol or SDK change. #148333's next-cadence policy remains separate.

## Consumers
Scheduled monitors, heartbeat tasks and immediate cron events.

## Invalidation
Enqueue pauses the deadline; attempts restart it; completion disposes it.

## Tests
196 tests passed on a fresh merge with main; 27 focused tests also cover unlimited heartbeats. Original-code negative controls fail. Type-aware checks passed.

## Contention
Immediate handoff, coalescing and cancellation remain unchanged and covered.

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

## What Problem This Solves
Heartbeat cron jobs report execution timeouts while queued behind foreground work.

## Why This Change Was Made
Queue entry pauses the cron watchdog; attempt start arms it. This state has one writer. Retries retain their final outcome, including after handler replacement.

Growth: `timer-job-runner.ts` +7 (deadline), `timer-execution.ts` +1 (handoff), `timer-execution-timeout.ts` +5 (type), `session-event-wake.ts` +18 (notifications).

Growth accepted under the owner's standing acceptance (2026-09-15).

## User Impact
Queue waits no longer create false errors. Actual failures and execution deadlines remain effective.

## Evidence
Real Gateway: hold a `chat.send` response for five seconds; call `cron.run` with a two-second heartbeat timeout; read `cron.runs`/`cron.get`.

Main expired at 2,010 ms before any heartbeat request, with one consecutive error. The fix stayed pending, then recorded the retained retry's success at 60.4 seconds. Separate controls recorded a failed retry and an executing timeout, each with one consecutive error.

## Compatibility
Preserves openclaw#134464 outcome accounting. No config, schema, protocol or SDK change. openclaw#148333's next-cadence policy remains separate.

## Consumers
Scheduled monitors, heartbeat tasks and immediate cron events.

## Invalidation
Enqueue pauses the deadline; attempts restart it; completion disposes it.

## Tests
196 tests passed on a fresh merge with main; 27 focused tests also cover unlimited heartbeats. Original-code negative controls fail. Type-aware checks passed.

## Contention
Immediate handoff, coalescing and cancellation remain unchanged and covered.

Co-authored-by: Ayaan Zaidi <[email protected]>
pash-openai added a commit that referenced this pull request Sep 18, 2026
* fix(cron): exclude queue waits from heartbeat timeouts (#148876)

Closes #148874

Heartbeat cron jobs report execution timeouts while queued behind foreground work.

Queue entry pauses the cron watchdog; attempt start arms it. This state has one writer. Retries retain their final outcome, including after handler replacement.

Growth: `timer-job-runner.ts` +7 (deadline), `timer-execution.ts` +1 (handoff), `timer-execution-timeout.ts` +5 (type), `session-event-wake.ts` +18 (notifications).

Growth accepted under the owner's standing acceptance (2026-09-15).

Queue waits no longer create false errors. Actual failures and execution deadlines remain effective.

Real Gateway: hold a `chat.send` response for five seconds; call `cron.run` with a two-second heartbeat timeout; read `cron.runs`/`cron.get`.

Main expired at 2,010 ms before any heartbeat request, with one consecutive error. The fix stayed pending, then recorded the retained retry's success at 60.4 seconds. Separate controls recorded a failed retry and an executing timeout, each with one consecutive error.

Preserves #134464 outcome accounting. No config, schema, protocol or SDK change. #148333's next-cadence policy remains separate.

Scheduled monitors, heartbeat tasks and immediate cron events.

Enqueue pauses the deadline; attempts restart it; completion disposes it.

196 tests passed on a fresh merge with main; 27 focused tests also cover unlimited heartbeats. Original-code negative controls fail. Type-aware checks passed.

Immediate handoff, coalescing and cancellation remain unchanged and covered.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 4e88587)

* fix: stop marking delivered scheduled reports as failed (#152165)

* fix: preserve completed scheduled reports after tool read failures

* fix: keep cron failures after progress-only messages

(cherry picked from commit e731216)

---------

Co-authored-by: Sriram Natarajan <[email protected]>
Co-authored-by: Ayaan Zaidi <[email protected]>
@vincentkoc
vincentkoc requested review from a team as code owners September 22, 2026 02:31
@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: slack Channel integration: slack labels Sep 22, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: android App: android app: ios App: ios app: linux app: macos App: macos app: wearos App: wearos app: web-ui App: web-ui channel: a2a channel: buzz channel: discord Channel integration: discord channel: feishu Channel integration: feishu channel: googlechat Channel integration: googlechat channel: imessage Channel integration: imessage channel: irc channel: line Channel integration: line channel: matrix Channel integration: matrix channel: mattermost Channel integration: mattermost channel: msteams Channel integration: msteams channel: nextcloud-talk Channel integration: nextcloud-talk channel: nostr Channel integration: nostr channel: qqbot channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: zalo Channel integration: zalo docker Docker and sandbox tooling docs Improvements or additions to documentation extensions: acpx extensions: active-memory extensions: admin-http-rpc extensions: anthropic extensions: arcee extensions: baseten Extension: baseten extensions: byteplus extensions: cerebras extensions: clawrouter Extension: clawrouter extensions: clickclack extensions: cloudflare-ai-gateway extensions: codex extensions: cohere extensions: comfy extensions: copilot extensions: copilot-proxy Extension: copilot-proxy extensions: crabbox extensions: deepgram extensions: deepinfra extensions: deepseek extensions: device-pair extensions: diagnostics-otel Extension: diagnostics-otel extensions: diagnostics-prometheus extensions: document-extract extensions: duckduckgo extensions: featherless extensions: fish-audio Extension: fish-audio extensions: gmi extensions: huggingface extensions: image-generation-core extensions: inworld Extension: inworld extensions: kilocode extensions: kimi-coding extensions: litellm extensions: llama-cpp extensions: llm-task Extension: llm-task extensions: lmstudio extensions: lobster Extension: lobster extensions: longcat LongCat provider plugin extensions: memory-core Extension: memory-core extensions: memory-lancedb Extension: memory-lancedb extensions: memory-wiki extensions: meta Extension: meta extensions: minimax extensions: moonshot extensions: nvidia extensions: oc-path extensions: onepassword 1Password plugin extensions: openai extensions: qa-lab fleet gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. plugin: azure-speech Azure Speech plugin plugin: beam Beam session sharing plugin plugin: bonjour Plugin integration: bonjour plugin: cua-computer plugin: facetime FaceTime plugin plugin: file-transfer plugin: geolocation Geolocation plugin (IP to coarse city) plugin: google-meet plugin: imap plugin: linux-node plugin: logbook Logbook automatic work journal plugin plugin: migrate-claude plugin: migrate-hermes plugin: mxc plugin: onnx plugin: team-reports plugin: typesafe rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security Security documentation size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Heartbeat monitors time out while only waiting behind busy work

2 participants