Repository navigation
fix(cron): sessions_send fails after current automation runs - #161085
Conversation
|
🦞👀 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: blocked before merge. Reviewed September 30, 2026, 2:24 AM ET / 06:24 UTC (Revision 12). ClawSweeper reviewWhat this changesThe branch admits follow-up messages to a current automation’s local detached run, cancels stale cron-root work, and updates runner code, hook handling, documentation, snapshots, and regression tests. Merge readiness⛔ Blocked before merge - 1 item remains Current main still rejects the reported stable cron key against an exact-run placement. This PR remains a viable fix, and its current-head Gateway proof addresses the in-flight hook effect gap from the prior review. The overlapping fix PR is open and unmerged. Priority: P1 Review scores
Verification
How this fits togetherCron records a detached run under a stable job key and an exact run key. Follow-up messages pass through Gateway placement admission before agent hooks, execution, and transcript writes. flowchart LR
A[Scheduled automation] --> B[Detached run]
B --> C[Stable and exact keys]
C --> D[Gateway placement admission]
D --> E[Run and hook authority]
E --> F[Provider or CLI effect]
E --> G[Run transcript]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +180, Tests +1647, Docs 0. Total +1827 across 39 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Land one verified local cron-alias admission rule while preserving stored placement identity and fencing stale hooks, provider requests, child effects, and transcript writes; then resolve the overlapping candidate. Do we have a high-confidence way to reproduce the issue? Yes. Current main’s exact placement-key comparison and the reported stable-key/exact-run rows establish a concrete failing path; this read-only review did not execute main. Is this the best way to solve the issue? Yes. Local placement admission is the narrow owner for the reported mismatch, and the branch keeps the exact stored claim identity while fencing reassigned roots. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 076ae3e01b96. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (11 earlier review cycles; latest 8 shown)
|
|
Merged via squash.
|
…d pass (#161737) Third-pass maintainer-requested Gateway cleanup following #159752 and #161284. Reuse canonical validation, stable bounded sorting and placement matching; consolidate RPC and workspace projections and remove forwarding wrappers. Preserve protocol, RPC results and errors, live-owner authority, worker lifecycle/fencing and persisted state. No user-visible behavior change is intended. Drop overlaps already landed in #160444, #161085 and #161642. Validation: independent Codex review clean at P0-P2; both import-cycle checks report zero; lint clean; 401 tests passed across 28 files and five Vitest shards, with one existing opt-in Podman skip. Rebased protocol generation has zero drift and SDK export/surface checks pass. Full source reading covered 645 production files at the starting base. Hosted CI run 36693161484 executed its build/test lanes. The sole failed test, session-activity-summaries.test.ts relocated-store recovery (expected 2 to be 3), also fails on unrelated PR #161714 head 8080a45, run 36692028664 job 109811633901. The changed RPC/workspace code is outside the failing execution path. Land under the explicitly authorized pre-existing-failure exception; retain this failure for the main-CI coordinator.
…w#161085) Allow sessions_send to address a current automation's stable cron key while claiming its recorded exact-run placement. Preserve the detached run's session identity and workspace, with replies recorded in its own transcript. Retain cron-root authority before reply hooks and through embedded and CLI execution. Reassignment aborts active work and fences hook effects, provider dispatch, and transcript writes. Ordinary sessions and exact-run keys keep their existing behavior. No persisted shape or migration changes. Validated with real-Gateway allowed/stale/fresh controls, a registered-plugin hook-revocation proof, real CLI-child cancellation, focused regression suites, independent Codex review, and successful exact-head CI run 36677514872. ClawSweeper revision 12 found no code or security findings; the PR records data-model compatibility evidence and the maintainer-approved production-LOC exception.
…d pass (openclaw#161737) Third-pass maintainer-requested Gateway cleanup following openclaw#159752 and openclaw#161284. Reuse canonical validation, stable bounded sorting and placement matching; consolidate RPC and workspace projections and remove forwarding wrappers. Preserve protocol, RPC results and errors, live-owner authority, worker lifecycle/fencing and persisted state. No user-visible behavior change is intended. Drop overlaps already landed in openclaw#160444, openclaw#161085 and openclaw#161642. Validation: independent Codex review clean at P0-P2; both import-cycle checks report zero; lint clean; 401 tests passed across 28 files and five Vitest shards, with one existing opt-in Podman skip. Rebased protocol generation has zero drift and SDK export/surface checks pass. Full source reading covered 645 production files at the starting base. Hosted CI run 36693161484 executed its build/test lanes. The sole failed test, session-activity-summaries.test.ts relocated-store recovery (expected 2 to be 3), also fails on unrelated PR openclaw#161714 head 8080a45, run 36692028664 job 109811633901. The changed RPC/workspace code is outside the failing execution path. Land under the explicitly authorized pre-existing-failure exception; retain this failure for the main-CI coordinator.
What Problem This Solves
Fixes
sessions_sendfailing with “Worker turn session key does not match its placement” when addressing acurrentautomation's cron session after a scheduled run. It also retains cron-root authority before reply hooks and through active embedded/CLI work, so a reassigned root cannot continue through the old run's hook or execution authority.User Impact
Follow-up messages reach the latest detached cron run, which keeps its own session identity and scheduled agent workspace. It does not inherit the bound conversation's cloud worker placement. Inbound replies belong in the cron run transcript; the scheduler's
currentcompletion mirror remains unchanged.Running turns addressed through a stable cron key stop when that key loses its admitted generation. Ordinary sessions and exact cron-run keys retain their existing behavior. No configuration or PR-specific data migration is required.
Why This Change Was Made
Cron already allocates a fresh detached session ID. The stable job key and exact
:run:key share that ID, but placement records use the exact key. Local admission now recognizes the root for its recorded run while retaining the caller's root for session-row checks and the stored exact-run key for claims. Unrelated jobs, agents, reverse aliases, sibling runs, ordinary sessions, and remote placements retain their identity checks.prepareCronRootSessionGenerationis the single owner of root selection and admitted generation facts. Both runners retain its checks through final I/O and transcript settlement. Embedded attempts bind revocation to their abort controller and the shared provider-stream boundary. CLI attempts now also connect its existing revocation callback to the signal passed to the backend. The existing supervisor cancels the active child and joins its termination. Caller and operator-model cancellation signals remain composed; ordinary runs keep their original signal.The CLI repair adds no new manager, process mechanism, or transport patch. A redundant local dependency binding was removed through an import alias to retain the existing file-size limit. Docs and model-facing automation text explain cancellation on stable-key reassignment; snapshots are regenerated.
Evidence
Hook revocation proof
Current proof commit:
b3bb9ea69e191; main merge:b91390eaac781. The committed tree exactly matches the reviewed/tested candidate. This addresses ClawSweeper revision 11's uncertainty about effects after mid-hook revocation.Extended the existing gated real-Gateway proof with a registered external test plugin, real cron/session stores, the embedded runner, and the public SDK guarded HTTP transport. There is no injected Gateway caller, hook runner, generation lease, or agent executor. The plugin has the documented conversation-hook grant only inside the isolated fixture.
The hook waits on a deferred HTTP response before its final outbound POST. The allowed control returns
handled: true, and the receiver's response becomes the visible terminal reply. For the revoked control, a forced scheduled run replaces the stable cron root while the hook is pending; only then does the test release it. The test separately joins the hook's ownfinallybefore checking the effect receiver, so an earlyagent.waiterror cannot hide later I/O. Production model-call observations are calibrated by the fixture's successful real-model cron and agent turns.The expanded production-path proof passed in 67.59s wall. Existing allowed/stale/fresh cron routing also passed. No production change was needed for the reviewed uncertainty: the existing retained generation and guarded-request scope prevent the final effect. No real timers, sleeps, retries, or timeout increases were added to the hook regression; it shares the existing isolated Gateway and uses deferred synchronization.
Fixture bring-up initially lacked the documented non-bundled conversation-hook grant, then exposed separate startup/request-scoped plugin module instances. The fixture now uses the existing process-wide observation-owner pattern and explicitly joins completion. These setup failures were not counted as authority proof; no assertion was loosened.
Counterfactual proof retained all post-hook generation checks but temporarily omitted only the assertion supplied to
withGuardedFetchRequestAuthority. The same real-Gateway regression then failed in 58.26s wall:The stale hook had emitted one real HTTP POST before the later error settlement. The production file was restored byte-for-byte, verified with an empty file diff, and the runtime rebuilt with guards enabled (61.05s). This establishes that the new regression detects the final-effect gap rather than merely observing a later rejected result.
Current main integration
Merged
origin/mainat25a42ef9feeeb. Only three generated prompt fixtures conflicted; source and lockfile merged cleanly, so no reinstall was needed. Each conflict was resolved through the snapshot generator after temporarily selecting one side:telegram-direct-codex-message-tool.md: regenerated the canonical prompt from merged source, preserving both sides' behavior.discord-group-codex-message-tool.md.diff: regenerated its delta against the merged canonical prompt.telegram-heartbeat-codex-tool.md.diff: regenerated its delta against the merged canonical prompt.pnpm prompt:snapshots:genregenerated all seven owned outputs in 35.93s. The merge also includes main's requester-settlement/continuation fixes. Prior CI36669229885failed only in the untouched Codex settlement test,settles timeout at final with writer release after cutoff, at 120 seconds. Main fixed that fixture in52e60fb42bc3eby giving the rotated successor thread a fresh identity; the exact file passed once on the merged tree, as recorded below.All repository tooling used
TMPDIR=/private/tmp/oc-cp. Live auth staging uses a fresh empty state directory beneath it, and the task env is sourced only inside the live-test shell. Autoreview uses the macOS private temporary directory withTMPandTEMPunset. No operator Gateway/state is used.Current-round gates and scope
All tests/repository tooling used
TMPDIR=/private/tmp/oc-cp; each live/build run used fresh empty state. Task credentials were sourced only in the live-test shell. Autoreview uses the macOS private temporary directory withTMP/TEMPunset.The inherited Codex file passed 7/7 cases, 41.31s shard duration;
settles timeout at final with writer release after cutofftook 2.529s, confirming main's named fixture fix on the merged tree. No timeout was changed here.Authored scope for this follow-up: production +0/-0; tests/support +215/-0. The existing live test gains 83 lines, its registered-plugin/HTTP fixture adds 132 lines, and the merge commits regenerated snapshot outputs. The hook controls add no normal per-PR test runtime because they remain in the existing gated live suite. Normal CI timing is pending publication. Prior-round production LOC exception and data-model compatibility evidence remain below.
Prior round: early hook authority
The follow-up closes the pre-execution hook gap in both runners. CLI acquires the existing stable-root generation lease before
before_agent_reply, retaining it through handled returns and normal execution. Embedded acquires a setup lease before reply/model-selection hooks; the attempt loop asserts and releases it immediately before the existing attempt lease takes over. Handled returns and setup failures dispose the setup lease. Compaction and plugin-runtime refresh retain their existing successor handoff.The private core hook-admission capability carries asynchronous preparation separately from its synchronous current-authority assertion. Existing internal callers were migrated together. The shared hook dispatcher checks current authority immediately before and after each handler. A root-only guarded-request scope covers reply-hook dispatch and observer finalization, including delayed guarded network effects; initial model-selection hooks receive the same scope and cannot swallow revocation through their normal plugin-error catch. Ordinary sessions receive no new generation/request guard. No public plugin hook signature or persisted field changes.
New runner-boundary regressions use real SQLite session rows. Both runners allow a handled hook while the lease is held, revoke retained handles after completion, and suppress a hook whose root was reassigned during admission. Ordinary-session controls have no new authority. Additional tests reject revoked handler results, suppress subsequent handlers/finalizer effects, and prevent a model-selection hook's fail-open catch from continuing a revoked run.
Before the production repair, both stale-root runner regressions failed for the intended reason:
Embedded red command: 71.13s wall / 33.11s Vitest. CLI red command: 40.46s wall / 34.76s Vitest; the ordinary control passed. The first full green hook/sibling run passed 156 cases in 239.53s wall.
Main
1eaef188e49b5bc5183eba3231e47f9b7da515d1was integrated in merge commitadd180eea1833; the hook repair isa5b19a6122f78. The committed tree exactly matches the reviewed/tested candidate. The merge had no conflicts and did not change the lockfile. The orchestrator's line-limit finding was resolved by placing setup-to-attempt handoff in the attempt loop and removing a redundant argument copy; no guard/baseline was changed.Final hook-repair gates passed on the reviewed source:
agents-root,agents-other,plugins-platform) 110.25s.qaRuntimebuild 96.55s, guards enabled, fresh isolated build state.git diff --check0.38s / 1.45s.Active CLI cancellation: real process proof
src/agents/cli-runner.cron-root-abort.test.tsretains real CLI preparation, execution, supervisor, and SQLite publication. A registered fixture backend starts a real Node child. A claimed loopback READY/GO protocol holds it before a file-write effect. A call-through preparation spy observes the real signal; it does not replace execution, generation, or process behavior.Before the callback/signal repair, the child started and actual root reassignment left its signal live. The regression failed at the intended assertion, 230.84s wall / 40.676s case:
node scripts/run-vitest.mjs src/agents/cli-runner.cron-root-abort.test.ts --maxWorkers=1 -t 'reassigned root'Standalone green: 3 passed, 279.25s wall. The final combined run after mechanical lint corrections passed 61 cases, 482.89s wall: placement 1, CLI authority 6, embedded/Bedrock 31, CLI settlement 23. Final real-child case costs: 9.376s allowed / 3.210s reassigned / 2.800s ordinary. Worker compilation/imports dominate wall time; actual process cancellation is the contract that a signal-only mock cannot prove. No sleeps, polling, timeout extension, broader mocks, or weakened assertions were added.
The final Bedrock cases passed: 5.241s allowed / 0.720s rotated / 1.035s ordinary. They use the public provider entry and real transport preparation with only the SDK send boundary substituted. Rotation during awaited payload preparation aborts the attempt, issues zero SDK requests, and rejects the transcript append. Allowed/ordinary controls issue one request and persist the decoded assistant reply. The original counterfactual failed with
expected "send" to not be called at all, but actually been called 1 times(297.36s wall).Prior-head main integration and gates
Merged main
70068329e5113in5b70a03855e6; CLI repair commit is77e9d98ef576b. No lockfile change, so no dependency reinstall was required. Source merged cleanly. Four generated conflicts were resolved through the snapshot generator:codex-dynamic-tools.telegram-direct.json: regenerated tool metadata from merged source, preserving main's tool changes and the current-session contract.telegram-direct-codex-message-tool.md: regenerated the canonical prompt with both sides' source behavior.discord-group-codex-message-tool.md.diff: regenerated the delta against the merged canonical prompt.telegram-heartbeat-codex-tool.md.diff: regenerated the delta against the merged canonical prompt.Prior-head gates passed:
agents-root): 141.61s, compiler portion 15.4s.git diff --check: 1.54s; staged diff check also passed.qaRuntimebuild on the committed head: 101.45s, publication/bootstrap guards enabled, supportedOPENCLAW_BUILD_ALL_NO_PNPM=1route.The known shared package-manager pre-command lock was avoided through the exact scripts owned by
package.json; no shared lock was recovered or altered:node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo node scripts/run-tsgo-core-test-shards.mjs --changed-paths-json '["src/agents/cli-runner.cron-root-abort.test.ts"]' node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/agents/cli-runner.ts src/agents/cli-runner.cron-root-abort.test.ts src/agents/tools/cron-tool.ts node --import ./scripts/tsx.mjs scripts/generate-prompt-snapshots.ts --write node --import ./scripts/tsx.mjs scripts/generate-prompt-snapshots.ts --checkReal Gateway proof
Prior-head real-Gateway proof passed on
a5b19a6122f78: 1 passed, 102.54s wall / 89.82s Vitest / 60.085s case. This was the one authorized retry on the freshly built committed runtime, with real model execution, production Gateway routing, and fresh isolated state. Gateway cleanup passed; task-owned auth staging was removed after the test process exited. No timeout or assertion changed.The live trace confirms production routing remains intact after the early-hook repair. Real SQLite hook regressions above separately prove the hook-specific held/revoked authority contract.
Prior-head real-Gateway proof passed on
77e9d98ef576b: 1 passed, 79.35s wall / 70.54s Vitest duration. This was the single authorized retry, using the freshly built runtime, realopenai/gpt-5.6-luna, production Gateway/cron/session routing, and a fresh empty state directory. Gateway and auth staging cleanup completed. No timeout, assertion, or harness behavior was changed.This production-routing proof complements the new real-child CLI cancellation test and native Bedrock boundary test above. It does not substitute a mocked Gateway or synthetic agent execution.
Retained prior-head production proof on
2ebda4fc359b: 1 passed, 44.40s wall / 30.766s case, using realopenai/gpt-5.6-luna, an isolated Gateway, authenticatedagentRPCs, and production cron/session routing. No injected Gateway caller or synthetic model execution:Source authority chain: root sends resolve the current session row; placement lookup uses that admitted session ID. A fresh send after reassignment selects the new run.
expectedExistingSessionIdrejects stale pins before execution. Writer admission checks ID/revision, retained generation facts fence final effects, and revocation now cancels both embedded and CLI attempts. An old exact-run transcript's continued existence does not authorize a root-addressed write to it after reassignment.Data model and upgrade compatibility
No persisted shape changed in this PR. This follow-up adds only a gated live-test fixture and regenerates prompt snapshots after merging main; it adds no production code or stored field. Auditing the PR diff against integrated main
1eaef188e49b5found zero persisted-type, schema, codec, or store files changed. Dedicated in-memory type/capability modules touched aresrc/agents/embedded-agent-runner/run/attempt-execution-types.ts(theassertCronRootCurrentattempt callback),src/agents/embedded-agent-runner/run/execution-context.ts(the setup-phase generation lease), andsrc/plugins/hook-claim-admission.ts(private host preparation/assertion functions). None is a serializer or durable record.src/config/sessions/session-delivery-generation.tsretains{ agentId, storePath, sessionKey, sessionId, lifecycleRevision }as in-memory attempt state, together with release callbacks, publication observations, and the attempt's abort controller. These facts are read from existing owner-held state; no new field is serialized.src/gateway/worker-environments/worker-turn-admission.tschanges admission to an existing durable operation: it recognizes the local cron root in memory, retains the addressed root for session-row checks, then passes the placement's already-stored exact-runsessionKeytoclaimTurn. The unchangedplacement-row-codec.tsensureLocal/assertIdentitypath verifies that identity. The unchangedplacement-turn-claims.tstransaction updates only existingturn_claim_owner,turn_claim_id,turn_claim_run_id,turn_claim_generation,turn_claim_owner_epoch, andupdated_at_msfields. It does not rewrite the placement'ssession_keyor persist an alias.File-level evidence:
src/gateway/worker-environments/placement-record.ts,placement-row-codec.ts,placement-store.ts,placement-turn-claims.ts, andplacement-turn-claims-store.ts.src/config/sessions/types.ts,src/config/sessions/session-delivery-generation.types.ts, the session SQLite entry/transcript owners,src/cron/types.ts, andsrc/cron/store.ts.src/state/**file changes in the PR, includingopenclaw-state-schema.sql,openclaw-state-db.generated.d.ts, schema versions, and migrations.v2026.9.6Git tag with this candidate: the completeworker_session_placementsSQL table definition,WorkerSessionPlacementsgenerated interface,PersistedTurnClaimunion, andparseTurnClaimcodec are byte-identical. They also match integrated main70068329e5113.The record retains its existing identity (
sessionId,agentId,sessionKey), state and ownership (state,executionMode,generation,environmentId,activeOwnerEpoch), workspace references, acknowledgement cursors, recovery/terminal fields, timestamps, and nullable turn claim. All 24 persisted columns were checked:active_owner_epoch,agent_id,created_at_ms,environment_id,execution_mode,last_live_event_ack_cursor,last_transcript_ack_cursor,recovery_error,remote_workspace_dir,session_id,session_key,state,state_changed_at_ms,terminal_at_ms,terminal_reason,transition_generation,turn_claim_generation,turn_claim_id,turn_claim_owner,turn_claim_owner_epoch,turn_claim_run_id,updated_at_ms,worker_bundle_hash, andworkspace_base_manifest_ref.SessionEntryCore.sessionIdand optionallifecycleRevisionalready exist inv2026.9.6; absent revisions retain the existingnullnormalization. Therefore, a Gateway upgraded from 2026.9.6 with pending cron placements/session rows needs no migration or backfill for this PR. Existing rows retain their exact-run identities and use the same codecs. Existing restart/claim revocation rules remain in force. This is a PR-specific compatibility statement; unrelated migrations supplied by newer main still run through the normal upgrade owner. No old-row/new-row transformation test is needed because this PR adds or changes no persisted field.Retained regression evidence and limits
The original placement regression failed with expected
status: "accepted", receivedstatus: "error", andWorker turn session key does not match its placement(371.36s). Before generation fencing, rotation/reset cases resolved instead of rejecting. Before scope narrowing, ordinary/exact-run controls incorrectly acquired request authority. Those counterfactuals and the current sibling passes protect the original routing and scope contracts.The previous main-integration round passed all three named inherited CI regressions and 223 distinct cases across focused runs. Its first placement invocation timed out at 120s; an instrumented diagnostic replay passed in 33.277s without assertion/timeout changes. The current uninstrumented placement test passes in 22.023s. No production fix is claimed for that earlier timing incident. Earlier live attempts failed in pre-auth WebSocket handshake before cron work; their results are not claimed as live passes.
Production LOC: +179 net (375 additions / 196 deletions against integrated main
1eaef188e49b5, excluding tests/support/live files); the maintainer accepted the LOC exception. The hook follow-up adds 85 net production lines, including extraction of the existing CLI handled-hook result path to keep orchestration bounded. No broad changed-scope wrapper was rerun; the requested focused/core lanes above were completed. Cloud-worker live execution and a real AWS Bedrock request were not exercised. Current-head CI and ClawSweeper review remain publication gates; no PR merge is part of this update.Prior-head CI status
ClawSweeper exact-head review
36664615291started at 03:29:20 UTC, less than two minutes after the push; no manual re-review comment was needed.CI run
36664491772failed in preflight's Build CI manifest step before project checks or test shards started:Failed preflight job. The PR-only diff against integrated main changes neither
.githubnor the named manifest paths. This was a CI-harness blocker on that prior head; no project-test failure was reported by that run. Integrated main supplies the previously missing manifest script. Exact-head CI and ClawSweeper review for the new hook repair are pending publication. No workflow/guard workaround or CI rerun was performed. The PR remains open; it has not been merged.