Skip to content

fix(heartbeat): let a conversation's chained command completions skip the interval wait - #164756

Merged
obviyus merged 1 commit into
mainfrom
fix/exec-completion-chain-cooldown
Oct 5, 2026
Merged

obviyus merged 1 commit into
mainfrom
fix/exec-completion-chain-cooldown

Conversation

@obviyus

@obviyus obviyus commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #164719, #17797, #75436

What Problem This Solves

Fixes: step 2 of a chained background request ("run A; when it finishes, tell me and run B") reaches the chat up to one heartbeat interval late when a heartbeat ran less than every ago.

#164719 (merged as f0b38ed) made a command started inside a conversation's completion turn belong to that conversation, so its result goes back to that chat or topic. Its completion wake still goes through the heartbeat event cooldown, though (shouldDeferWake in src/infra/heartbeat-cooldown.ts). The completion turn for step 1 counts as a heartbeat run, so when step 2 finishes more than 30 s later, its wake is deferred not-due until lastRun + every. Measured live on origin/main: with every: 3m, step 2 arrived about 2m22s after the command exited. With every: 1h, no wake came in 5+ minutes; the before run below waited 8+ minutes.

User Impact

User impact: when the agent starts a background command while answering a previous command's result, the new result comes back about as soon as the command exits, instead of waiting up to the heartbeat interval (an hour on a typical quiet setup). Periodic heartbeats, heartbeat-started commands, automation-started commands and other event wakes keep the full cooldown. No new settings, messages or warnings.

Why This Change Was Made

Provenance

Fix

startHeartbeatRunner peeks the targeted session's pending events for an exec-event wake, excluding heartbeat delivery-awareness notices (the same view the prompt builder uses). When every pending event is a conversation-owned exec completion (isConversationExecCompletion, now shared with heartbeat-runner-prompt.ts), shouldDeferWake skips only the not-due gate. The other guards still apply:

  • the 5-starts-per-60 s flood guard (DEFAULT_FLOOD_THRESHOLD / DEFAULT_FLOOD_WINDOW_MS), which is checked first
  • the 30 s minimum spacing between event turns (DEFAULT_MIN_WAKE_SPACING_MS)

Heartbeat-owned, automation, mixed and unflagged queues keep the full #17797 / #75436 cooldown.

No chain cap (maintainer decision)

An earlier draft of this PR proposed a chain-depth cap. It was dropped. On origin/main, short commands already chain every 30 s through retained wakes, with no total bound. Letting conversation-owned completions skip the not-due gate adds no new unbounded case; it only stops penalizing commands that run longer than 30 s. The rate guards stay as they are, and each turn is model-gated.

Bounded cost

  • Worst case for one conversation whose model starts a new background command in every completion turn: one turn per 30 s, 2 per minute, 120 per hour. That is the same ceiling origin/main already allows for commands shorter than 30 s. A chain of 40 s commands runs at most 1.5 turns per minute (14 in 10 simulated minutes in the regression).
  • Across wake paths, the flood guard caps admitted starts at 5 per 60 s per agent, and it is checked before the exemption.
  • Each turn is a model turn the model chose to continue; the model can end the chain (NO_REPLY stays silent), and tools.exec.notifyOnExit: false turns completion turns off.
  • Heartbeat-owned chains are unchanged: a heartbeat-started 40 s command chain still gets 1 turn in 10 minutes.
  • No new state, config or stored data.

Evidence

Regressions (real scheduler, src/infra/heartbeat-runner.scheduler.test.ts)

These drive startHeartbeatRunner through requestHeartbeat with real system-event queue entries. Fake time, 10 simulated minutes, and each turn starts the next command:

Row Turns On origin/main's cooldown
conversation, instant command 20 (every ≥30 s) 20 (same: retained wakes)
conversation, 40 s command 14 fails: 1
heartbeat-owned, 40 s command 1 1
conversation completion beside an unflagged reminder 1 1
conversation completion after a heartbeat delivery-awareness notice 14 fails: 1

"holds a conversation's completion turn behind the flood guard": after 5 manual runs, a conversation completion at 40 s does not run until the flood window clears at 60 s.

Mutation checks: moving the exemption ahead of the flood guard fails 2 rows; every → some fails the reminder row; dropping the delivery-awareness filter fails the awareness row.

Checks: tsgo:core and tsgo:core:test pass. Scheduler, cooldown, event-routing and broadcast-outcome suites pass (4 files, 85 tests).

Test cost: pnpm test src/infra/heartbeat-runner.scheduler.test.ts --maxWorkers=1 takes 20.2 s wall time locally on a cold transform cache (Vitest duration 17.7 s, 96% of it transform; 31 tests). The six added tests run in 1–5 ms each on fake timers, with no real timers or process boots. In CI (checks-node-changed-6, run 37367320373) the file took 2.84 s (Vitest duration), and its shard finished in 3.99 s.

CI: everything passes except check-lint-core-2, which is inherited. It fails on src/state/openclaw-agent-execution-incognito.compute.test.ts (max-lines, 1024 > 1000). That file isn't touched here, and oxlint reproduces the same error on clean origin/main 0ac81cf. Earlier cancellations ("job was not acquired by Runner of type hosted") were runner capacity and passed on rerun.

Live: Telegram Test Server forum topic, real gpt-6-astra

Config in our setup's shape: heartbeat every: 1h, target: "none", isolatedSession: true, lightContext: true, directPolicy: "allow", active hours set. The prompt asks for two chained sleep 40; echo RESULT-<nonce>-A|B background steps.

Run Head Step 2 command exits Step 2 result in the topic
Before origin/main 0ac81cf 19:41:23Z never: no wake for 8m15s, until the gateway stopped at 19:49:38Z
After 3e5ab66 19:53:48.3Z completion turn at 19:53:48.6Z, Step 2 printed: RESULT-C340395F-B posted at 19:53:52.9Z (~5 s after exit, 64 s after "Step 2 started")

Before (origin/main): the topic got "Step 1 started." and "Step 2 started." The step 2 command ran on the topic session (#164719), but because step 1's completion turn had started about 45 s earlier, its wake was deferred not-due until lastRun + 1h.

After: the topic got "Step 1 started and is running in the background.", "Step 2 started and is running in the background.", then Step 2 printed: RESULT-C340395F-B. Step 2's completion turn ran 45 s after step 1's: past the 30 s spacing, well inside every. The first periodic heartbeat poll ran later in its isolated :heartbeat session and posted nothing (target: "none"). No warnings and no other messages.

Unchanged and out of scope: step 1's "Step 1 printed: …" line is commentary text before a tool call, and heartbeat delivery posts only the final payload of a completion turn (existing behavior, noted on #164719).

An earlier after run on the same head

Step 2's command exited at 19:41:18Z. The completion turn started at 19:41:18.1Z, and Step 2 printed: RESULT-639E6818-B was posted at 19:41:22.9Z. In that run, the first user turn ended with an empty final answer from the model. The existing incomplete-turn path posted "⚠️ Agent couldn't generate a response…" at 19:40:12Z, before any completion or heartbeat turn had run, so the scheduler wasn't involved. I reran for a clean timeline (above).

Proof directories (local): events.ndjson (Telegram timeline), gateway.log, the transcript snapshot and root-patch.json for each run.

Reviews

  • Fresh gpt-6-astra reviewer, round 1 on 3e5ab66: LAND, no findings. It confirmed that the queue peek matches preflight for targeted and global keys, isolation and the awareness filter; that retained and merged wakes are unchanged; and that dropping the scheduled-tick and task exclusions is safe, because scheduled ticks already set nextDueMs = now and task intent already skips not-due.
  • Separate loop-safety pass on 3e5ab66: LAND, no findings. Only user turns and route-qualified continuations set the flag; heartbeat, periodic-poll, cron and node events never do. Worst case for one self-chaining conversation is 1 turn per 30 s (120/h), the same as origin/main's short-command chaining. The flood guard is checked before the exemption on targeted and broadcast paths.

LOC vs origin/main: production +38/-5, tests +78, docs +1/-1.

@clawsweeper

clawsweeper Bot commented Oct 4, 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: S labels Oct 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 5:49 PM ET / 21:49 UTC (Revision 4).

ClawSweeper review

What this changes

The heartbeat scheduler lets conversation-owned background command completions skip the periodic interval while preserving event spacing and flood limits.

Merge readiness

✅ Ready for maintainer review

The PR remains necessary: current main still delays these completions until the heartbeat interval. No actionable patch defect remains, and the prior review’s test-cost documentation request is satisfied.

Priority: P2
Reviewed head: 3e5ab66188b3e97456d83ff3b4c3c3239d9c828e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with direct before/after runtime evidence, meaningful scheduler regressions, and the prior documentation follow-up resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured pinned-head Telegram Test Server trace exercises background completion through the production scheduler and records the requested step-2 reply about five seconds after exit, compared with no reply during the before-run observation. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured pinned-head Telegram Test Server trace exercises background completion through the production scheduler and records the requested step-2 reply about five seconds after exit, compared with no reply during the before-run observation. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduced change: The merge-base-to-head diff introduces the completion exemption, shares the existing completion predicate, adds scheduler regressions, and updates heartbeat documentation.
Rate guards remain authoritative: The flood guard runs before the exemption, and eligible completion events still pass the minimum-spacing check. Mixed and unflagged queues do not receive the new interval exemption.
Current main still needs the repair: The fetched main cooldown has exemptions for task intent and retained work, but no conversation-completion exemption; commands finishing beyond the spacing floor can still wait until nextDueMs.
Findings None None.
Security None None.

How this fits together

Background command exits queue completion events that wake OpenClaw’s heartbeat runner. The scheduler decides when those events may start an agent turn, whose existing delivery path returns useful results to the conversation.

flowchart TD
  A[Background command exits] --> B[Session event queue]
  B --> C[Completion ownership check]
  C --> D[Heartbeat scheduler]
  D --> E[Spacing and flood guards]
  E --> F[Agent continuation turn]
  F --> G[Conversation reply]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +34, Tests +78, Docs 0. Total +112 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 38 4 +34
Tests 1 78 0 +78
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 117 5 +112

Review metrics

None.

Technical review

Best possible solution:

Keep conversation completions responsive through the existing runner while preserving periodic-work cooldowns and shared rate guards.

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

Yes: current-main source exposes the interval deferral after a preceding completion turn when the next command takes more than 30 seconds; the captured before/after live run corroborates it. This review did not execute a reproduction.

Is this the best way to solve the issue?

Yes: the patch repairs the existing scheduler decision and shares the completion classifier without adding another wake owner, setting, or delivery path.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded responsiveness repair for chained background commands, with existing spacing and flood protection preserved.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured pinned-head Telegram Test Server trace exercises background completion through the production scheduler and records the requested step-2 reply about five seconds after exit, compared with no reply during the before-run observation. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured pinned-head Telegram Test Server trace exercises background completion through the production scheduler and records the requested step-2 reply about five seconds after exit, compared with no reply during the before-run observation. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduced change: The merge-base-to-head diff introduces the completion exemption, shares the existing completion predicate, adds scheduler regressions, and updates heartbeat documentation. (src/infra/heartbeat-runner-scheduler.ts:227, 3e5ab66188b3)
  • Rate guards remain authoritative: The flood guard runs before the exemption, and eligible completion events still pass the minimum-spacing check. Mixed and unflagged queues do not receive the new interval exemption. (src/infra/heartbeat-cooldown.ts:35, 3e5ab66188b3)
  • Current main still needs the repair: The fetched main cooldown has exemptions for task intent and retained work, but no conversation-completion exemption; commands finishing beyond the spacing floor can still wait until nextDueMs. (src/infra/heartbeat-cooldown.ts:53, 1b7dd0b2ac92)
  • Existing ownership and delivery boundary: The producer sets conversation ownership for user turns and existing conversation continuations. Preflight still independently requires matching event routes and the stored conversation route before continuing that conversation; this patch changes scheduling rather than delivery authorization. (src/infra/heartbeat-runner-prompt.ts:78, 3e5ab66188b3)
  • Captured real behavior proof: The supplied PR body records a Telegram Test Server forum-topic run through the real Gateway and model with every=1h, target=none, and isolated sessions. Before the fix, step 2 had no reply during an 8m15s observation; on the pinned head it exited at 19:53:48.3Z, started its completion turn at 19:53:48.6Z, and posted the requested result at 19:53:52.9Z. This directly exercises the changed scheduler path; the review did not rerun it. (3e5ab66188b3)
  • Prior review follow-up resolved: The captured body now states the scheduler test command, 20.2s local wall time, 2.84s CI file duration, and 3.99s shard duration. The added table and flood case use fake time and exercise scheduler admission with real event queue entries. (src/infra/heartbeat-runner.scheduler.test.ts:305, 3e5ab66188b3)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (3 earlier review cycles)
  • reviewed 2026-10-04T04:19:38.948Z sha c2c5f3b :: blocked before merge. :: none
  • reviewed 2026-10-04T19:32:55.696Z sha c2c5f3b :: blocked before merge. :: none
  • reviewed 2026-10-05T21:26:33.817Z sha 3e5ab66 :: needs changes before merge. :: none

@obviyus
obviyus force-pushed the fix/exec-completion-origin-session branch from 4dbc218 to 70bad65 Compare October 4, 2026 11:19
@obviyus
obviyus force-pushed the fix/exec-completion-origin-session branch from 70bad65 to 8b1e99b Compare October 4, 2026 16:32
Base automatically changed from fix/exec-completion-origin-session to main October 4, 2026 19:26
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L and removed size: S labels Oct 4, 2026
@obviyus
obviyus force-pushed the fix/exec-completion-chain-cooldown branch from c2c5f3b to 3e5ab66 Compare October 5, 2026 19:42
@obviyus
obviyus marked this pull request as ready for review October 5, 2026 20:03
@obviyus

obviyus commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. labels Oct 5, 2026
@obviyus

obviyus commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit 2883684 into main Oct 5, 2026
328 of 399 checks passed
@obviyus
obviyus deleted the fix/exec-completion-chain-cooldown branch October 5, 2026 21:53
@obviyus

obviyus commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as the merge commit above.

Checked on the exact head 3e5ab66: two gpt-6-astra reviewers LAND (general + loop safety), ClawSweeper ready, live Telegram (every=1h: step 2 arrived ~5 s after exit; main: nothing in 8+ min). Admin merge past one inherited red: check-lint-core-2 max-lines in src/state/openclaw-agent-execution-incognito.compute.test.ts, untouched here and over the limit on clean main.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
… the interval wait (openclaw#164756)

A background command completion started by the conversation (user turn or conversation continuation) now skips the heartbeat not-due wait, so a chained step reports within the existing 30 s spacing instead of waiting up to the heartbeat interval. The flood guard and 30 s spacing still apply; heartbeat-owned and other event wakes keep the full cooldown.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

1 participant