Skip to content

fix(heartbeat): skip completions acknowledged during preparation - #164156

Closed
etzelm wants to merge 1 commit into
openclaw:mainfrom
etzelm:fix/exec-ack-duplicate-wake
Closed

etzelm wants to merge 1 commit into
openclaw:mainfrom
etzelm:fix/exec-ack-duplicate-wake

Conversation

@etzelm

@etzelm etzelm commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Closes #141202

Builds on #141352 by @maximilliangrand. Supersedes #141352.

What Problem This Solves

Fixes: the agent runs a duplicate turn for a background command result it already read with process poll, when that poll lands while a heartbeat is preparing its turn.

A finished background exec queues one completion event with a one-use receipt and requests an exec-event heartbeat wake. Reading the result with process poll removes that event, and a wake that has not started yet retires itself in preflight. But preflight snapshots the pending events before preparation awaits delivery routing and the runner awaits the dispatcher import and typing start. A poll acknowledgement inside those awaits leaves the heartbeat building the exec-completion prompt from a completion that is no longer queued.

User Impact

User impact: a background command result the agent already read no longer triggers a second agent turn. On a local single-slot backend that turn is a full long-context prefill with no reusable prefix; the report shows a 191,557-token prompt taking about 269 s.

Unobserved completions still wake the agent. Work that shares the wake still runs: another unobserved completion, cron events, a coalesced cadence tick, and due heartbeat tasks. Surviving events stay queued until their turn is handled successfully.

Why This Change Was Made

The heartbeat runner owns its event snapshot, so it revalidates it after its last await and immediately before building the turn: it rereads which of the originally selected occurrences are still queued, matched by queue-owned ID, without consuming anything. This is the pattern AGENTS.md prescribes for owner-held authority: revalidate after awaited work, right before the side effect. Process poll keeps owning acknowledgement and the wake owner keeps owning retries; there is no grace timer and no early consumption.

When an occurrence was consumed, everything the heartbeat derived from the selection is rebuilt from the survivors: prompt, turn source, failure copy, restart custody, and session publication eligibility, which now holds only while session-owned work survives. Two decisions are not rebuilt in place, because they belong to earlier owners: admission (a session's own completion lets its wake pass agent-wide busy guards) and routing (an event-owned last/owner turn source, or the session-owned completion route of an internal WebChat session). When a consumed occurrence made either decision, the runner returns the existing retryable preempted result with an immediate retry time, so the wake owner rebuilds both from the live queue instead of reusing them for the survivors.

The change in one sentence

Right before a heartbeat builds its agent turn, it rechecks which of its selected events are still queued and skips, retries, or narrows the turn to the survivors.

Contract

Case Result
Completion acknowledged during preparation, nothing else selected skipped no-pending-event; no agent turn; unrelated queued events stay queued
Another unobserved completion survives runs as an exec turn with only the survivor in the prompt; survivor consumed after success
Survivor's delivery fails failed; survivor stays queued
Coalesced cadence tick or due task survives runs as a heartbeat turn
Same-text completion queued during preparation not part of this wake; stays queued for its own wake
A session wake passed agent-wide busy guards because of its own completion; the completion is consumed and a cron event survives skipped preempted, retry due at once; the retry runs the busy guards (requests-in-flight while the main lane is busy)
Consumed completion's delivery context chose a last/owner route skipped preempted, retry due at once; the retry sends the surviving cron event to its own destination
Consumed completion held a WebChat session-only route, only cadence survives skipped preempted, retry due at once; the retry delivers the cadence turn to the configured target
WebChat session, completion consumed, cron event survives runs as a cron turn; the reply is not published into the session
Restart continuation survives on a restart wake runs; the reply still publishes into the WebChat session
Explicit heartbeat target route unchanged
Nothing consumed prepared turn used as-is; nothing recomputed
Selected occurrence evicted by the queue's 20-event cap during preparation treated like an acknowledgement; the queue is authoritative
Not handled: acknowledgement after the reply dispatcher starts the turn proceeds; later awaits belong to the dispatcher and agent runner

Evidence

Provenance: Mac Studio (macOS 27.0, arm64), Node 24.21.0, head 718bf16e701e on main 7ff3b3be3713, 2026-10-03 07:15 UTC, one sitting and one harness; BEFORE is this branch with only the four production files reverted to main.

The harness is a copy of the committed real-seam regression (src/infra/heartbeat-runner.exec-acknowledgement.test.ts) that records one JSON line per case instead of asserting. It starts a real background exec, waits for its completion event, and runs runHeartbeatOnce through the real heartbeat, reply, and agent pipeline against a loopback OpenAI Responses server, then reads the persisted transcript. The one interception wraps the real routing resolver: in the acknowledged case it calls the real process poll tool and the production result-acknowledgement hook while preparation is awaiting routing. No reply resolver is injected. Test-only setup is the loopback provider, the fast-reply test config, and a test scheduler bound for the session MCP runtime, which the embedded agent runner requires.

BEFORE (production change reverted):

EVIDENCE {"case":"completion acknowledged by process poll during heartbeat preparation","backgroundExecStatus":"running","queueBeforeHeartbeat":["Exec completed (cool-nud, code 0) :: SYNTHETIC_COMPLETION"],"pollDuringPreparation":{"status":"completed","aggregated":"SYNTHETIC_COMPLETION"},"queueAfterPoll":[],"heartbeatResult":{"status":"ran","durationMs":4039},"heartbeatEvents":[{"ts":1791011854925,"status":"ok-empty","reason":"exec-event","indicatorType":"ok","silent":true,"durationMs":4039}],"providerRequests":1,"providerRequestCarriesCompletionPrompt":true,"persistedAssistantTurns":1,"queueAfterHeartbeat":[]}
EVIDENCE {"case":"completion left unobserved (control)","backgroundExecStatus":"running","queueBeforeHeartbeat":["Exec completed (clear-su, code 0) :: SYNTHETIC_COMPLETION"],"heartbeatResult":{"status":"ran","durationMs":985},"heartbeatEvents":[{"ts":1791011857197,"status":"ok-empty","reason":"exec-event","indicatorType":"ok","silent":true,"durationMs":985}],"providerRequests":1,"providerRequestCarriesCompletionPrompt":true,"persistedAssistantTurns":1,"queueAfterHeartbeat":[]}

AFTER (this branch):

EVIDENCE {"case":"completion acknowledged by process poll during heartbeat preparation","backgroundExecStatus":"running","queueBeforeHeartbeat":["Exec completed (nova-com, code 0) :: SYNTHETIC_COMPLETION"],"pollDuringPreparation":{"status":"completed","aggregated":"SYNTHETIC_COMPLETION"},"queueAfterPoll":[],"heartbeatResult":{"status":"skipped","reason":"no-pending-event"},"heartbeatEvents":[{"ts":1791011941955,"status":"skipped","reason":"no-pending-event","durationMs":655}],"providerRequests":0,"providerRequestCarriesCompletionPrompt":false,"persistedAssistantTurns":0,"queueAfterHeartbeat":[]}
EVIDENCE {"case":"completion left unobserved (control)","backgroundExecStatus":"running","queueBeforeHeartbeat":["Exec completed (salty-cl, code 0) :: SYNTHETIC_COMPLETION"],"heartbeatResult":{"status":"ran","durationMs":3261},"heartbeatEvents":[{"ts":1791011946978,"status":"ok-empty","reason":"exec-event","indicatorType":"ok","silent":true,"durationMs":3261}],"providerRequests":1,"providerRequestCarriesCompletionPrompt":true,"persistedAssistantTurns":1,"queueAfterHeartbeat":[]}
Case BEFORE AFTER
Acknowledged during preparation (queueAfterPoll: [] in both) ran; 1 provider request carrying the completion prompt; 1 persisted assistant turn skipped no-pending-event; 0 provider requests; 0 persisted assistant turns
Unobserved control ran; 1 provider request carrying the completion prompt; 1 persisted assistant turn ran; 1 provider request carrying the completion prompt; 1 persisted assistant turn

Exec IDs are random per background process; each case starts a fresh one.

Build

pnpm build on the head, exit 0 (453 s wall). The Control UI budget check and the phase timings, verbatim:

verified 912 finalized Control UI sidecars
  startup JS: 8 requests, 364.7 KiB gzip (373451 B), 335.2 KiB br, 1208062 B raw (limits: 18 requests, 364.7 KiB gzip / 373454 B)
  startup CSS: 1 request, 49.5 KiB gzip (50708 B), 42.1 KiB br, 312651 B raw (limits: 1 request, advisory target 46080 B, hard ceiling 51200 B; headroom 492 B)
  warning: startup CSS gzip is above the 46080 B advisory target; remaining hard-ceiling headroom: 492 B
[build-all] phase timings: total 7m 27.8s; slowest write-unified-entry-dts 5m 34.9s; write-plugin-sdk-entry-dts 1m 0.2s; tsdown-unified 15.1s; ui:build 7.85s; check-cli-bootstrap-imports 6.99s; runtime-postbuild 5.36s; external-plugins:local-dist 4.12s; write-cli-startup-metadata (reused) 3.49s; plugins:assets:build 2.11s; plugins:assets:copy 1.63s; build-stamp 1.49s; tsdown-ai (reused) 1.45s; tsdown-packages (reused) 1.44s; check-plugin-sdk-exports 1.25s; runtime-postbuild-stamp 270ms; write-build-info 98ms; native-protocol 49ms

The startup CSS advisory warning comes from the Control UI build. This diff contains no ui/ files; I did not build main separately, so I am not claiming the warning predates this branch, only that these files cannot cause it.

Behaviour case by case

Green run on the head, node scripts/run-vitest.mjs per file:

 ✓  infra  src/infra/heartbeat-runner.exec-acknowledgement.test.ts > heartbeat preparation acknowledgement through real agent dispatch > acknowledged during preparation: true 2532ms
 ✓  infra  src/infra/heartbeat-runner.exec-acknowledgement.test.ts > heartbeat preparation acknowledgement through real agent dispatch > acknowledged during preparation: false 4437ms
 Test Files  1 passed (1)
      Tests  2 passed (2)
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > retires a stale exec event without retrying or dropping coalesced task work 10ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > passes persisted cadence through an unscoped coalesced exec wake 5ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps a scheduled turn alive when an acknowledged exec wake coalesces with it 2863ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps tagged cron work alive when an exec wake is coalesced 1814ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > retires a stale exec wake before retryable busy gates 1275ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > does not move cadence when a stale exec wake defers for min-spacing 3ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > does not record cooldown bookkeeping for an acknowledged exec wake 2ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with none work and none failure 1406ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with exec work and none failure 1824ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with exec work and delivery failure 1946ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with cadence work and none failure 1858ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with task work and none failure 1893ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps remaining cron delivery independent of consumed exec with internal 2052ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps remaining cron delivery independent of consumed exec with event-route 1943ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps remaining cron delivery independent of consumed exec with explicit-target 1880ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > rebuilds routing when an acknowledged WebChat completion leaves only cadence 1907ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > returns surviving cron work to busy guards once the admitting completion is acknowledged 1417ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps restart custody in the WebChat session when a joined completion is acknowledged 1826ms
 Test Files  1 passed (1)
      Tests  18 passed (18)

Tests

All heartbeat runner and system-events test files (30 files; the live file is excluded by the runner), pnpm test src/infra/heartbeat-runner*.test.ts src/infra/system-events.test.ts (93 s wall, exit 0):

[test] starting test/vitest/vitest.unit-fast.config.ts
 Test Files  3 passed (3)
      Tests  12 passed (12)
   Duration  6.87s (transform 78%, import 19%, tests 2%)
[test] starting test/vitest/vitest.infra.config.ts
 Test Files  26 passed (26)
      Tests  362 passed (362)
   Duration  83.04s (tests 84%, import 7%, transform 6%, setup 2%)
[test] passed 2 Vitest shards in 91.92s

Owning directory lane, pnpm test src/infra/ (687 s wall, exit 0):

[test] starting test/vitest/vitest.unit-fast.config.ts
 Test Files  181 passed | 1 skipped (182)
      Tests  2358 passed | 3 skipped (2361)
   Duration  10.86s (tests 54%, transform 25%, import 21%)
[test] starting test/vitest/vitest.unit-fast-isolated.config.ts
 Test Files  4 passed (4)
      Tests  58 passed (58)
   Duration  39.78s (tests 75%, transform 15%, import 9%)
[test] starting test/vitest/vitest.infra.config.ts
 Test Files  867 passed | 9 skipped (876)
      Tests  12761 passed | 63 skipped (12824)
   Duration  614.54s (tests 87%, import 6%, setup 5%, transform 2%)
[test] starting test/vitest/vitest.cli-process.config.ts
 Test Files  1 passed (1)
      Tests  3 passed (3)
   Duration  4.99s (transform 54%, tests 39%, setup 6%)
[test] passed 4 Vitest shards in 686.15s

An earlier run of the same lane on the same head failed one test outside this diff:

 Test Files  181 passed | 1 skipped (182)
      Tests  2358 passed | 3 skipped (2361)
 Test Files  4 passed (4)
      Tests  58 passed (58)
 FAIL   infra  src/infra/sqlite-transaction.windows.test.ts > services a held write lock across native namespace aliases of \\Server\Share\agent.sqlite
Error: database is locked
 Test Files  1 failed | 866 passed | 9 skipped (876)
      Tests  1 failed | 12760 passed | 63 skipped (12824)

That test holds a real SQLite write lock against a 100 ms busy timeout, and it fails the same way on main without this change. Interleaved in one sitting, pnpm test src/infra/sqlite-transaction.windows.test.ts:

Tree Failed runs
main 7ff3b3be3713, fresh clone 3 of 3
this head, same fresh clone 3 of 3
this head, the clone used for every other result here 3 of 3

Which of its two alias cases fails varies by run; the file passed inside the full lane above.

Regression proof (red/green)

Same tree, only the four production files reverted to main (git diff --stat against the head shows exactly those four files, 42 insertions and 194 deletions). The real-seam regression fails on the duplicate turn itself:

 ×  infra  src/infra/heartbeat-runner.exec-acknowledgement.test.ts > heartbeat preparation acknowledgement through real agent dispatch > acknowledged during preparation: true 7926ms
 ✓  infra  src/infra/heartbeat-runner.exec-acknowledgement.test.ts > heartbeat preparation acknowledgement through real agent dispatch > acknowledged during preparation: false 2548ms
AssertionError: expected { status: 'ran', …(3) } to deeply equal { status: 'skipped', …(3) }

- Expected
+ Received

  {
-   "assistantTurns": 0,
-   "providerRequests": 0,
-   "reason": "no-pending-event",
-   "status": "skipped",
+   "assistantTurns": 1,
+   "providerRequests": 1,
+   "reason": undefined,
+   "status": "ran",
  }
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > retires a stale exec event without retrying or dropping coalesced task work 11ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > passes persisted cadence through an unscoped coalesced exec wake 7ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps a scheduled turn alive when an acknowledged exec wake coalesces with it 3280ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps tagged cron work alive when an exec wake is coalesced 2225ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > retires a stale exec wake before retryable busy gates 1595ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > does not move cadence when a stale exec wake defers for min-spacing 3ms
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > does not record cooldown bookkeeping for an acknowledged exec wake 2ms
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with none work and none failure 2124ms
   → expected { status: 'failed', …(1) } to deeply equal { status: 'skipped', …(1) }
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with exec work and none failure 2116ms
   → expected 'failed' to be 'ran' // Object.is equality
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with exec work and delivery failure 2122ms
   → expected { status: 'failed', …(1) } to match object { status: 'failed', …(1) }
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with cadence work and none failure 2131ms
   → expected 'failed' to be 'ran' // Object.is equality
 ✓  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > revalidates acknowledged completions with task work and none failure 1987ms
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps remaining cron delivery independent of consumed exec with internal 2372ms
   → expected 'exec' to be 'cron' // Object.is equality
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps remaining cron delivery independent of consumed exec with event-route 2123ms
   → expected { status: 'ran', durationMs: 1389 } to match object { status: 'skipped', …(1) }
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps remaining cron delivery independent of consumed exec with explicit-target 2100ms
   → expected 'exec' to be 'cron' // Object.is equality
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > rebuilds routing when an acknowledged WebChat completion leaves only cadence 2223ms
   → expected { status: 'ran', durationMs: 1457 } to match object { status: 'skipped', …(1) }
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > returns surviving cron work to busy guards once the admitting completion is acknowledged 2179ms
   → expected { status: 'ran', durationMs: 1272 } to match object { status: 'skipped', …(1) }
 ×  infra  src/infra/heartbeat-runner.stale-exec.test.ts > stale exec heartbeat wakes > keeps restart custody in the WebChat session when a joined completion is acknowledged 2244ms
   → expected 'An async command you ran earlier has …' not to contain 'Exec completed (observed-job, code 0)…'
 Test Files  1 failed (1)
      Tests  10 failed | 8 passed (18)

Every red is an AssertionError against main's behavior, not a missing symbol: both test files import only APIs that exist on main. Where main reports failed, the reply stub rejected a prompt that still contained the acknowledged completion; for example, the first runner row's received result is:

+   "reason": "expected 'An async command you ran earlier has …' not to contain 'Exec completed (first-job, code 0) ::…'",
+   "status": "failed",

The due-task row passes in both runs by design: on main a due task already owns its prompt, so the row is a control for the revalidation's task branch rather than a regression. With the production files restored, both files pass (2/2 and 18/18).

Other checks

Check Result
pnpm check:changed --base origin/main exit 0 (683 s); 33 planned steps: conflict markers; line-cap, max-lines, assertion-safety, SQLite-worker and test-timeout ratchets; format; tsgo:core and tsgo:core:test (27 test graphs, all passed); oxlint on the 6 changed files (0 warnings, 0 errors); dead-export scan; import cycles (0); boundary and guard scripts
pnpm build exit 0 (above)
git diff --check exit 0
pnpm changed:lanes --json core, coreTests; every other lane false; extensionImpactFromCore: false

Measured test cost

pnpm test <file> --maxWorkers=1, same sitting as the evidence, on a host shared with other workloads:

# main (before this PR): node --import ./scripts/tsx.mjs scripts/test-projects.mts src/infra/heartbeat-runner.stale-exec.test.ts --maxWorkers=1
 Test Files  1 passed (1)
      Tests  7 passed (7)
   Duration  12.42s (tests 49%, transform 39%, import 10%, setup 2%)
[test] passed 1 Vitest shard in 14.05s
# this PR: node --import ./scripts/tsx.mjs scripts/test-projects.mts src/infra/heartbeat-runner.stale-exec.test.ts --maxWorkers=1
 Test Files  1 passed (1)
      Tests  18 passed (18)
   Duration  32.23s (tests 81%, transform 15%, import 4%, setup 1%)
[test] passed 1 Vitest shard in 33.79s
# this PR (new file): node --import ./scripts/tsx.mjs scripts/test-projects.mts src/infra/heartbeat-runner.exec-acknowledgement.test.ts --maxWorkers=1
 Test Files  1 passed (1)
      Tests  2 passed (2)
   Duration  25.35s (transform 66%, tests 28%, import 5%, setup 1%)
[test] passed 1 Vitest shard in 27.42s

The stale-exec file grows from about 6.1 s to about 26.1 s of test time. Each of its 11 new cases runs the real heartbeat runner against a fresh SQLite-backed session store. The sandbox fixture measured about 0.7 s per case on this host, most of it seeding the session row into a fresh state directory, and a run adds about 1 to 2 s: the same per-case cost as the file's existing runner cases. No cheaper layer proves these contracts: the defect sits between the runner's awaited routing and its dispatch, and the rebuilt selection is read from the live queue, so the runner has to execute.

The new integration file is the only test that crosses the real process poll acknowledgement and the persisted agent transcript. Its two cases take about 7.1 s; most of the rest of its duration compiles the agent and gateway import graph.

Gaps, stated plainly

  • Not reproduced on Windows or against a llama-server backend. Neither the reporter's trace nor the later completion-turn observation in the issue pins the exact poll-versus-preparation ordering; the regression reproduces the preparation window independently, through the real seam, with a loopback provider.
  • An acknowledgement that lands after the reply dispatcher starts still produces a turn (contract table). Closing that window needs a revalidation point inside the reply pipeline, which this change does not add.
  • Flags that preflight derived from the original selection (whether to inspect pending events, scratch gating, the routeless-poll skip) are not recomputed after a consumption. Main drives the turn from the same flags today.
  • The full pnpm test suite was not run. pnpm changed:lanes --json reports core and coreTests only (ui, extensions, extensionTests, apps, scripts, testRoot, docs, all false; extensionImpactFromCore: false). The owning src/infra/ lane ran in full on the head (Tests section).
  • src/infra/heartbeat-runner.live.test.ts did not run: the test runner excludes *.live.test.ts, and it needs OPENCLAW_LIVE_SESSION_EVENT_WAKE=1 plus live credentials.
  • No live channel or Gateway process was started.

- Recheck the selected event occurrences after routing, typing, and the
  dispatcher import, right before the heartbeat builds its agent turn.
- Skip with no-pending-event when an acknowledged completion was the
  wake's only work; unrelated queued events stay queued.
- Rebuild prompt, turn source, failure copy, and restart custody from the
  surviving occurrences; session publication follows surviving
  session-owned work only.
- Return preempted with an immediate retry when a consumed occurrence chose
  the route (event-owned turn source or session-owned completion) or admitted
  the wake past agent-wide busy guards, so the wake owner rebuilds both.
- Add peekSelectedSystemEventEntries for read-only revalidation and share
  shouldSkipConsumedExecWake between preflight and revalidation.
- Add a real-seam regression (background exec, process poll
  acknowledgement, heartbeat, loopback provider, persisted transcript) and
  runner-level cases for surviving work, failures, and routing.

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

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

@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The heartbeat runner rechecks selected background-command completions before starting an agent turn, skipping acknowledged results and preserving surviving work with its own routing and delivery policy.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with strong production-path evidence and meaningful survivor, routing, publication, and delivery-failure controls.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): At the pinned head, recorded macOS execution exercises the changed heartbeat owner through real exec completion, process poll acknowledgement, HTTP provider dispatch, and transcript persistence: acknowledged work produces zero requests or turns, while the unobserved control produces one. Routing and publication controls supplement that trace. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Merge readiness

✅ Ready for maintainer review

This remains a useful fix absent from current main and the latest release. No blocking correctness or security findings remain, the recorded runtime proof is sufficient, and the previous draft blocker is resolved.

Priority: P2
Reviewed head: 718bf16e701e01c2d3cc4cc916c5ee367f1828de

Before merge

None.

Findings

None.

Agent review details

How this fits together

Heartbeats turn queued command completions and scheduled work into agent requests. Process polling can acknowledge a completion while heartbeat routing awaits, so the runner must check its selection again before dispatch.

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 -->|No work remains| F[Skip turn]
  E -->|Admission or route changed| G[Retry preparation]
  E -->|Work survives| H[Agent turn and delivery]
Loading

Technical review

Best possible solution:

Keep acknowledgement with the process owner and revalidate exact event occurrences at the heartbeat dispatch boundary, preserving independent work and successful-delivery consumption.

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

Yes: acknowledge a selected completion through process poll while heartbeat routing awaits, then resume dispatch. Current-main source retains the stale snapshot, and the contributor records a failing before-fix run; this review did not execute target code.

Is this the best way to solve the issue?

Yes for the demonstrated preparation window: checking occurrence identities at the heartbeat owner is narrower than delaying notifications and reuses the existing retry owner when admission or routing changes.

AGENTS.md: found and applied where relevant.

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

Security

None.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head delta. The verified test merge has the pinned base followed by the exact PR head as its raw parents; its result contains the same six introduced paths. (718bf16e701e)
  • Current-main necessity: The four production files are unchanged between the pinned merge base and fetched main. Current main awaits preparation and typing, then dispatches the prepared prompt without the new occurrence recheck. (src/infra/heartbeat-runner-run.ts:77, 3f3bbcfea0b1)
  • Latest-release comparison: Read the v2026.9.8 file through GitHub's contents API: it also builds the heartbeat context immediately after typing without revalidating selected completion occurrences. Local inspection of the release blob failed because its object could not be fetched; the pinned GitHub read supplied the comparison. (src/infra/heartbeat-runner-run.ts:77, fc23bc864e45)
  • Recorded production-path proof: The full PR body matches captured SHA-256 f7da5270b0c731626033ce69d77377f7058af33ca78f904c03c848a95da5c00f (25,273 UTF-16 units). Its macOS/Node trace exercises real background exec, process poll acknowledgement, heartbeat/reply/agent dispatch, loopback HTTP provider requests, and persisted transcripts. Before the fix the acknowledged case produces one request and assistant turn; afterward it produces zero. The unobserved control produces one in both runs. The committed harness explicitly selects the OpenClaw runtime. (src/infra/heartbeat-runner.exec-acknowledgement.test.ts:95, 718bf16e701e)
  • Selection and final-effect safeguards: Revalidation retains queue-owned occurrence identities, removes session publication eligibility when session-owned work disappears, and retries when consumed work supplied admission or routing. Supplemental regressions observe no channel send or session publication for inappropriate survivors, preserve failed-delivery events, and verify restart continuation publication. Existing publication still checks session generation and writer ownership at its transaction boundary. (src/infra/heartbeat-runner-execution.ts:686, 718bf16e701e)
  • Related work and maintainer clarification: [Bug]: regression race after #120575: terminal process.poll can still trigger duplicate notifyOnExit wake #141202 tracks the ordinary-completion race. Its MEMBER comment by VACInc explicitly distinguishes the merged cancellation repair from snapshot revalidation. fix: avoid duplicate agent turns for acknowledged completions #141352 remains an overlapping open candidate with production-path proof; this PR credits and builds on that work. Neither is a merged fixing PR that would make this contribution obsolete.

PR surface

Source +152, Tests +565. Total +717 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 4 194 42 +152
Tests 2 566 1 +565
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 760 43 +717

Review metrics

Metric Value Why it matters
Regression execution cost Reported standalone wall time: stale-exec 14.05s → 33.79s; new integration 27.42s The body measures and explains the added cost of runner-level controls and real process-to-transcript coverage.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #141202
Summary: This PR addresses the independently reproduced preparation-time acknowledgement race tracked by the canonical issue.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The bounded acknowledgement race wastes agent computation and can repeat expensive long-context inference.
  • 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.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (1 earlier review cycle)
  • reviewed 2026-10-03T08:02:47.964Z sha 718bf16 :: needs changes before merge. :: none

Reviewed October 3, 2026, 4:10 AM ET / 08:10 UTC (Revision 2).

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: 🐚 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.

[Bug]: regression race after #120575: terminal process.poll can still trigger duplicate notifyOnExit wake

1 participant