Skip to content

fix(gateway): keep slow worker operations from blocking unrelated sessions - #160299

Merged
steipete merged 6 commits into
mainfrom
codex/placement-session-admission
Sep 28, 2026
Merged

steipete merged 6 commits into
mainfrom
codex/placement-session-admission

Conversation

@steipete

@steipete steipete commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Related: #159881

What Problem This Solves

Fixes unrelated session dispatch and Stop waiting behind slow cloud-worker reconciliation, Move, provisioning recovery, or forced teardown. In an isolated Gateway on September 27, four Crabbox environments repeatedly failing teardown kept sweeps busy: two dispatches to a local paired device took 818 seconds and 554 seconds with the Gateway idle, and Stop waited 3.7 minutes before draining.

User Impact

Independent sessions can dispatch, move, and stop while another session's provider work remains stuck. Operations affecting the same session preserve their order, and Stop begins cancellation and drain preparation immediately.

Update behavior: process-local ordering only; no persisted-state, schema, configuration, protocol, or dependency change.

Why This Change Was Made

The coordinator owns one queue per session. Dispatch and Move capture earlier Stops before entering session admission. Stop prepares cancellation and turn-claim drain outside the queue, then admits only entered cleanup. Provisioning recovery retains admission until provider settlement, even after foreground timeout. Forced teardown reserves attached and live lifecycle owners synchronously and waits for those predecessors before destruction. After worker-backed durable discovery, it atomically reserves only additional idle owners, checking both queued work and live lifecycle operations. Busy durable-only owners are skipped; phase 2 never waits while holding phase 1. All acquired reservations remain held through settlement.

Environment reconciliation runs outside session admission. Full/startup recovery skips busy sessions, targeted recovery waits for queued entries, and every admitted unit reads fresh state. Recovery units remain separate from lifecycle tracking so they do not invalidate initial-placement waiters. Orphan cleanup tries all known sessions sharing each workspace root and retries skipped roots on the next full sweep.

The global placement fence, dispatch-idle bookkeeping, dispatch cohorts, and sweep recovery-join machinery are removed.

Follow-up: recovery units run sequentially; bounded concurrency is a separate change.

Known limitation (pre-existing)

An admitted lifecycle operation—Move or dispatch's local barrier—that waits for turn-claim release can wait until its drain timeout when releasing that claim depends on same-session targeted recovery. On main, the global exclusive fence blocks every session and sweep during that wait. This change confines the wait to the affected session. Stop performs preparation outside admission, allowing targeted recovery to release its turn claim.

Follow-up: perform the turn-claim drain before entering session admission.

Evidence

September 28 forced-destroy deadlock and recovery contract cycle

Candidate: 22b8fb463fa0622e4a3ddba0920f443165afc54b; merge-base: 465fdd5adba67a2b8cef72fcc8c7fd688b7c9967.

Forced destruction no longer waits for additional durable owners while holding its initial session reservations. Phase 1 still synchronously reserves attached/live owners at call time and waits before service destruction. After durable discovery, phase 2 checks both queued work and live lifecycle operations synchronously, reserves only idle additional owners, and never waits on a phase-2 key. Acquired reservations remain held through settlement.

This removes the cycle where D1 holds A, B becomes attached, D2 reserves A and B behind D1, and D1 discovers B behind D2. A skipped durable-only owner had no attachment or live lifecycle operation targeting this environment at call time. Intervening lifecycle writes retain CAS guards and environment/workspace locks; overlapping destroys retain shared phase-1 ordering. Removed the previous pre-discovery phase-1 wait because it existed only to support phase-2 waiting. Retained the wait before the service call and the fixed-owner overlap test because they protect actual call-order contracts. Lifecycle docs describe the corrected ordering.

The separate cycle fix moves WorkerPlacementRecoveryAdmission into the existing type-only placement-recovery-contract.ts leaf beside PlacementRecoveryDeps. Recovery and orphan cleanup import it directly there. The recovery implementation no longer exports it, and no re-export shim remains. This fixes the architecture failure reported by CI run 36419759684. No update, persistence, schema, protocol, or dependency behavior changed.

GitHub reported a merge conflict before publication, so the branch was rebased onto the base above. The terminal-results fixture retains main's createWorkerTurnTunnel/acknowledgeCompletedWorkerTurn helpers and this branch's targeted-recovery/Stop assertions. Main's active-placement fixture extraction auto-merged. All PR production files are byte-identical before/after rebase; at rebase, the four existing follow-up commits were unchanged in range-diff.

The three task commits remain separate, with Peter Steinberger as author and committer:

  • 8ba2cfcf9e6a812143a84ecba36c435c90e94888: forced-destroy deadlock repair.
  • 0d8bb389a73468ff3d61c7f565c51b4440b58623: recovery admission contract leaf.
  • 22b8fb463fa0622e4a3ddba0920f443165afc54b: adapt test spies to main's harness method snapshots.

The exact owner-growth negative control used original production head 310ed33309d2, deferred fakes, and --testTimeout 1000 only on the command line. No sleeps or timers were added:

Before:
  settles overlapping destroys when attached owners grow=true
  Test timed out in 1000ms.
  Test Files  1 failed (1)
       Tests  1 failed | 8 skipped (9)
  Command wall: 4.94 s

After (same 1000 ms CLI bound, complete forced-destroy file):
  Test Files  1 passed (1)
       Tests  9 passed (9)
  Command wall: 4.08 s

Coverage verifies D1's service call precedes D2, a B dispatch issued after D2 follows it, idle durable owners hold later same-session work, and busy queued recovery or Stop preparation can proceed independently of destruction. The rebased broad run also passed all nine forced-destroy cases.

Validation:

  • Before rebase, the full requested union passed 48 files / 643 tests, 485.09 s command wall.
  • After rebase, the expanded union also included worker-turn-launcher-terminal-results.test.ts: 47 files passed / 2 failed; 655 tests passed / 4 failed, 1128.54 s command wall. These failures were deterministic fixture integration defects: main's harness now copies store methods, so spies installed afterward no longer intercept the service. That bypassed candidate-list injection and claim-call observation, and left Stop waiting for a read hook that could never run. The whole Stop file reproduced the same 120 s timeout in its original test order (12 passed / 1 failed, 485.99 s command wall).
  • The separate fixture commit installs spies before harness construction, retains bound originals, and arms deferred behavior at the original observation boundary. No production code, assertion, timeout, or main harness implementation changed. After the repair, the complete affected files passed 13/13 Stop tests and 10/10 recovery-admission tests, including all four failures. The previously hung Stop case passed in 5.375 s. The other 47 files' passing evidence is reused; the complete 49-file invocation was not repeated after this test-only correction.
  • pnpm tsgo:core passed after rebase (24.45 s). All four Gateway core-test graphs passed after rebase (63.12 s) and again after the fixture repair (21.00 s).
  • Madge reproduced 1 cycle before the contract move, then 0 cycles afterward. The full rebased pnpm check:architecture passed, exit 0, 1507.27 s command wall: 0 runtime value cycles, 0 Madge cycles, and passing deprecated API/JSDoc, wrapper shadowing, generated Kysely types, Kysely guardrails, and database-first legacy-store checks. The later fixture correction changes no imports or production code.
  • Pre-rebase node scripts/check-changed.mjs passed all 26 core test graphs, formatting, ratchets, boundaries, and three dead-export scans, then reported the known UI max-lines error (713/700) plus one new fixture shadowing error. Renaming that fixture function fixed the latter; targeted type-aware lint passed. The UI file was not edited by this PR; main subsequently changed it during rebase. The aggregate command was not repeated after rebase. Final targeted type-aware lint passed for the merged fixtures and contract consumers (53.18 s) and the repaired spy fixtures (57.38 s).
  • Formatting and git diff --check passed for the complete branch diff.
  • Independent Codex autoreview: branch mode, base 465fdd5adba67a2b8cef72fcc8c7fd688b7c9967, high reasoning, fast service, P2: scoped-clean, no accepted/actionable findings. Unchanged lifecycle owners and main's fixture helpers were supplied as context. Each new local correction also received a clean precommit review.

Changed test-file costs, each measured with pnpm test <file> --maxWorkers=1:

File under src/gateway/ Command wall Tests
worker-environments/placement-dispatch-coordinator.test.ts 12.64 s 26 passed
worker-environments/placement-dispatch-coordinator-destroy.test.ts 5.65 s 9 passed
server-worker-placement-reclaim.test.ts 227.41 s 13 passed
worker-environments/placement-dispatch-recovery-admission.test.ts 188.32 s 10 passed

The original coordinator file measured 4.72 s / 32 passed before splitting out forced-destroy coverage. Command walls include transform/worker setup under varying host load and are not a performance comparison. The existing integration files retain real SQLite recovery and RPC cancellation/drain proof; a fake-only coordinator test cannot establish those persisted-state and cancellation contracts. CI per-file timing is not collected in this handoff; CI will not be watched to completion.

Earlier September 28 rebase and #159484 integration

Candidate: 310ed33309d270c673959daa3f44170ea0f0c170; merge-base: e433bfda89c486f98dfb03586dacd1e23b6f820b. Rebased the three commits onto main, integrating a08f2aa4ed7d (#159484). The two forced-destroy follow-up commits are unchanged in the range-diff; the first commit contains the conflict resolution and startup regression. All three retain Peter Steinberger as author and committer.

Startup preserves both of #159484's obligations: forced abandonment resumes before ordinary Stop synthesis, and a claimless draining Stop gets its fenced reclaim claim and recovery handoff before environment recovery. Each candidate now enters the same coordinator admission function before reading fresh projection facts or writing placement/workspace state. Startup/full recovery uses try-admission: a busy session has a live lifecycle operation in this process that owns its final save. Targeted recovery retains wait-admission. Ordering remains startup pre-pass → bounded environment pass → admitted session recovery → orphan tail.

Forced-abandonment writes retain session admission → workspace exclusion → environment-lock ordering. Environment reconciliation runs after the admitted unit returns, in a second workspaceOperations.run(environmentId, …) scope. The gap is safe because abandonment has already committed the failed placement/generation and closed its worker claims, while persisted destroy intent prevents attachment, credential renewal, and worker admission. Reconciliation reacquires workspace exclusion and reads current environment state; its guard can defer to an intervening lifecycle. It cannot revive the abandoned owner or target a replacement environment. Keeping reconciliation outside session admission also avoids its guard re-entering that session through resumeProvisioning.

PlacementRecoveryDeps remains owned by placement-recovery-contract.ts; orphan cleanup remains in placement-dispatch-orphan-cleanup.ts. There are no duplicate exports, shims, schema changes, or protocol changes. The existing restart/update final-save behavior is preserved.

Validation on this head:

  • The new deferred-fake busy/idle regression failed before the fix because startup called claimReclaimWorkspaceResult once while a live Stop owned the session (expected zero). The idle control passed. Both pass after the fix; there are no authored timers or sleeps.
  • node scripts/run-vitest.mjs ran the complete requested union: every test changed by fix(cloud-workers): Stop can lose workspace edits across a Gateway restart or update #159484, this PR's changed tests, and all placement-dispatch*.test.ts, server-worker-placement-*.test.ts, and worker-turn-launcher-*.test.ts: 58 files / 822 tests passed, 1,289.59 s command wall with two workers. No failures or timeout reruns.
  • pnpm test src/gateway/worker-environments/placement-dispatch-recovery-admission.test.ts --maxWorkers=1: 10 passed, 25.34 s command wall; Vitest 20.64 s. In the broad run the new busy/idle cases took 1.574 / 1.041 s. This file exercises real SQLite and coordinator/recovery owners through the existing shared fixture. CI per-file timing is not collected in this handoff.
  • pnpm tsgo:core and all four requested Gateway test graphs passed. The aggregate changed check additionally passed all 26 core test graphs, formatting, ratchets, boundaries, and all three dead-export scans (zero entries).
  • node scripts/check-changed.mjs stopped at the inherited core-lint error: ui/src/lib/sessions/session-roster-observations.ts:736:2, 713 counted lines versus 700 allowed. That file has identical blob aabefd3c2a2b162fe4697eb21b345f17b1ac56a1 at the merge-base and candidate; the UI tree, lint configuration, and runner are unchanged. No limit or suppression was changed. The remaining gates ran directly and passed: scripts lint, native schema, legacy stores, media helpers, runtime sidecar loaders, runtime import cycles (zero), webhook ordering, and both pairing guards.
  • git diff --check passed for both the worktree and the complete branch diff.
  • Independent Codex autoreview, branch mode against the new merge-base, high reasoning, fast service, P2: scoped-clean, no accepted/actionable findings. The unchanged abandonment, workspace, environment, admission, and store owners were supplied as review context.

Earlier forced-destroy ordering follow-up

Candidate: 240a212355157a8dbdb63b45a99927567766eaca; merge-base: c07906d5fa371add54d39321561c98a6da1dc434. Two new commits retain call-time ordering for attached/live owners and prevent overlapping destroys from acquiring their additional durable owners in reverse order. Durable discovery remains worker-backed; no synchronous SQLite or global wait was added. Every created reservation settles on success or failure, including a failed durable read.

Fail-before/pass-after controls use deferred fakes, without authored timers:

Original PR head 28bef6e4da98, attached-session controls:
  dispatch: expected ['destroy', 'dispatch']; received ['dispatch', 'destroy']
  Move:     expected ['destroy', 'move'];     received ['move', 'destroy']
  owner-read failure: same-session work ran while the read was held
  Tests 3 failed | 27 passed (30)

Exact original coordinator, live owner without attachment:
  expected ['move'] to deeply equal []
  Tests 1 failed | 31 skipped (32)

Intermediate dd4b0ee949a4, overlapping destroys with reversed owner reads:
  Test timed out in 1000ms (negative-control CLI bound; both reads resolved)
  Tests 1 failed | 31 skipped (32)

Final candidate:
  Coordinator: 32 passed
  Coordinator admission/reclaim and reporting siblings: 30 passed
  Recovery-event fixture: 15 passed
  Lifecycle-ordering fixture: 3 passed

Final production types and all four Gateway test graphs passed (pnpm tsgo:core; pnpm tsgo:core:test --ci-graphs-json '["core-test-gateway-root","core-test-gateway-server","core-test-gateway-other","core-test-gateway-methods"]'). Targeted lint passed for all 28 branch-changed source files. Formatting and git diff --check passed.

The requested 46-file test selection completed on dd4b0ee949a4: 44 files passed / 2 failed; 614 tests passed / 12 failed, wall 3881.12 s. It covers placement-dispatch*.test.ts, server-worker-placement-*.test.ts, server-methods/environments*.test.ts, placement-session-retirement*.test.ts, and the adjusted lifecycle-ordering fixture. The final overlap-only delta was then checked with the coordinator and reporting suites above. The broad run is not all green:

  • server.sessions.worker-placement-order.test.ts: the existing recover case exceeded its 120 s deadline (128.859 s). One final-candidate standalone run retained the original delete/archive/recover case order and passed all three; no timeout or assertion changed. That replay does not establish a fix for the broad-run timeout.
  • server-worker-placement-session-evidence.worker.test.ts: eleven failures involved missed pool callbacks, queue-capacity expectations, stale-absence expectations, and three 120 s close-boundary timeouts. The failing capacity case passed in one fresh-context standalone diagnostic (17.231 s test time, 462.96 s command wall, 1 passed / 16 skipped). Its test, resolver, pool, and state/config owners are unchanged against the merge-base. Non-isolated mock/pool initialization is implicated, but the exact shared-worker predecessor was not captured and no fixture repair is claimed. The original failures remain unresolved.

Local aggregate checks also expose two inherited UI limits: ui-other has 721 test roots / 720 allowed, and broad lint:core reports ui/src/lib/sessions/session-roster-observations.ts at 713 lines / 700 allowed. The UI tree and relevant configs/guard scripts are identical to the merge-base. The root limit is advisory only in GitHub Actions; its local failure was preserved. No limit, baseline, assertion, timeout, or environment flag was weakened. Final node scripts/check-changed.mjs stopped at the same inherited UI-root limit after its preceding checks passed. The remaining guards were executed directly: coercion/deprecation/deadcode, scripts lint, native schema/legacy stores, media/runtime-sidecar/import cycles, webhook ordering, and both pairing guards passed. Broad core lint retained the inherited UI max-lines failure; targeted lint for the changed source passed.

Independent Codex autoreview completed in branch mode against the pinned merge-base, high reasoning, fast service, P2: scoped-clean, no accepted/actionable findings. Its first overlap finding was reproduced and fixed. A subsequent changing-attachment hypothesis was evaluated with the unchanged owner implementations included and rejected: attachment accepts only ready/idle environments, attached state permits exactly one session, prepared allocation rejects existing placement references, and reclaim destroys the old environment before replacement.

Per-file cost on the final candidate, each measured with pnpm test <file> --maxWorkers=1:

File under src/gateway/ Command wall Result
worker-environments/placement-dispatch-coordinator.test.ts 13.24 s 32 passed
server-worker-placement-recovery-events.test.ts 193.83 s 15 passed
server.sessions.worker-placement-order.test.ts 209.55 s 3 passed

The latter two files only gained the required accessor fixture; their existing Gateway/SQLite lifecycle work and preparation dominate cost. No new process/Gateway boot or timer was added. The new overlap case took 6 ms in focused proof. The system volume was nearly full during the broad run; final focused proof used an isolated checkout on another local volume. The existing frozen lockfile was installed after the rebase, with no manifest or lockfile changes. Before this rebase, CI attachment at the preceding pushed head was blocked: GitHub reports mergeable: CONFLICTING with main. At that handoff the main CI workflow had no run for 240a212355157a8dbdb63b45a99927567766eaca; only pull_request_target workflows attached, including Security Review. No CI dispatch, rerun, merge, or post-push history rewrite was performed. CI completion and per-file CI timings were not collected.

Earlier campaign evidence (before this follow-up)

Pinned validation base: 71f918d0fa434ed778aaa6d13b644d6b247da8a2. The dependency install was refreshed with pnpm install --frozen-lockfile; no dependency or lockfile change is part of this PR.

  • pnpm tsgo:core: passed. pnpm tsgo:core:test: all 25 shards passed.
  • node scripts/check-changed.mjs: passed, including formatting, lint, both type graphs, schema guards, and zero runtime import cycles. The scoped changed check also passed after the final test-only conflict alignment. git diff --check: passed.
  • Final committed branch 0822a9954ee7: independent Codex branch review against the pinned base was scoped-clean at P2 (exit 0), with no actionable findings.
  • Fresh fail-on-main controls ran against the pinned main production files, not the earlier baseline: 14 intended cross-session failures. The restored candidate passed 6 files / 83 tests; final paired controls passed 23 tests / 60 skipped across those files. The real-service + SQLite independence case passed in 3.113 s, and the real Stop/turn-claim cycle case passed in 5.099 s.
Fail-on-main and mutation control output

Exact Vitest summary lines from the pinned-main controls:

Admission/reclaim cross-session regressions:
 Test Files  2 failed (2)
      Tests  9 failed | 18 skipped (27)
   Duration  17.23s

Coordinator cross-session siblings:
 Test Files  1 failed (1)
      Tests  4 failed | 23 skipped (27)
   Duration  10.18s

Real service + SQLite, teardown stuck and unrelated device provisioning:
 Test Files  1 failed (1)
      Tests  1 failed | 7 skipped (8)
   Duration  244.30s

Failing cases from those controls:

 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > admits unrelated device dispatch while a reconciliation provider teardown never settles
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > admits unrelated device reclaim while a reconciliation provider teardown never settles
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > admits unrelated device dispatch while another session's move provider never settles
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > admits unrelated device dispatch while another session's recovery provider never settles
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > admits unrelated device dispatch while another session's destroy provider never settles
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > full recovery preserves same-session ordering and admits unrelated dispatch
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-admission.test.ts > worker placement session admission > targeted recovery preserves same-session ordering and admits unrelated dispatch
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-reclaim.test.ts > reclaims independent sessions while targeted sweep waits for another session's dispatch
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator-reclaim.test.ts > reclaims independent sessions while recovery waits for another session's dispatch
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator.test.ts > worker placement dispatch coordinator > coalesces full sweeps while unrelated targeted sweeps run independently
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator.test.ts > worker placement dispatch coordinator > keeps same-session recovery behind move while unrelated recovery proceeds
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator.test.ts > worker placement dispatch coordinator > keeps same-session recovery behind reclaim while unrelated recovery proceeds
 FAIL  |gateway-core| src/gateway/worker-environments/placement-dispatch-coordinator.test.ts > worker placement dispatch coordinator > keeps same-session recovery behind destroy while unrelated recovery proceeds
 FAIL  |gateway-database-workers| src/gateway/worker-environments/placement-dispatch-recovery-admission.test.ts > placement recovery session admission with persisted placements > a real dispatch reaches device provisioning while another placement's teardown is stuck

The narrow cases failed at the 1,000 ms command-line negative-control bound. The real-service case entered teardown and requested unrelated dispatch, then failed at its 60,000 ms bound. Tests use deferred provider fakes; no authored sleeps were added. Wrapper walls were 23.59 s, 14.40 s, and 333.65 s respectively.

Temporary mutation Observed regression Vitest result Vitest / wrapper wall
Bypass admission Live startup/full dispatch classified as interrupted, live Move expired, targeted reads premature 6 failed / 2 skipped 774.60 / 1126.71 s
Move initial read before admission Activation, Move, and post-Stop pending-result facts read too early 3 failed / 3 passed / 2 skipped 185.79 / 219.75 s
Reserve Stop at call time Targeted recovery called zero times while Stop waits for its claim 1 failed / 15 skipped 379.37 / 421.37 s
Remove environment guard deferral Initial-placement waiter settles before reconciliation 1 failed / 4 skipped 33.86 / 44.08 s

All mutations were removed and restoration verified. The final paired positive control took 221.43 s in Vitest / 245.55 s wrapper wall. Subsequent source changes were orphan-cleanup extraction and behavior-preserving lint/binding corrections; the full candidate suite also exercises these regressions.

The required test union contains 138 files / 5,174 tests, covering every requested placement/turn-launcher/server/RPC family plus direct importers of changed production and support modules. Runs use node scripts/run-vitest.mjs with the owning project configurations and isolated Gateway state/ports. The latest results across the selected projects total 135 files passed / 3 failed; 5,171 tests passed / 3 unresolved timeout failures. The complete broad run is not all green; unchanged-file setup/timeout failures and their bounded reproductions are recorded below. Assertions and timeouts were not weakened.

Required suite results and bounded timeout reproductions

Latest completed results by owning project are listed below; unaffected methods results are reused from the complete Gateway run. This is not a claim that one full invocation was all green.

Project Files Passed tests Failed tests Vitest / command wall seconds
Tooling importers 7 3345 0 614.47 / 632.381
Gateway core 22 314 1 406.47 / 425.745
Gateway server 25 281 0 372.18 / 382.470
Gateway database workers 68 1045 0 610.93 / 622.440
Gateway server isolated 1 2 1 437.73 / 485.480
Gateway methods isolated 1 1 0 included in Gateway run
Gateway methods 13 183 0 included in Gateway run
UI importer 1 0 1 228.56 / 651.017

Timeout gaps after one bounded reproduction:

  • node-workspace-upload-reader.test.ts: the large-result upload/apply case exceeded its existing 60 s limit twice (69.277 s and 62.433 s). Telemetry reached apply-result without a correctness assertion failure.
  • server.placement-abandonment.test.ts: the offline-device abandonment case exceeded its existing 90 s limit twice (122.399 s and 142.750 s); the other two cases passed on replay.
  • worker-initial-setup.real-gateway.e2e.test.ts: the existing 90 s test deadline expired twice. Gateway listener startup took 75.4 s initially and 46.2 s on replay; captured logs stop at startup/ambient-channel suppression without later placement progress. The remaining wait is unresolved.

Other failures and their bounded reproductions:

  • Root-watch configuration resolution initially reached its 120 s child-process limit, then passed unchanged in 81.053 s. The complete seven-file replay passed.
  • Direct/restart shutdown initially exceeded the existing 5 s final-close guard; both later passed unchanged (84.265 s and 14.851 s total case time). The complete 25-file replay passed.
  • The remote-handoff fixture hit git init exit 124 at its existing 10 s setup limit before placement setup. The provider-bootstrap fixture hit its existing entry poll before bootstrapWorker began; cleanup then emitted one unhandled Worker provisioning operation is closed rejection. Both cases passed unchanged during the final bounded database replay; its complete result is listed above.

These are unchanged-file failures on a heavily contended host, not proven fixes. No assertions or timeouts were weakened, no retries were added, and no further replay loop was run. Deterministic fixture expectations tied to the removed global ordering were updated while preserving same-session, cancellation, authority, provider, and claim-settlement assertions. All 249 cases in the 16 changed test files passed in their final per-file measurements.

  • Live proof after the Stop ordering change: device dispatch reached active in 51.214695 s, and Stop reached reclaimed in 14.373463 s, while the unrelated provider stop remained unsettled 391.197 s after entry. Creation took 14.489888 s. This rerun covers the amendment's changed Stop preparation/admission and dispatch predecessor timing.

The live proof used a real isolated Gateway, SQLite, WebSocket callGateway, paired local session host, device provider, managed workspace, and reclaim. The cloud CLI fault was synthetic; no cloud API, credentials, or lease were used. Periodic reconciliation remained enabled, but exact sweep-entry times were not instrumented. No live main comparison ran. The built runtime predates the rebase; all ten relevant production modules were individually SHA-256-identical to the rebased candidate at measurement. Later changes extracted orphan cleanup and corrected lint/bindings and test fixtures; Stop/dispatch timing logic is unchanged. Host load was approximately 45–72 on 32 cores, so these numbers demonstrate independent completion rather than benchmark performance. All owned live/test processes, state/config/pairing material, workspaces, temporary proof worktrees, and the scratch runtime were removed.

Change size and retired coordination machinery

Production: +245 / −332 (net −87). Tests and support: +1245 / −1038 (net +207). Docs: +3 / −3. Test routing: +1 / −0.

Removed: placementFence, PlacementFence, MaintenanceAdmission, ReconciliationSweep, activeDispatches, dispatchIdleWaiters, waitForDispatchIdle, enterMaintenance, prepareReclaim, runExclusivePlacementOperation, runPlacementOperation, dispatchCohort, recoveryReady, acceptingJoins, and joinedRecoveries.

Measured cost of every changed test file

Each file ran once on final head 0822a9954ee7 with pnpm test <file> --maxWorkers=1, isolated Gateway state/ports, and the filesystem module cache disabled. These are command wall times, including wrapper/preparation overhead on the contended host. All 16 commands exited 0. CI per-file timing is not yet available at the ready-PR handoff.

File under src/gateway/ Wall seconds Result
server-worker-placement-provision-cancellation.test.ts 99.218 passed
server-worker-placement-reclaim.test.ts 55.475 passed
server-worker-placement-reconcile-guard.test.ts 9.370 passed
server-worker-placement-recovery-events.test.ts 46.729 passed
server-worker-placement-startup.test.ts 71.430 passed
server.sessions.archive-worker-placement.test.ts 240.582 passed
server.sessions.worker-placement-order.test.ts 208.028 passed
worker-environments/placement-dispatch-coordinator-admission.test.ts 6.564 passed
worker-environments/placement-dispatch-coordinator-reclaim.test.ts 5.745 passed
worker-environments/placement-dispatch-coordinator.test.ts 7.270 passed
worker-environments/placement-dispatch-device.test.ts 158.424 passed
worker-environments/placement-dispatch-recovery-admission.test.ts 164.294 passed
worker-environments/placement-dispatch-reporting.test.ts 8.818 passed
worker-environments/placement-dispatch.test.ts 268.027 passed
worker-environments/placement-startup-concurrency.test.ts 48.517 passed
worker-environments/worker-turn-launcher-terminal-results.test.ts 232.834 passed

@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL labels Sep 28, 2026
@steipete
steipete marked this pull request as ready for review September 28, 2026 08:52
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. 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 Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 9:53 AM ET / 13:53 UTC (Revision 6).

ClawSweeper review

What this changes

The branch replaces Gateway-wide cloud-worker placement ordering with per-session ordering for dispatch, Move, Stop, recovery, and forced destruction, and updates lifecycle documentation and tests.

Merge readiness

✅ Ready for maintainer review

Keep this PR open. Current main still uses a Gateway-wide placement fence, so the branch’s per-session fix remains useful. The earlier startup-recovery integration concern is addressed in the reviewed head, with combined regression coverage and real Gateway proof.

Priority: P1
Reviewed head: 22b8fb463fa0622e4a3ddba0920f443165afc54b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Real Gateway proof and focused ordering regressions support a useful, well-scoped repair across a broad lifecycle surface.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR reports a real isolated Gateway, SQLite store, and paired session host exercising dispatch and Stop while an unrelated provider teardown remained stuck; dispatch became active and Stop reclaimed the session before teardown settled. Focused tests cover the later forced-destroy ordering amendment. The change adds no stored-data format, so data-model compatibility is not applicable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR reports a real isolated Gateway, SQLite store, and paired session host exercising dispatch and Stop while an unrelated provider teardown remained stuck; dispatch became active and Stop reclaimed the session before teardown settled. Focused tests cover the later forced-destroy ordering amendment. The change adds no stored-data format, so data-model compatibility is not applicable.
Evidence reviewed 8 items Current main still has the global fence: The fetched main revision retains placementFence and routes forced destruction and Move through exclusive placement operations.
Per-session admission: The introduced coordinator reserves session keys before yielding and keeps reservations until their operations settle.
Startup recovery integration: The startup pre-pass now admits each session before reading fresh placement facts, preserving forced-abandonment handling and claimless-draining Stop handoff.
Findings None None.
Security None None.

How this fits together

The Gateway coordinates cloud-worker operations for sessions using placement records and worker environments. Its ordering determines when dispatch, recovery, Stop, and destruction can affect a session and its workspace.

flowchart LR
  A[Session request] --> B[Placement coordinator]
  C[Recovery sweep] --> B
  B --> D{Same session busy?}
  D -->|Yes| E[Wait or defer recovery]
  D -->|No| F[Worker operation]
  E --> F
  F --> G[Placement and workspace result]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source -43, Tests +506, Docs 0. Total +463 across 32 files.

View PR surface stats
Area Files Added Removed Net
Source 11 336 379 -43
Tests 20 1526 1020 +506
Docs 1 3 3 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 32 1865 1402 +463

Review metrics

Metric Value Why it matters
Production and test footprint production net −87 lines; tests and support net +207 lines The coordination code shrinks while coverage for its session-ordering contracts expands.

Root-cause cluster

Relationship: canonical
Canonical: #160299
Summary: The linked merged PRs cover prerequisite recovery reads and distinct Stop durability behavior; this PR remains the candidate for cross-session ordering.

Members:

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

Technical review

Best possible solution:

Keep the coordinator’s per-session ordering while preserving the existing placement owner, workspace, and authorization checks at each final effect.

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

Yes, at the source and regression-fixture level: current main retains the global fence, and the PR records specific fail-on-main cross-session controls. This read-only review did not execute a current-main Gateway.

Is this the best way to solve the issue?

Yes. Per-session admission addresses the shared wait at its coordination owner while the existing service retains placement and workspace checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 3a300c650a5b.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: Slow worker teardown can delay unrelated session dispatch and Stop for minutes.
  • merge-risk: 🚨 session-state: The patch changes ordering among dispatch, Stop, recovery, and destruction around durable session placements.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a real isolated Gateway, SQLite store, and paired session host exercising dispatch and Stop while an unrelated provider teardown remained stuck; dispatch became active and Stop reclaimed the session before teardown settled. Focused tests cover the later forced-destroy ordering amendment. The change adds no stored-data format, so data-model compatibility is not applicable.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a real isolated Gateway, SQLite store, and paired session host exercising dispatch and Stop while an unrelated provider teardown remained stuck; dispatch became active and Stop reclaimed the session before teardown settled. Focused tests cover the later forced-destroy ordering amendment. The change adds no stored-data format, so data-model compatibility is not applicable.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Lehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (5 earlier review cycles)
  • reviewed 2026-09-28T08:59:45.316Z sha 0822a9954ee7315b8f2f6f2493c59a413d5f5d63 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-28T09:28:31.163Z sha 28bef6e :: blocked before merge. :: none
  • reviewed 2026-09-28T10:34:06.127Z sha 28bef6e :: blocked before merge. :: none
  • reviewed 2026-09-28T11:18:21.292Z sha 240a212355157a8dbdb63b45a99927567766eaca :: blocked before merge. :: none
  • reviewed 2026-09-28T11:28:40.021Z sha 240a212355157a8dbdb63b45a99927567766eaca :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/placement-session-admission branch from 0822a99 to 28bef6e Compare September 28, 2026 09:21
@openclaw-barnacle openclaw-barnacle Bot reopened this Sep 28, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. label Sep 28, 2026
@steipete
steipete force-pushed the codex/placement-session-admission branch from 240a212 to 310ed33 Compare September 28, 2026 12:06
Reserve attached sessions and live placement owners before asynchronous durable owner reads. Admit only additional durable owners in a second phase and settle both reservations on every outcome, including read failure.
Wait for known session predecessors before discovering additional durable owners so overlapping destroys cannot reserve the second phase in reverse order. Keep the reservation local to the affected sessions and cover the cycle with deferred owner reads.
Try-reserve only idle durable owners after discovery, preserving call-time reservations and the phase-1 service-order wait. Skip busy durable-only owners instead of holding phase 1 while waiting behind a later destroy.

Cover owner growth, queued recovery, Stop preparation, and idle durable-owner holding with deferred coordinator fakes. Keep the fixed-owner overlap contract, remove the obsolete pre-discovery wait, and document the updated ordering.
Move the shared admission type out of the recovery implementation so orphan cleanup no longer imports its caller. Both consumers use the existing type-only recovery contract; no re-export shim remains.
The main harness now snapshots store methods. Install spies before that snapshot, preserve the bound implementations, and arm deferred reads at the existing observation boundary so Stop and recovery probes still exercise the service.

Preserve all assertions, deadlines, and production code. This fixes the four deterministic fixture failures exposed by the required main rebase.
@steipete
steipete force-pushed the codex/placement-session-admission branch from 310ed33 to 22b8fb4 Compare September 28, 2026 13:45
@steipete
steipete merged commit 522e29d into main Sep 28, 2026
134 of 203 checks passed
@steipete
steipete deleted the codex/placement-session-admission branch September 28, 2026 14:27
steipete added a commit that referenced this pull request Sep 28, 2026
Allow targeted workspace-result recovery to release a turn claim while
Dispatch or reconcile Move drains. Wait for earlier registered placement
operations before draining, then hand ingress closure to the existing
lifecycle mutation before writing durable dispatch or Move state.

Keep Stop and explicit source abandonment unchanged. Add SQLite-backed
Dispatch and durable Move retry regressions, protect FIFO before drain,
and document the out-of-queue preparation. Follow-up to #160299.

Validation: both regressions fail on the original production code at the
recovery-admission boundary, without the 15-second timeout. Restoring the
production patch reproduced the exact saved diff hash. Final per-file
runs pass 31 coordinator, 27 cancellation, and 17 terminal-result tests;
new Dispatch and Move cases take 2.72s and 1.96s respectively. Single-worker
file walls are 12.98s, 119.69s, and 142.96s in that order. Core and core-test
tsgo, check-changed, diff checks, and independent review pass.

The 73-file family run passed 965 tests and timed out the first real
abandonment fixture; its two successors rejected unreleased fixture
ownership. A single diagnostic reproduction in the same isolated-file
order passed all four tests, including all three abandonment cases.
The original timeout cause remains unproven; no assertion or timeout was
weakened, and no flake fix is claimed. Its orphaned mock provider and
retained temporary namespace were cleaned up after verifying termination.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…sions (openclaw#160299)

- fix(gateway): keep slow worker operations from blocking unrelated sessions
- fix(gateway): keep forced destroy ahead of later same-session work
- fix(gateway): order overlapping forced-destroy admissions
- fix(gateway): avoid forced-destroy discovery deadlocks
- refactor(gateway): keep recovery admission in the recovery contract leaf
- test(gateway): install placement spies before harness construction

Periodic worker-placement reconciliation no longer installs a global placement fence. Each coordinator operation is admitted per session: dispatch and Move enter after same-session Stop predecessors, Stop preparation stays outside the queue and only entered cleanup joins it, provisioning recovery holds its session until the provider settles, and forced destroy reserves attached/live owners at call time and try-reserves durable-only owners without waiting. Sweep recovery units read fresh facts after admission (full/startup sweeps skip busy sessions; targeted sweeps wait), and environment reconciliation always runs outside session admission. The openclaw#159484 startup Stop final-save pass runs as admitted units. Slow provider inspection or teardown for one environment no longer delays dispatch or Stop of unrelated sessions (live: paired-device dispatch had taken 818 s and 554 s behind stuck Crabbox teardown).

Known pre-existing limitation: Move and dispatch local barriers wait for turn-claim release inside admission; previously global, now same-session only.

Landed with an operator-authorized admin merge: the remaining CI failure was unrelated (src/gateway/server.config-patch.test.ts ConfigWritePostCommitError), with all static checks green.
steipete added a commit that referenced this pull request Sep 29, 2026
Allow targeted workspace-result recovery to release a turn claim while
Dispatch or reconcile Move drains. Wait for earlier registered placement
operations before draining, then hand ingress closure to the existing
lifecycle mutation before writing durable dispatch or Move state.

Keep Stop and explicit source abandonment unchanged. Add SQLite-backed
Dispatch and durable Move retry regressions, protect FIFO before drain,
and document the out-of-queue preparation. Follow-up to #160299.

Validation: both regressions fail on the original production code at the
recovery-admission boundary, without the 15-second timeout. Restoring the
production patch reproduced the exact saved diff hash. Final per-file
runs pass 31 coordinator, 27 cancellation, and 17 terminal-result tests;
new Dispatch and Move cases take 2.72s and 1.96s respectively. Single-worker
file walls are 12.98s, 119.69s, and 142.96s in that order. Core and core-test
tsgo, check-changed, diff checks, and independent review pass.

The 73-file family run passed 965 tests and timed out the first real
abandonment fixture; its two successors rejected unreleased fixture
ownership. A single diagnostic reproduction in the same isolated-file
order passed all four tests, including all three abandonment cases.
The original timeout cause remains unproven; no assertion or timeout was
weakened, and no flake fix is claimed. Its orphaned mock provider and
retained temporary namespace were cleaned up after verifying termination.
steipete added a commit that referenced this pull request Sep 29, 2026
Keep validation and durable placement writes ahead of interruption. While a
Dispatch or Move waits for its retained turn claim, admit same-session
results-only recovery and join every lent unit before continuing. Remove
the former pre-drain path and preserve ordinary recovery and Stop ordering.

Related: #160299
steipete added a commit that referenced this pull request Sep 29, 2026
…rn's result needs recovery (#160535)

* fix(gateway): drain turn claims before placement session admission

Allow targeted workspace-result recovery to release a turn claim while
Dispatch or reconcile Move drains. Wait for earlier registered placement
operations before draining, then hand ingress closure to the existing
lifecycle mutation before writing durable dispatch or Move state.

Keep Stop and explicit source abandonment unchanged. Add SQLite-backed
Dispatch and durable Move retry regressions, protect FIFO before drain,
and document the out-of-queue preparation. Follow-up to #160299.

Validation: both regressions fail on the original production code at the
recovery-admission boundary, without the 15-second timeout. Restoring the
production patch reproduced the exact saved diff hash. Final per-file
runs pass 31 coordinator, 27 cancellation, and 17 terminal-result tests;
new Dispatch and Move cases take 2.72s and 1.96s respectively. Single-worker
file walls are 12.98s, 119.69s, and 142.96s in that order. Core and core-test
tsgo, check-changed, diff checks, and independent review pass.

The 73-file family run passed 965 tests and timed out the first real
abandonment fixture; its two successors rejected unreleased fixture
ownership. A single diagnostic reproduction in the same isolated-file
order passed all four tests, including all three abandonment cases.
The original timeout cause remains unproven; no assertion or timeout was
weakened, and no flake fix is claimed. Its orphaned mock provider and
retained temporary namespace were cleaned up after verifying termination.

* fix(gateway): bind the pre-admission drain to the requested session

Resolve the canonical entry before closing ingress and refuse the drain
when the session key now names a different session, so an interrupt by
key cannot reach a replacement session. Matches Stop's preparation.

* fix(gateway): reject stale placement requests before draining session work

Read observed placement facts through the state read worker before closing
session ingress or interrupting work. Share the row preconditions with the
durable writers; preserve their final CAS and recovery checks. A draining
Move retry may interrupt only the same environment and owner epoch.

Prove stale active and draining Move sources through the real sessions.move
handler, coordinator, drain, admissions, and SQLite placement store. Prove
active dispatch rejection at the coordinator boundary. All three regressions
fail on the original production code at the interruption assertion and pass
after restoration, with source hashes verified.

Core and core-test typechecks, check-changed, and Codex review pass. The
77-file placement/worker-turn family has 1009 passing tests and one previously
observed abandonment timeout; one ordered isolated replay passed all four
tests. Its timeout cause remains unproven, and no flake fix is claimed.

* refactor(gateway): keep the move-source precondition with its owner

The shared precondition module imported the placement reclaim contract,
whose service-contract types import the move intent module back, closing
a static import cycle once the move writer used the shared predicate.
Keep the Move-source predicate beside beginPlacementMove and its source
type; the shared module keeps only the dispatch predicate. Behavior is
unchanged.

* fix(gateway): lend claim-wait admission to result recovery

Keep validation and durable placement writes ahead of interruption. While a
Dispatch or Move waits for its retained turn claim, admit same-session
results-only recovery and join every lent unit before continuing. Remove
the former pre-drain path and preserve ordinary recovery and Stop ordering.

Related: #160299

* fix(gateway): let interrupted worker turns finish result recovery

Keep results-only admission lending open across interruption and claim release. Admit already-queued targeted recovery when the window opens while retaining its original FIFO reservation.

* test(gateway): cover production result recovery during Move

Replace direct claim settlement in the Move regression with the real dispatch recovery action and SQLite result completion. Supply the required lending hook to the keyed-store-write barrier test added on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 30, 2026
…rn's result needs recovery (openclaw#160535)

* fix(gateway): drain turn claims before placement session admission

Allow targeted workspace-result recovery to release a turn claim while
Dispatch or reconcile Move drains. Wait for earlier registered placement
operations before draining, then hand ingress closure to the existing
lifecycle mutation before writing durable dispatch or Move state.

Keep Stop and explicit source abandonment unchanged. Add SQLite-backed
Dispatch and durable Move retry regressions, protect FIFO before drain,
and document the out-of-queue preparation. Follow-up to openclaw#160299.

Validation: both regressions fail on the original production code at the
recovery-admission boundary, without the 15-second timeout. Restoring the
production patch reproduced the exact saved diff hash. Final per-file
runs pass 31 coordinator, 27 cancellation, and 17 terminal-result tests;
new Dispatch and Move cases take 2.72s and 1.96s respectively. Single-worker
file walls are 12.98s, 119.69s, and 142.96s in that order. Core and core-test
tsgo, check-changed, diff checks, and independent review pass.

The 73-file family run passed 965 tests and timed out the first real
abandonment fixture; its two successors rejected unreleased fixture
ownership. A single diagnostic reproduction in the same isolated-file
order passed all four tests, including all three abandonment cases.
The original timeout cause remains unproven; no assertion or timeout was
weakened, and no flake fix is claimed. Its orphaned mock provider and
retained temporary namespace were cleaned up after verifying termination.

* fix(gateway): bind the pre-admission drain to the requested session

Resolve the canonical entry before closing ingress and refuse the drain
when the session key now names a different session, so an interrupt by
key cannot reach a replacement session. Matches Stop's preparation.

* fix(gateway): reject stale placement requests before draining session work

Read observed placement facts through the state read worker before closing
session ingress or interrupting work. Share the row preconditions with the
durable writers; preserve their final CAS and recovery checks. A draining
Move retry may interrupt only the same environment and owner epoch.

Prove stale active and draining Move sources through the real sessions.move
handler, coordinator, drain, admissions, and SQLite placement store. Prove
active dispatch rejection at the coordinator boundary. All three regressions
fail on the original production code at the interruption assertion and pass
after restoration, with source hashes verified.

Core and core-test typechecks, check-changed, and Codex review pass. The
77-file placement/worker-turn family has 1009 passing tests and one previously
observed abandonment timeout; one ordered isolated replay passed all four
tests. Its timeout cause remains unproven, and no flake fix is claimed.

* refactor(gateway): keep the move-source precondition with its owner

The shared precondition module imported the placement reclaim contract,
whose service-contract types import the move intent module back, closing
a static import cycle once the move writer used the shared predicate.
Keep the Move-source predicate beside beginPlacementMove and its source
type; the shared module keeps only the dispatch predicate. Behavior is
unchanged.

* fix(gateway): lend claim-wait admission to result recovery

Keep validation and durable placement writes ahead of interruption. While a
Dispatch or Move waits for its retained turn claim, admit same-session
results-only recovery and join every lent unit before continuing. Remove
the former pre-drain path and preserve ordinary recovery and Stop ordering.

Related: openclaw#160299

* fix(gateway): let interrupted worker turns finish result recovery

Keep results-only admission lending open across interruption and claim release. Admit already-queued targeted recovery when the window opens while retaining its original FIFO reservation.

* test(gateway): cover production result recovery during Move

Replace direct claim settlement in the Move regression with the real dispatch recovery action and SQLite result completion. Supply the required lending hook to the keyed-store-write barrier test added on main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant