Repository navigation
Conversation
- 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]>
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThe 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
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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherHeartbeats 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]
Technical reviewBest 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. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +152, Tests +565. Total +717 across 6 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. LabelsLabel changes: No label changes. Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed October 3, 2026, 4:10 AM ET / 08:10 UTC (Revision 2). |
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
execqueues one completion event with a one-use receipt and requests anexec-eventheartbeat wake. Reading the result withprocess pollremoves 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.mdprescribes 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/ownerturn source, or the session-owned completion route of an internal WebChat session). When a consumed occurrence made either decision, the runner returns the existing retryablepreemptedresult 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
no-pending-event; no agent turn; unrelated queued events stay queuedexecturn with only the survivor in the prompt; survivor consumed after successfailed; survivor stays queuedheartbeatturnpreempted, retry due at once; the retry runs the busy guards (requests-in-flightwhile the main lane is busy)last/ownerroutepreempted, retry due at once; the retry sends the surviving cron event to its own destinationpreempted, retry due at once; the retry delivers the cadence turn to the configured targetcronturn; the reply is not published into the sessionEvidence
Provenance: Mac Studio (macOS 27.0, arm64), Node 24.21.0, head
718bf16e701eon main7ff3b3be3713, 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 backgroundexec, waits for its completion event, and runsrunHeartbeatOncethrough 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 realprocesspoll 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):
AFTER (this branch):
queueAfterPoll: []in both)no-pending-event; 0 provider requests; 0 persisted assistant turnsExec IDs are random per background process; each case starts a fresh one.
Build
pnpm buildon the head, exit 0 (453 s wall). The Control UI budget check and the phase timings, verbatim: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.mjsper file: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):Owning directory lane,
pnpm test src/infra/(687 s wall, exit 0):An earlier run of the same lane on the same head failed one test outside this diff:
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:7ff3b3be3713, fresh cloneWhich 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 --statagainst the head shows exactly those four files, 42 insertions and 194 deletions). The real-seam regression fails on the duplicate turn itself:Every red is an
AssertionErroragainst main's behavior, not a missing symbol: both test files import only APIs that exist on main. Where main reportsfailed, the reply stub rejected a prompt that still contained the acknowledged completion; for example, the first runner row's received result is: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
pnpm check:changed --base origin/maintsgo:coreandtsgo: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 scriptspnpm buildgit diff --checkpnpm changed:lanes --jsoncore,coreTests; every other lane false;extensionImpactFromCore: falseMeasured test cost
pnpm test <file> --maxWorkers=1, same sitting as the evidence, on a host shared with other workloads: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
processpoll 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
pnpm testsuite was not run.pnpm changed:lanes --jsonreportscoreandcoreTestsonly (ui,extensions,extensionTests,apps,scripts,testRoot,docs,allfalse;extensionImpactFromCore: false). The owningsrc/infra/lane ran in full on the head (Tests section).src/infra/heartbeat-runner.live.test.tsdid not run: the test runner excludes*.live.test.ts, and it needsOPENCLAW_LIVE_SESSION_EVENT_WAKE=1plus live credentials.