Skip to content

fix: avoid duplicate agent turns for acknowledged completions - #141352

Closed
maximilliangrand wants to merge 1 commit into
openclaw:mainfrom
maximilliangrand:fix/heartbeat-consumed-completions
Closed

maximilliangrand wants to merge 1 commit into
openclaw:mainfrom
maximilliangrand:fix/heartbeat-consumed-completions

Conversation

@maximilliangrand

@maximilliangrand maximilliangrand commented Sep 7, 2026 •

Copy link
Copy Markdown

Status, October 20, 2026: superseded on main. The host-exec notification path targeted here was replaced by merged #167113 (753a7a57be105d1d64d5205cce0c8486a0662453). The maintainer closed the underlying issue with this explanation and acknowledgement of the investigation. Current main routes host completion notifications through ordinary session execution and retains the exact receipt cancellation callback for terminal polling. This PR remains closed; the implementation and validation below describe the historical heartbeat candidate, not a merged change. This does not claim cancellation can undo an already-started model request.

Related: #141202

What Problem This Solves

Fixes an unnecessary agent turn when a completed background command is read while heartbeat preparation is still awaiting routing. The redundant turn processes an obsolete completion notice and can repeat long-context inference.

User Impact

Already-observed completions no longer trigger this follow-up. Unobserved completions, remaining cron work, due tasks, and scheduled cadence still run. Unread events remain queued if dispatch or delivery fails.

This is a bounded fix for acknowledgement during heartbeat-owned preparation. It does not retract a turn after generic dispatch starts or close later waits inside the generic dispatcher. The reporter's live Windows/provider trace does not establish this exact ordering; the regression below reproduces it independently.

Why This Change Was Made

Revalidate the original event occurrences after heartbeat preparation and use their surviving selection for the prompt, outcome policy, and successful consumption. Same-text successor events retain their own identities.

If removing an event invalidates its delivery route, return the existing retryable preempted outcome so the wake owner rebuilds routing. A consumed completion also loses its WebChat publication permission; coalesced cron work cannot inherit that permission. No grace timer, early event consumption, or additional routing owner is introduced.

Thanks to @wpu911 for the report and ordering examples in #141202. Allow edits from maintainers remains enabled.

Evidence

Rebased onto 4502cad0a1f483561f11c59175e5252b20bf9c51 and validated on macOS arm64 / Node 26.7.0. The mechanical conflict resolution preserves upstream's work-started marker immediately before preparation. Dependencies were refreshed with pnpm install --frozen-lockfile before the post-rebase checks.

The runtime regression starts a real background process, observes its completion using the real process poll tool and production result-acknowledgement hook, runs the real heartbeat/reply/agent pipeline, and reads the persisted transcript. A deterministic local HTTP server supplies the provider response. A wrapper awaits the actual routing resolver and delivers the poll acknowledgement before preparation returns; no reply resolver is injected.

Scenario Unmodified main (ebfe25f8) Fixed
Completion acknowledged during preparation 1 provider request, 1 persisted assistant turn Skipped; 0 provider requests, 0 assistant turns
Completion remains unobserved 1 provider request, 1 persisted assistant turn 1 provider request, 1 assistant turn

Replay the committed runtime regression:

node scripts/run-vitest.mjs src/infra/heartbeat-runner.exec-acknowledgement.test.ts

Both runtime cases pass. Before the mechanical rebase, the standalone file took 4.25 seconds of test execution and 29.03 seconds command wall time including cold worker compilation. In the post-rebase four-file run, with TypeScript checking concurrently, its test execution took 11.67 seconds. This integration cost verifies real model-request dispatch and transcript creation; the existing stale-exec test file supplies the cheaper event-selection and retry controls.

Additional validation:

  • After rebasing and refreshing dependencies: 95 tests passed across the stale-exec, real acknowledgement, wake-preemption, and upstream poll-disposition files, in 62.86 seconds command wall time.
  • Post-rebase core and selected infra-test TypeScript checks, resolved-file formatting, and git diff --check passed.
  • Before rebasing, on ebfe25f8: 298 tests passed and 1 Windows-only case skipped across 14 files (274 heartbeat/event tests and 24 Git worktree tests), in 190.76 seconds command wall time. Core and selected infra-test TypeScript checks, typed lint, formatting, and git diff --check passed on that version.
  • Independent source review and the repository's autoreview workflow found no remaining actionable P0–P2 findings in the six-file patch before rebasing. The conflict resolution received independent source review; its range-diff contains only the preserved upstream admission-marker context.
  • The worktree stdout-limit test that failed in the previous Windows CI run passes locally. This macOS run does not explain or prove a fix for that Windows failure.

At head 9b1e05f, CI has 151 successful checks but three failed test jobs, which leave the aggregate CI gate red:

  • Extension bundle 18: two native Codex output-fidelity cases report Expected native command execution.
  • Extension bundle 28: memory candidate-repair completion remains zero instead of two.
  • Compact large 12: Gateway session-cleanup failures, followed by lease and migration errors.

The failures are outside the six changed files, but that alone does not establish that they are unrelated. An unchanged-base reproduction has not been completed. No CI rerun or test suppression was used to hide these failures. No external model, live channel, or Windows runtime result is claimed.

@clawsweeper

clawsweeper Bot commented Sep 7, 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.

@maximilliangrand
maximilliangrand marked this pull request as ready for review September 7, 2026 16:34
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 7, 2026
@clawsweeper

clawsweeper Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 7, 2026, 6:57 AM ET / 10:57 UTC (Revision 4).

ClawSweeper review

What this changes

The PR rechecks queued background-command completions before starting an agent turn and rebuilds the prompt and delivery policy from surviving events.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Needs changes before merge - 2 items remain

The fix remains necessary, but surviving cron work can inherit a consumed completion's busy-guard exemption. The proof-positive replacement also has merge conflicts, so it does not yet justify closing this branch.

Priority: P2
Reviewed head: 9b1e05f10890e95fb640ef4149ed850d1465b465

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong production-boundary proof supports the central repair, but surviving work still needs correct busy admission.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Contributor execution exercises the changed heartbeat owner through real subprocess completion, poll acknowledgement during actual routing, HTTP client dispatch, and transcript persistence on macOS. The acknowledged case falls from one request and assistant turn to zero while the unobserved control retains both; the deterministic loopback provider is sufficient for this internal ordering contract. No stored-data format changes are introduced.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Contributor execution exercises the changed heartbeat owner through real subprocess completion, poll acknowledgement during actual routing, HTTP client dispatch, and transcript persistence on macOS. The acknowledged case falls from one request and assistant turn to zero while the unobserved control retains both; the deterministic loopback provider is sufficient for this internal ordering contract. No stored-data format changes are introduced.
Evidence reviewed 8 items Pinned introduced change: Reviewed the merge-base-to-head production hunks and complete changed test files. The added revalidation narrows the event selection and rebuilds the prompt immediately before dispatch.
Surviving work retains stale admission: Wake admission exempts a targeted session completion from agent-wide Main, Cron, and active-run guards. The introduced runner code can remove that completion and dispatch surviving cron work without returning through those guards. The exemption already exists in the pinned base; processing the narrowed cron selection under it is the introduced trigger.
Current main still needs the central fix: Fetched main prepares a snapshot, awaits dispatcher loading and typing, then builds the agent input from that prepared snapshot without rereading selected occurrences. The merged visible-child and manual-cancellation fixes address different notification causes.
Findings 1 actionable finding [P2] Rebuild admission when the exempting completion is consumed
Security None None.

How this fits together

Background commands queue completion events that wake OpenClaw's heartbeat runner. The runner selects pending work, prepares its delivery route, and dispatches an agent turn whose successful handling consumes the selected events.

flowchart TD
  A[Background command finishes] --> B[Session event queue]
  C[Process poll acknowledges result] --> B
  B --> D[Heartbeat preparation]
  D --> E[Recheck selected events]
  E --> F[Skip or retry]
  E --> G[Agent turn for surviving work]
  G --> H[Deliver reply and consume events]
Loading

Before merge

  • Rebuild admission when the exempting completion is consumed (P2) - A targeted exec wake containing a completion and a cron event can pass resolveHeartbeatWakeStage while the Main lane or another agent session is busy, because isSessionExecCompletion exempts it from those guards. If polling consumes that completion during preparation, this new selection rebuild dispatches the surviving cron event directly: the cron event prevents shouldSkipConsumedExecWake from skipping, and an unchanged or explicit route prevents routing preemption. Ordinary cron work therefore inherits a busy exemption reserved for the session's completion, instead of being deferred. Return retryable preempted when the completion supporting admission disappears, and cover the retry's busy result. This is a late discovery on the unchanged previously reviewed head.
  • Complete next step (P2) - Integrate one implementation with current main, repair the consumed-completion admission exemption, and validate surviving cron work through the busy guards before merge.

Findings

  • [P2] Rebuild admission when the exempting completion is consumed — src/infra/heartbeat-runner-run.ts:103-110
Agent review details

Security

None.

PR surface

Source +96, Tests +443. Total +539 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 109 13 +96
Tests 2 444 1 +443
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 553 14 +539

Review metrics

Metric Value Why it matters
Production versus regression growth production net +96 lines; tests net +443 lines Production growth implements occurrence revalidation and policy rebuilding; the larger regression surface covers real dispatch and surviving-work behavior.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #141202
Summary: This PR addresses the preparation-window subset of the canonical acknowledgement race; the overlapping replacement is still conflicting and cannot safely supersede it yet.

Members:

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

Technical review

Best possible solution:

Keep one heartbeat-owned revalidation path that rebuilds surviving work and retries admission whenever the completion supporting its busy exemption disappears.

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

Yes: source and contributor before/after boundary evidence establish the preparation race. The remaining finding can be exercised with a targeted completion plus a cron event, a busy Main lane, and acknowledgement during routing; this review did not execute that scenario.

Is this the best way to solve the issue?

Unclear as submitted: queue-owned occurrence revalidation is the right repair, but prompt rebuilding must also invalidate admission decisions that depended on a now-consumed completion.

Full review comments:

  • [P2] Rebuild admission when the exempting completion is consumed — src/infra/heartbeat-runner-run.ts:103-110
    A targeted exec wake containing a completion and a cron event can pass resolveHeartbeatWakeStage while the Main lane or another agent session is busy, because isSessionExecCompletion exempts it from those guards. If polling consumes that completion during preparation, this new selection rebuild dispatches the surviving cron event directly: the cron event prevents shouldSkipConsumedExecWake from skipping, and an unchanged or explicit route prevents routing preemption. Ordinary cron work therefore inherits a busy exemption reserved for the session's completion, instead of being deferred. Return retryable preempted when the completion supporting admission disappears, and cover the retry's busy result. This is a late discovery on the unchanged previously reviewed head.
    Confidence: 0.96
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): Contributor execution exercises the changed heartbeat owner through real subprocess completion, poll acknowledgement during actual routing, HTTP client dispatch, and transcript persistence on macOS. The acknowledged case falls from one request and assistant turn to zero while the unobserved control retains both; the deterministic loopback provider is sufficient for this internal ordering contract. No stored-data format changes are introduced.
  • 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: This is a bounded background-completion race that causes redundant inference, with a normal-priority surviving-work admission defect.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (terminal): Contributor execution exercises the changed heartbeat owner through real subprocess completion, poll acknowledgement during actual routing, HTTP client dispatch, and transcript persistence on macOS. The acknowledged case falls from one request and assistant turn to zero while the unobserved control retains both; the deterministic loopback provider is sufficient for this internal ordering contract. No stored-data format changes are introduced.
  • proof: sufficient: Contributor real behavior proof is sufficient. Contributor execution exercises the changed heartbeat owner through real subprocess completion, poll acknowledgement during actual routing, HTTP client dispatch, and transcript persistence on macOS. The acknowledged case falls from one request and assistant turn to zero while the unobserved control retains both; the deterministic loopback provider is sufficient for this internal ordering contract. No stored-data format changes are introduced.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head production hunks and complete changed test files. The added revalidation narrows the event selection and rebuilds the prompt immediately before dispatch. (src/infra/heartbeat-runner-run.ts:96, 9b1e05f10890)
  • Surviving work retains stale admission: Wake admission exempts a targeted session completion from agent-wide Main, Cron, and active-run guards. The introduced runner code can remove that completion and dispatch surviving cron work without returning through those guards. The exemption already exists in the pinned base; processing the narrowed cron selection under it is the introduced trigger. (src/infra/heartbeat-runner-execution.ts:204, 4502cad0a1f4)
  • Current main still needs the central fix: Fetched main prepares a snapshot, awaits dispatcher loading and typing, then builds the agent input from that prepared snapshot without rereading selected occurrences. The merged visible-child and manual-cancellation fixes address different notification causes. (src/infra/heartbeat-runner-run.ts:79, 0dc209168731)
  • Latest-release check: The v2026.9.8 runner likewise dispatches the prepared snapshot without the proposed occurrence revalidation; no shipped implementation of this fix was established. (src/infra/heartbeat-runner-run.ts:79, fc23bc864e45)
  • Production-boundary behavior proof: The captured PR body and contributor comment describe macOS arm64 / Node 26.7.0 execution through a real subprocess, process poll acknowledgement, heartbeat/reply/agent dispatch, HTTP provider client, and persisted transcript. Acknowledgement during routing changes one provider request and assistant turn to zero; the unobserved control retains one of each. Reading the complete committed harness confirms those entrypoints and assertions. The provider response is deterministic loopback output, not an external-model claim. (src/infra/heartbeat-runner.exec-acknowledgement.test.ts:150, 9b1e05f10890)
  • Replacement is not presently a safe supersession target: fix(heartbeat): skip completions acknowledged during preparation #164156 explicitly credits this contribution, targets the same preparation race, and supplies detailed positive before/after runtime traces plus an admission-revalidation case. Its supplied snapshot is truncated; a separate live REST read supplied the complete current body. GitHub currently reports the replacement open, unmerged, mergeable=false, and mergeable_state=dirty at head 718bf16. (718bf16e701e)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: 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.

  • Return surviving cron work through fresh admission when its completion exemption disappears, and demonstrate deferral while the Main lane is busy.
  • Resolve current-main conflicts on the chosen implementation branch while preserving contributor credit and queue-occurrence semantics.

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-09-07T16:40:41.525Z sha 8d35141f4b56085710cc55d452568c04badc4312 :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-22T13:26:46.571Z sha 0c77c807412aab92194ed2c177113d3b3060e019 :: needs changes before merge. :: none
  • reviewed 2026-09-22T16:39:44.348Z sha 9b1e05f :: needs maintainer review before merge. :: none

@maximilliangrand
maximilliangrand force-pushed the fix/heartbeat-consumed-completions branch from 8d35141 to 0c77c80 Compare September 22, 2026 13:20
@maximilliangrand

maximilliangrand commented Sep 22, 2026 •

Copy link
Copy Markdown
Author

Rebased onto 4502cad0a and updated the description with actual runtime before/after proof. The committed regression launches a background process and exercises process polling, the production acknowledgement hook, real reply/agent dispatch, a deterministic loopback provider, and transcript persistence. An acknowledgement during preparation now produces zero model requests and zero assistant turns; the unobserved control still produces one of each.

The description also states the precise preparation boundary and distinguishes this reproduction from the reporter's Windows/provider timing trace. Coalesced work retains its own event identities and delivery policy, with regression coverage for WebChat publication and route changes.

The conflict resolution preserves upstream's work-started marker before preparation. After refreshing the frozen dependencies, all 95 focused acknowledgement/wake-owner tests and both core and infra-test TypeScript checks pass. The description separates this validation from the broader test run and formal review performed before the mechanical rebase.

@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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 22, 2026
@maximilliangrand
maximilliangrand force-pushed the fix/heartbeat-consumed-completions branch from 0c77c80 to 9b1e05f Compare September 22, 2026 13:27
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 7, 2026
@clawsweeper clawsweeper Bot added 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 Oct 7, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Oct 8, 2026
@vincentkoc

Copy link
Copy Markdown
Member

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

@vincentkoc vincentkoc closed this Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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.

2 participants