Skip to content

fix(heartbeat): cron jobs for one agent starve heartbeats for all other agents - #167845

Merged
steipete merged 7 commits into
openclaw:mainfrom
yozakura-ava:upstream-hb-gate
Oct 15, 2026
Merged

steipete merged 7 commits into
openclaw:mainfrom
yozakura-ava:upstream-hb-gate

Conversation

@yozakura-ava

@yozakura-ava yozakura-ava commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Related: #167844

What Problem This Solves

Cron work for one agent can continuously suppress scheduled heartbeats for every other agent on the same Gateway.

User Impact

Heartbeats can run while another agent has active or queued automation work. Work targeting the heartbeat's own agent or session still defers it, and exact cron executions waiting for heartbeat settlement remain exempt. Legacy or unbound work without a recorded target stays conservative and blocks all agents. No configuration change or migration is required.

Why This Change Was Made

The original fix scoped active cron markers but left actual cron model turns blocked by global queue counts. The command queue now retains its existing execution target when an entry becomes active, replacing the task-ID Set with one Map. Heartbeat uses the same target predicate for current markers and active/queued Cron, CronNested, and HookDispatch entries. It never infers lane ownership by subtracting unrelated marker counts. Unfiltered queue counts retain their constant-time path.

Cron receipt publication also records an explicit target session because the job owner and an agent-qualified execution key can differ. Targets describe the admitted operation, not later job edits. Current queue membership and generation fences own cleanup; marker generation and exact identity own the heartbeat-wait exemption. No new deferred external effect or permission is introduced.

Main's ambient channel-readiness backoff (#173003) and self-removal owner guard (#167857) are preserved. The original review's lane-level concern is addressed; this retains a Related reference because legacy/unattributed work and the main command lane remain conservative global guards.

Original fix by @yozakura-ava; maintainer cleanup completes queue targeting, removes the duplicate private-predicate tests and 208-line synthetic-depth suite, and adds smaller coverage in the existing heartbeat and queue tests.

Evidence

  • Source confirmation: main at c66b651210ab2efa74c5670a31d43e4dfc27106e used process-global marker queries and all three cron-related lane depths. Current cron receipt publication supplies agent ownership, and embedded execution/compaction already enqueue with session targets.
  • Exact-head CI run 38737320593 passed for 4794818c99d20623157fe0d17881c60a114c87a7, including openclaw/ci-gate. The selected tests, production and test types, lint, format, source/architecture guards, and UI integration checks passed. No inherited failure exception is needed for this final CI run.
  • Regressions: scopes scheduled heartbeats to cron targets (owner=$owner, session=$sessionKey); ignores foreign active and queued %s work but protects the target session; the existing heartbeat-wait settlement test now includes foreign active work; counts matching targets with lane concurrency %s; the existing queue-reset replacement test now checks retained target identity.
  • Lint/format: all 12 changed files pass the pinned oxfmt 0.72.0. Direct oxlint passed with zero diagnostics across 11 TypeScript files and 231 rules; the follow-up test cleanup also passes type-aware oxlint (264 rules). The nested wrapper lacks local dependencies; the direct configuration uses the root rule definitions with the UI-only Solid override omitted because its dependency is absent. Full repository lint runs in CI. The formatter hook used an existing validated tooling owner; no dependencies were installed.
  • Deslop: removed duplicated predicates, repeated explanatory comments, and redundant test scaffolding. Codex autoreview (--mode branch, through P2) returned scoped-clean with no actionable findings; it statically checked target scoping, exact waiting-owner exemptions, and queue generation/reset behavior. Pre-commit review also found no actionable findings.
  • First CI head: changed-test jobs and production types passed; lint job 116425793951 found two redundant default type arguments in the new test. They were removed, scoped type-aware lint passed, and a fresh static review found no actionable findings. This was a candidate defect, not an inherited main failure.
  • Test cost: deferred-promise fixtures add no real sleeps or timers. All 16 selected Node test jobs passed; their job wall times were 71–486 seconds, including setup and unrelated selected tests, not isolated regression timings. Local unit tests, negative controls, typechecks, and live Gateway proof were intentionally skipped per maintainer policy; PR CI is the proof gate. No Crabbox/Testbox lease was created.
  • LOC against main: production +75/-44 (net +31), tests +103/-13 (net +90), docs +2/-2 (net 0). Production growth retains target identity across queue admission and handles explicit execution sessions; no unrelated deletions were used to meet a line budget.

ClawSweeper review 6084047604 reported no code findings on the contributor head, requested removal of redundant predicate coverage, and asked for live proof. Redundant coverage is removed. The proof-only request is superseded by maintainer policy: PR CI is the proof.

riko added 2 commits October 9, 2026 14:33
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.
…-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.
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

Scope heartbeat automation guards to recorded agent and session targets while retaining conservative handling of unattributed work.

Example: Agent alpha has a scheduled heartbeat while agent beta has active and queued cron turns.

  • Before: Alpha skips its heartbeat with cron-in-progress.
  • After: Alpha can run; automation targeting alpha or lacking a recorded target still blocks it.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is focused and source-consistent, with passing exact-head CI; overall readiness follows the required proof tier.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: An agent’s periodic background checks can stop running while another agent performs automation.
Reason: The focused repair restores useful agent independence; its Related reference correctly leaves conservative main-lane and unattributed-work behavior outside the claimed fix.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this PR addresses source-confirmed cross-agent heartbeat starvation that remains on current main, and the revised patch has no actionable code findings.

Priority: P1
Reviewed head: 4794818c99d20623157fe0d17881c60a114c87a7

Before merge

  • Add real behavior proof - The changed heartbeat admission and queue owners have regression tests and passing exact-head CI, but no supplied Gateway execution shows the new cross-agent behavior. The PR body’s CI-only policy assertion does not waive this external-PR proof requirement. Add redacted Gateway logs or terminal output showing a bystander scheduled heartbeat completing during foreign active/queued cron work, with same-agent work remaining blocked; redact IPs, API keys, phone numbers, and non-public endpoints. Only transient in-memory targets change, so no persisted-data migration is needed. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

Findings

None.

Tests

  • Missing end-to-end proof: Supply a base-fails/head-passes Gateway scenario showing a scheduled alpha heartbeat completing during beta’s active and queued cron work while same-agent work still defers it; that shipped-entry-point regression has not been demonstrated.
Agent review details

How this fits together

The Gateway heartbeat runner reads cron activity and command-queue ownership before preparing a background agent turn, then either skips the wake or admits it for execution.

flowchart TD
  A[Scheduled heartbeat] --> B[Heartbeat admission]
  C[Cron execution markers] --> B
  D[Active and queued command targets] --> B
  B --> E[Busy skip]
  B --> F[Agent turn and delivery]
Loading

Technical review

Best possible solution:

Use queue-owned execution targets to admit independent agents’ heartbeats while preserving same-agent exclusion, exact waiting-owner exemptions, and conservative unattributed-work guards.

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

Current-main source deterministically returns cron-in-progress for an otherwise eligible alpha heartbeat while beta owns non-waiting cron activity or automation lane work; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The revised approach fixes attribution at the existing queue owner instead of subtracting unrelated marker counts, and preserves cleanup and capacity semantics without another state owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Heartbeat automation busy guards changes intended behavior with a stated reason (fix: report settled heartbeat cron outcomes #134464: Waiting cron executions must not block their own heartbeat, while unrelated work remains a busy signal; the patch explicitly narrows unrelated work using authoritative targets.)
  • Command queue activity and shared capacity keeps the original intent (3374f78: Capacity derives from canonical active tasks so completion, timeout, abort, and reset share cleanup; replacing the ID set with a target map preserves that lifecycle.)
  • Cron launch and receipt publication keeps the original intent (refactor(cron): centralize durable run queue and launch ownership #169364: The worker queue owns cron activation and the host publishes admitted execution facts; the added session attribution stays on the existing transient marker.)
  • Scheduled heartbeat skip semantics keeps the original intent (5599536: Never-started event-free polls skip to their next cadence rather than accumulating running work; this PR changes target matching while retaining that outcome.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c4f1483 adds src/process/command-queue.ts:245 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c4f148368aee; files: src/process/command-queue.ts)
  • Jason (Json): Raw commit 1b69866 adds src/cron/active-jobs.ts:257 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1b69866e08d4; files: src/cron/active-jobs.ts)

PR surface

Source +31, Tests +90, Docs 0. Total +121 across 12 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 75 44 +31
Tests 3 103 13 +90
Docs 1 2 2 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 12 180 59 +121

Review metrics

Metric Value Why it matters
Production versus test LOC Production +75/-44; tests +103/-13 The focused growth retains active execution targets and adds independent queue and heartbeat contract coverage.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #167844
Summary: This PR is the active candidate repair for the paired cross-agent heartbeat starvation report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P1: Foreign automation can repeatedly suppress unattended heartbeat workflows across a multi-agent Gateway, with source confirmation and current-release field reports.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-09T15:31:34.131Z sha f594eca :: needs real behavior proof before merge. :: [P2] [P2] Discount only foreign jobs that own actual Cron lane entries
  • reviewed 2026-10-09T16:23:31.703Z sha 6ec94fc :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-09T16:40:01.230Z sha 6ec94fc :: needs real behavior proof before merge. :: none

Reviewed October 15, 2026, 9:11 AM ET / 13:11 UTC (Revision 4).

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.
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Oct 9, 2026
steipete and others added 2 commits October 15, 2026 05:31
Merge current main and complete the contributor's marker-scoping fix with
queue-owned target facts for active and queued cron/nested/hook work. Preserve
same-agent/session exclusion, exact heartbeat-wait exemptions, and conservative
unbound-target behavior. Consolidate regressions into existing owner suites.

Related: openclaw#167844
Original fix: openclaw#167845 by @yozakura-ava.
Validation: changed-file lint/format and static Codex autoreview. Unit tests,
typechecks, and live proof are delegated to PR CI per maintainer policy.

Co-authored-by: yozakura-ava <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels Oct 15, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Oct 15, 2026
@steipete
steipete merged commit 439366b into openclaw:main Oct 15, 2026
143 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

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

docs Improvements or additions to documentation gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants