Skip to content

fix: report settled heartbeat cron outcomes - #134464

Merged
fuller-stack-dev merged 1 commit into
mainfrom
fix/heartbeat-cron-settlement
Aug 31, 2026
Merged

fuller-stack-dev merged 1 commit into
mainfrom
fix/heartbeat-cron-settlement

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Fixes #134327
Refs #134373

What Problem This Solves

Fixes an issue where heartbeat cron runs were recorded as successful as soon as their wake was accepted, even when the delayed heartbeat agent turn later failed. Operators could therefore see ok / succeeded history for model work that never completed.

Why This Change Was Made

Cron task completion accounting is the lifecycle owner. Heartbeat cron work now stays open until the coalesced wake reaches a terminal result, and that result is mapped through the existing cron outcome vocabulary.

The wake queue fans one child result out to every represented cron parent, retains waiters across retryable skips and handler replacement, and detaches only the exact waiter on cancellation. Exact waiting cron and lane owners are excluded from the child's busy check so they cannot block their own work; unrelated cron work remains a blocker.

This uses the existing ten-minute cron watchdog and durable running-receipt recovery. It does not add a protocol status, persistence schema, polling loop, retry that hides failures, or unbounded scheduler wait.

#134373 concerns deletion of completed isolated cron sessions. It does not share this completion transition, so this PR does not change session cleanup.

User Impact

Heartbeat cron history now reports the eventual heartbeat outcome:

  • failed child: error / failed
  • successful child: ok / succeeded
  • disabled heartbeat: skipped / failed

Coalescing still produces one child turn, manual heartbeat runs use the same contract, and ordinary system-event cron remains dispatch-only.

Evidence

An expanded local pnpm test:changed run completed twelve projects before a Vitest worker exited while another full OpenClaw campaign saturated the host. It produced no assertion failure; exact-head hosted CI remains required before landing.

Scope and Review Notes

Production LOC: +231/-71 (net +160) | Tests: +473/-20 | Test support: +12/-2

The production growth is the bounded many-parent-to-one-child settlement bridge and exact lifecycle ownership needed to preserve coalescing. Shared settlement and Gateway adapter logic were extracted to avoid duplicate branches.

Related open PRs are not superseded: #133747 covers cancelled-run retry settlement, #132464 covers orphaned heartbeat transcripts, #72677 covers handoff warnings, and #131590 covers one-shot disable visibility. None owns heartbeat child-to-parent completion.

Release-note context: Cron heartbeat jobs now report the settled heartbeat child outcome instead of treating accepted wake dispatch as completed work.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: L maintainer Maintainer-authored PR labels Aug 31, 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 Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed August 31, 2026, 5:28 PM ET / 21:28 UTC.

ClawSweeper review

What this changes

The PR makes heartbeat-monitor and heartbeat-task cron runs wait for the coalesced heartbeat turn’s terminal result and records that result in cron history.

Regression provenance

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

Merge readiness

⚠️ Ready for maintainer review - 3 items remain

The central cron-history bug remains unfixed on current main, and this PR addresses it at the right lifecycle boundary. A handler-replacement race can drop an awaited cron settlement and turn a completed heartbeat into a ten-minute cron timeout, so the PR needs one focused repair before merge.

Priority: P2
Reviewed head: dc1c560787fa97eea016fffca3ca1873560aff5a

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The core repair is well-scoped and tested, but the unresolved handler-replacement race can still produce an incorrect cron terminal outcome.
Proof confidence 🌊 off-meta tidepool Not applicable: The author association is MEMBER, so the external-contributor real-behavior-proof gate does not apply; the supplied older terminal artifacts were not independently reachable from this review environment and are not used to clear the remaining exact-head race.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The author association is MEMBER, so the external-contributor real-behavior-proof gate does not apply; the supplied older terminal artifacts were not independently reachable from this review environment and are not used to clear the remaining exact-head race.
Evidence reviewed 6 items Current-main behavior: Current main immediately returns an ok cron result after requesting a heartbeat wake, so the reported premature-success behavior remains present without this PR.
Settlement ownership: The PR correctly changes heartbeat cron execution to await the new settlement callback and maps ran, failed, and skipped results into the existing cron outcome vocabulary.
Dropped waiter on replacement: After an awaited wake returns a terminal result but its handler generation changed, this introduced branch omits the current wake from handoff when retainWake is false. Its settlement is then neither resolved nor requeued.
Findings 1 actionable finding [P2] Preserve settlements across handler replacement
Security None None.

How this fits together

The Automations scheduler runs system-owned heartbeat cron jobs, which enqueue work through the shared heartbeat wake queue. That queue coalesces work into a heartbeat agent turn and must return its settled result to every waiting cron parent.

flowchart LR
  A[Cron monitor or task] --> B[Cron execution]
  B --> C[Heartbeat wake queue]
  C --> D[Coalesced heartbeat turn]
  D --> E[Wake settlement]
  E --> F[Cron run history]
  G[Handler replacement] --> C
Loading

Before merge

  • Preserve settlements across handler replacement (P2) - When a handler replacement increments the generation after the old handler has produced a terminal result, retainWake is false and this handoff starts at the next wake. The current awaited settlement is dropped, so its cron parent remains running until the watchdog reports a timeout despite the child having completed. Settle that waiter with the result or requeue the current wake, and cover this interleaving.
  • Resolve merge risk (P2) - A terminal heartbeat result that races an in-process handler replacement can lose its cron waiter, leaving the cron run active until the watchdog records a timeout instead of the actual child outcome.
  • Complete next step (P2) - A single mechanical wake-settlement repair and regression test can resolve the blocking lifecycle race.

Findings

  • [P2] Preserve settlements across handler replacement — src/infra/heartbeat-wake.ts:542-552
Agent review details

Security

None.

PR surface

Source +170, Tests +453. Total +623 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 8 243 73 +170
Tests 6 473 20 +453
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 716 93 +623

Review metrics

Metric Value Why it matters
Lifecycle implementation delta production +160 net; tests +453 net; test support +10 net The added settlement bridge is substantial but concentrated in cron-to-heartbeat lifecycle ownership; the replacement-race invariant needs correction before that complexity is accepted.

Merge-risk options

Maintainer options:

  1. Preserve the terminal waiter (recommended)
    Resolve or transfer the current wake’s settlement when a handler replacement occurs after its terminal result, then add a regression that verifies the cron parent does not watchdog-timeout.

Technical review

Best possible solution:

Preserve every awaited settlement across a handler-generation change by either resolving it with the already-observed terminal result or requeuing the current wake, and add a focused replacement-race regression.

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

Yes: current main’s source completes heartbeat cron work immediately after dispatch, while the PR’s new awaitable settlement path makes the reported outcome mismatch directly reproducible in a focused cron/heartbeat harness.

Is this the best way to solve the issue?

No: awaiting the coalesced child is the right owner-boundary repair, but the proposed handoff logic must retain or settle the current waiter when the heartbeat handler changes generation.

Full review comments:

  • [P2] Preserve settlements across handler replacement — src/infra/heartbeat-wake.ts:542-552
    When a handler replacement increments the generation after the old handler has produced a terminal result, retainWake is false and this handoff starts at the next wake. The current awaited settlement is dropped, so its cron parent remains running until the watchdog reports a timeout despite the child having completed. Settle that waiter with the result or requeue the current wake, and cover this interleaving.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add merge-risk: 🚨 other: Merging can record a watchdog timeout instead of a completed heartbeat result during handler replacement, producing incorrect operator-visible cron history.
  • 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: The author association is MEMBER, so the external-contributor real-behavior-proof gate does not apply; the supplied older terminal artifacts were not independently reachable from this review environment and are not used to clear the remaining exact-head race.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: The PR repairs inaccurate cron outcomes but its remaining defect is a bounded lifecycle race rather than an immediate availability or security emergency.
  • merge-risk: 🚨 other: Merging can record a watchdog timeout instead of a completed heartbeat result during handler replacement, producing incorrect operator-visible cron history.
  • 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: The author association is MEMBER, so the external-contributor real-behavior-proof gate does not apply; the supplied older terminal artifacts were not independently reachable from this review environment and are not used to clear the remaining exact-head race.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/infra/heartbeat-wake.settlement.test.ts src/infra/heartbeat-wake.test.ts src/cron/service.heartbeat-payload.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server-cron.test.ts.
  • [P1] node scripts/check-changed.mjs.

What I checked:

  • Current-main behavior: Current main immediately returns an ok cron result after requesting a heartbeat wake, so the reported premature-success behavior remains present without this PR. (src/cron/service/timer-execution.ts:207, 6334c317eb1d)
  • Settlement ownership: The PR correctly changes heartbeat cron execution to await the new settlement callback and maps ran, failed, and skipped results into the existing cron outcome vocabulary. (src/cron/service/timer-execution.ts:211, dc1c560787fa)
  • Dropped waiter on replacement: After an awaited wake returns a terminal result but its handler generation changed, this introduced branch omits the current wake from handoff when retainWake is false. Its settlement is then neither resolved nor requeued. (src/infra/heartbeat-wake.ts:542, dc1c560787fa)
  • Reachable replacement boundary: Handler registration increments the generation and aborts the prior generation; the scheduler owns that registration for the heartbeat runtime, making the post-await generation check a real lifecycle boundary. (src/infra/heartbeat-wake.ts:719, dc1c560787fa)
  • Coverage gap: The new settlement tests cover coalescing, retryable skips, and a hanging handler recovered by replacement, but not a terminal result racing with handler replacement. (src/infra/heartbeat-wake.settlement.test.ts:31, dc1c560787fa)
  • Product boundary: Heartbeat is a system-owned Automation whose persisted monitor row owns cadence, and embedded heartbeat turns use the cron-nested lane; this supports treating the parent result as a lifecycle outcome rather than dispatch acknowledgement. Public docs: docs/gateway/heartbeat.md. (docs/gateway/heartbeat.md:15, dc1c560787fa)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Add a focused test where a terminal old-handler result and handler replacement interleave, then prove the waiting cron parent receives a terminal result rather than its watchdog timeout.

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-08-31T21:06:05.555Z sha 3fbe17d78ba5c43837bd84f8edbfcfeb76dc4cb2 :: needs maintainer review before merge. :: none

@fuller-stack-dev
fuller-stack-dev force-pushed the fix/heartbeat-cron-settlement branch from 3fbe17d to 20a7916 Compare August 31, 2026 21:12
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

ClawSweeper rank-up move resolved: I accept the +160 net production-line lifecycle cost because this repair needs one bounded many-parent-to-one-child settlement path plus exact active-owner exclusion. The logic remains concentrated in heartbeat-wake-settlement and its wake-queue integration; existing cron timeout and startup recovery bound the wait. A new public dispatch state, direct heartbeat execution, or a label-only correction would either widen the protocol/persistence surface or lose coalescing and cancellation semantics. Independent review found no actionable issue, and the mechanical fresh-main rebase preserved the patch byte-for-byte.

@fuller-stack-dev
fuller-stack-dev force-pushed the fix/heartbeat-cron-settlement branch from 20a7916 to dc1c560 Compare August 31, 2026 21:22
@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. 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. and removed 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 Aug 31, 2026
@fuller-stack-dev
fuller-stack-dev force-pushed the fix/heartbeat-cron-settlement branch from dc1c560 to a2aa35f Compare August 31, 2026 21:32
@fuller-stack-dev
fuller-stack-dev merged commit 1b69866 into main Aug 31, 2026
251 checks passed
@fuller-stack-dev
fuller-stack-dev deleted the fix/heartbeat-cron-settlement branch August 31, 2026 21:41
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via squash.

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]>
yozakura-ava pushed a commit to yozakura-ava/openclaw that referenced this pull request Oct 9, 2026
Drop the cron lane-depth discount. It subtracted a count of foreign cron
markers from a count of Cron lane entries, but those are different
populations with different lifecycles: a scheduled run publishes its marker
without entering the lane (src/cron/service/run-admission.ts), while a
queued manual run holds a lane slot before its marker exists
(src/cron/service/ops-run-preparation.ts). An equal-count mismatch therefore
escaped the fail-closed guard and could let a heartbeat fire into its own
queued automation.

The marker term is now agent-scoped via hasActiveCronJobsForAgent and
hasActiveCronJobsForAgentExceptMarkers, so another agent's running cron job
no longer blocks this agent's heartbeat. listCronHeartbeatWaitOwners stays
process-wide as in openclaw#134464: its owners carry the exact lane task they occupy,
which makes the exemption an exact identity match rather than a count-based
guess. CronNested and HookDispatch remain global by design because they are
entered with no owning cron marker; both residuals are pinned by tests and
need agentId on CommandLaneTaskMarker, which is out of scope here.
steipete added a commit that referenced this pull request Oct 15, 2026
…er agents (#167845)

* fix(heartbeat): scope cron busy-gate to the target agent

Cron work for one agent starved heartbeats for every other agent on a
multi-agent gateway: the busy-gate used process-global hasActiveCronJobs()
plus process-wide Cron/CronNested/HookDispatch lane depths, while the
reply-run gate beside it was already agent-scoped via hasActiveRunForAgent.

Scope the cron gate the same way:

- add hasActiveCronJobsForAgentExceptMarkers(), countActiveCronJobsForOtherAgents()
  and listCronHeartbeatWaitOwnersForAgent() to src/cron/active-jobs.ts
- use them in src/infra/heartbeat-runner-execution.ts, preserving the
  ownsCronLaneTask exemption per agent

CommandLaneTaskMarker carries no agentId, so the Cron-lane depth is
corrected by discounting runs this process can attribute to other agents.
Markers with no recorded agent stay in the global count, keeping the
documented safe default: unattributed work keeps suppressing every agent
rather than letting a heartbeat fire into cron work it cannot name.
CronNested/HookDispatch have no run attribution at all today and so keep
counting process-wide.

A cron run against agent X still suppresses agent X's heartbeats; only
cross-agent suppression is removed. Single-agent gateways are unchanged.

* fix(heartbeat): fail closed on the cron lane discount; pin the nested-lane residual

Rin REWORK round 1 on 9a779b6f.

R3: the foreign-run discount clamped with Math.max(0, ...), which silently
reports a busy lane as idle whenever the foreign-marker count exceeds observed
lane depth. Markers are created at admission while a lane slot is held only
while the task is queued or running, so the two views can disagree. Fail closed
instead: when they disagree, keep counting the lane globally. Also drop the
comment's unproven "one admitted cron run holds exactly one Cron lane slot"
claim.

R1: CronNested and HookDispatch stay process-global, but not because they are
cron-only -- gateway hook dispatch and the reply-runner fallback enqueue into
them with no owning cron marker, so "every cron run belongs to another agent"
would not prove the work is foreign and relaxing on that basis would be
unsound. Kept fail-closed, documented in place, and pinned by two new tests
that name the residual and will flip to "ready" once per-agent attribution
lands on CommandLaneTaskMarker.

NOT TEST-VERIFIED: the infra shard could not be scoped to run in this
environment (see card 9a779b6f). Lint clean; cron shard unaffected.

* fix(heartbeat): scope the cron marker gate to the target agent

Drop the cron lane-depth discount. It subtracted a count of foreign cron
markers from a count of Cron lane entries, but those are different
populations with different lifecycles: a scheduled run publishes its marker
without entering the lane (src/cron/service/run-admission.ts), while a
queued manual run holds a lane slot before its marker exists
(src/cron/service/ops-run-preparation.ts). An equal-count mismatch therefore
escaped the fail-closed guard and could let a heartbeat fire into its own
queued automation.

The marker term is now agent-scoped via hasActiveCronJobsForAgent and
hasActiveCronJobsForAgentExceptMarkers, so another agent's running cron job
no longer blocks this agent's heartbeat. listCronHeartbeatWaitOwners stays
process-wide as in #134464: its owners carry the exact lane task they occupy,
which makes the exemption an exact identity match rather than a count-based
guess. CronNested and HookDispatch remain global by design because they are
entered with no owning cron marker; both residuals are pinned by tests and
need agentId on CommandLaneTaskMarker, which is out of scope here.

* test(heartbeat): use inferred deferred types

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: yozakura-ava <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…er agents (openclaw#167845)

* fix(heartbeat): scope cron busy-gate to the target agent

Cron work for one agent starved heartbeats for every other agent on a
multi-agent gateway: the busy-gate used process-global hasActiveCronJobs()
plus process-wide Cron/CronNested/HookDispatch lane depths, while the
reply-run gate beside it was already agent-scoped via hasActiveRunForAgent.

Scope the cron gate the same way:

- add hasActiveCronJobsForAgentExceptMarkers(), countActiveCronJobsForOtherAgents()
  and listCronHeartbeatWaitOwnersForAgent() to src/cron/active-jobs.ts
- use them in src/infra/heartbeat-runner-execution.ts, preserving the
  ownsCronLaneTask exemption per agent

CommandLaneTaskMarker carries no agentId, so the Cron-lane depth is
corrected by discounting runs this process can attribute to other agents.
Markers with no recorded agent stay in the global count, keeping the
documented safe default: unattributed work keeps suppressing every agent
rather than letting a heartbeat fire into cron work it cannot name.
CronNested/HookDispatch have no run attribution at all today and so keep
counting process-wide.

A cron run against agent X still suppresses agent X's heartbeats; only
cross-agent suppression is removed. Single-agent gateways are unchanged.

* fix(heartbeat): fail closed on the cron lane discount; pin the nested-lane residual

Rin REWORK round 1 on 9a779b6f.

R3: the foreign-run discount clamped with Math.max(0, ...), which silently
reports a busy lane as idle whenever the foreign-marker count exceeds observed
lane depth. Markers are created at admission while a lane slot is held only
while the task is queued or running, so the two views can disagree. Fail closed
instead: when they disagree, keep counting the lane globally. Also drop the
comment's unproven "one admitted cron run holds exactly one Cron lane slot"
claim.

R1: CronNested and HookDispatch stay process-global, but not because they are
cron-only -- gateway hook dispatch and the reply-runner fallback enqueue into
them with no owning cron marker, so "every cron run belongs to another agent"
would not prove the work is foreign and relaxing on that basis would be
unsound. Kept fail-closed, documented in place, and pinned by two new tests
that name the residual and will flip to "ready" once per-agent attribution
lands on CommandLaneTaskMarker.

NOT TEST-VERIFIED: the infra shard could not be scoped to run in this
environment (see card 9a779b6f). Lint clean; cron shard unaffected.

* fix(heartbeat): scope the cron marker gate to the target agent

Drop the cron lane-depth discount. It subtracted a count of foreign cron
markers from a count of Cron lane entries, but those are different
populations with different lifecycles: a scheduled run publishes its marker
without entering the lane (src/cron/service/run-admission.ts), while a
queued manual run holds a lane slot before its marker exists
(src/cron/service/ops-run-preparation.ts). An equal-count mismatch therefore
escaped the fail-closed guard and could let a heartbeat fire into its own
queued automation.

The marker term is now agent-scoped via hasActiveCronJobsForAgent and
hasActiveCronJobsForAgentExceptMarkers, so another agent's running cron job
no longer blocks this agent's heartbeat. listCronHeartbeatWaitOwners stays
process-wide as in openclaw#134464: its owners carry the exact lane task they occupy,
which makes the exemption an exact identity match rather than a count-based
guess. CronNested and HookDispatch remain global by design because they are
entered with no owning cron marker; both residuals are pinned by tests and
need agentId on CommandLaneTaskMarker, which is out of scope here.

* test(heartbeat): use inferred deferred types

---------

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: yozakura-ava <[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: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L 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.

[Bug]: Heartbeat cron run is recorded succeeded before its cron-nested agent turn fails

1 participant