Skip to content

refactor(gateway): run placement transitions and drain settlement in workers - #164252

Merged
steipete merged 2 commits into
mainfrom
dbasync/placetrans
Oct 3, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/placetrans

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Placement transitions, drain/reconcile, and terminal-failure writes still ran SQLite on the Gateway main thread during dispatch, reclaim, and recovery.

Why This Change Was Made

Extend the existing placementTurns commands and shared-state broker from #163594 and #163819. The worker rereads the exact state, generation, environment, epoch, pending result, and claim inside the synchronous transaction. Host authority is checked at transaction and commit admission. Acknowledged placement, closed-claim, and activation-demand facts publish through the existing owners before observers.

All affected runtime callers await settlement, including activation/reclaim lifecycle barriers and diagnostic terminal recovery. Idle drain compares the captured activity timestamp in the worker and rechecks current host policy without placement reads in the grant. Unknown outcomes retain recovery custody; they never authorize replay, generic failure compensation, or inverse filesystem effects.

User Impact

Internal execution change only. Main's current terminal-failure semantics remain intact. No schema, stored format, retention, durability, permission, configuration, or update behavior changes; zero new OPENCLAW_* names. No operator action is required.

Released SDK check against v2026.9.8: the five store mutations and terminal-recovery callbacks are internal. Gateway readers, retirement, and asynchronous dispatch contracts remain compatible. The callable reclaim source check retains its signature, with an optional host-only eligibility assertion; the SDK type regression accepts the original plain callback. Existing compatibility adapters are unchanged.

Overlap: #164014/#164022 cleanup is already in the baseline; #160108 remains adjacent. #121063 will need to rebase on this cutover. Its proposed capability-fenced-worker drain/fail behavior is deliberately untouched.

Evidence

  • Original reviewed head production: 29 files, +905 / −481, net +424; 1,386 changed production lines, below the split threshold. Test changes propagate awaits and preserve assertions; focused regressions exercise the real worker boundary.
  • Inventory: T1 1,311 → 1,300. Shared kernels still used by excluded placement-move and prepared-environment owners retain conservative T1 classification.
  • Full node scripts/check-changed.mjs --base efcd9ff82b8488abfc6f9dbd6443ba0afb2fdcd8 passed in 1,125.38 s, including all 27 core test typecheck groups, formatting, lint, SDK/export checks, and storage guards.
  • Madge: 0 cycles, 32.48 s. Pinned database-worker ratchet: passed, 2.60 s.
  • 297/297 focused tests passed across 19 files, 883.59 s summed command wall time. Each command used pnpm test <file> --maxWorkers=1; detailed timings are below.
  • Independent Codex autoreview: scoped-clean through P2, pinned to merge base efcd9ff82b8488abfc6f9dbd6443ba0afb2fdcd8. No accepted/actionable findings remain.
  • Blacksmith Testbox: tbx_01m40gb7mt52wyd0mmgy36ajra, run 37112041188. The receiver verified source tree c2f63d4c2f4e95a001766c90fb880d9352303c0b and every changed file. The staged commit tree matches exactly.

Earlier validation found the startup line cap and async test-fixture signatures. The provisioning-retention helper was moved into its existing sibling owner, and the fixtures were corrected. No assertion, timeout, skip, or baseline exception was weakened.

The first Testbox lease reached its approximately 60-minute workflow lifetime after the gate and 17 suites passed; its Actions job is cancelled, not a green overall run. The completed command prefix remains valid proof. A replacement lease remained queued and was stopped before execution. The two unfinished suites passed locally on the same source. Both leases are verified completed. The first Testbox check job consumed 3,900 CI wall seconds including setup, earlier fixture corrections, and shutdown; the table records focused command seconds separately. Exact-head PR CI will run after publication and is not included in this prepublication proof.

Authority-read follow-up debt

The existing short indexed reads remain live in grants: session revision/transcript-owner checks at src/gateway/server-worker-placement-session-target.ts:129, canonical session binding at src/gateway/server-worker-placement-session-target.ts:275, and the worktree lookup at src/agents/worktrees/registry.ts:258. They use other owners' admitted native handles or prepared facts, not maintenance-scoped shared-state snapshots. Boundary tests assert zero caller-thread SQL for the moved placement operations, not for these unrelated authority owners. Prepared-environment binding, placement moves, retirement, and general placement reads remain separate migration work.

Focused test timings

Longer suites exercise real SQLite workers, lost-reply settlement, claim-close observers, and session lifecycle barriers. A mock of those owners would not establish the thread or custody contract. Existing fixtures gained awaits; no additional per-test Gateway boots were added.

Test file Tests Wall seconds Host
src/gateway/worker-environments/placement-turn-claims.worker.test.ts 28 27.57 Testbox
src/gateway/worker-environments/placement-store-terminal.test.ts 13 24.31 Testbox
src/gateway/worker-environments/placement-store.turn-claim-closure.test.ts 32 45.99 Testbox
src/gateway/worker-environments/placement-store.reconcile.test.ts 1 16.29 Testbox
src/gateway/worker-environments/placement-worker-gate.test.ts 22 28.76 Testbox
src/gateway/worker-environments/worker-turn-launcher-failure-recovery.test.ts 11 47.20 Testbox
src/gateway/worker-environments/worker-turn-launcher-initial-setup.test.ts 17 38.16 Testbox
src/gateway/worker-environments/worker-turn-launcher-terminal-results.test.ts 17 51.18 Testbox
src/gateway/server-worker-placement-reclaim.preparation.test.ts 40 44.09 Testbox
src/gateway/worker-environments/placement-force-abandon.test.ts 5 18.74 Testbox
src/gateway/worker-environments/placement-idle-sweep.test.ts 20 31.16 Testbox
src/gateway/worker-environments/provider-provisioning.shutdown-replay.test.ts 1 18.90 Testbox
src/plugin-sdk/gateway-placement-compat.test.ts 1 1.33 Testbox
test/scripts/pr-wrapper-source-closure.test.ts 6 3.58 Testbox
src/gateway/server.sessions.recover.test.ts 22 42.69 Testbox
src/gateway/server.sessions.worker-original-order.test.ts 1 23.47 Testbox
src/gateway/server-worker-placement-cancel.test.ts 3 21.41 Testbox
src/gateway/server-worker-placement-provision-cancellation.test.ts 27 225.66 macOS
src/gateway/worker-environments/placement-dispatch-reclaim.test.ts 30 173.10 macOS

Landing review and CI repairs

The released SDK check was repeated against v2026.9.8: no removed public export or changed released sync/async signature. The optional reclaim source assertion preserves plain callback compatibility. ClawSweeper completed on f69fe0f6f4007775409bcc1ba421dd8840ac47f8 with no code findings; its config/data-model flags came from a truncated file list. The complete diff changes no schema, stored format, configuration default, retention, permission, or update contract.

Initial CI run 37117055531 exposed missed awaits in the canonical-descendant and cloud-worker disappearance fixtures, an obsolete exact spy-call expectation, a duplicate-recovery fixture that asserted before the first recovery progressed, an unnecessary placement command root in the standalone PR wrapper inventory, and a caller-authority check incorrectly applied to final bookkeeping after admitted teardown. These are attributed to this cutover and repaired in 6e5de1de3fd427f26fc2f75c0705d9f740bfc891; the failed run is not passing evidence. Authorization still gates new teardown and Gateway workspace materialization. The existing exact generation predicate and held lifecycle fence protect final settlement.

The required shared-registry checks passed: runtime-process-build-graph, shared-state worker imports, get-reply imports, and worker-turn-launcher imports (16 tests, 100.66 s total local wall time). The wrapper command runtime remains outside the standalone lease wrapper; the extracted transition module is part of the compiled application worker graph, whose dependency inventory is generated from imports.

ClawSweeper revision 2 on the original head independently identified the same five wrapper, fixture, and post-destroy completion defects. The repair removes the unnecessary wrapper root instead of expanding a standalone lease wrapper to include application commands; both wrapper inventory/export tests and real extracted-wrapper lease execution pass. The duplicate-recovery fixture now starts both calls before awaiting their settlement and asserts the duplicate result, without a dangling wait or timer.

Repair validation: 191 tests passed across six files in 515.70 s local wrapper wall time: eager-import-closure (17), placement-dispatch-authority and placement-move-abandon (38), canonical-descendant and diagnostic recovery (125), and followup recovery (11). Every invocation used --maxWorkers=1. Both affected root test typechecks, scoped formatting/lint, the pinned database-worker ratchet, and fresh P2 Codex autoreview passed. Initial failing CI is retained above; exact-head CI run 37118573977 passed at 6e5de1de3fd427f26fc2f75c0705d9f740bfc891 (452 s elapsed; 4,088 aggregate Node test job seconds).

ClawSweeper revision 3 completed on the repaired head and confirms all five findings are resolved with no remaining actionable code or security defect. The two generic config/data compatibility checklist items are covered by the complete-diff and released-SDK checks above.

Independent attribution is complete: five singly executed invocations per revision for diagnostic recovery, dispatch authority, move abandonment, canonical descendant, and the two selected wrapper closure cases. All 25 original-head invocations reproduced the expected failures; all 25 merge-base invocations passed. Each used node scripts/run-vitest.mjs <file> --maxWorkers=1 (wrapper selection: -t 'PR wrapper inventory|wrapper package exports'). Total serial command wall time was 2,681.04 s for the original head and 2,655.52 s for the merge base, run concurrently in isolated worktrees; no CI was rerun for attribution. Main run 37113342869 had the separate import-graph and attempt-stream fixture failures noted in the handoff. No inherited-failure admin exception is needed or claimed.

Run transitions, drain/reconcile and terminal failure settlement through
placementTurns and the existing shared-state writer. Preserve exact claims,
physical store identity, live grants, publication order and unknown-outcome
custody. Keep the current terminal-failure policy unchanged.

Validation: changed-file gate, 297 focused tests, database-worker ratchet,
zero import cycles and independent Codex review through P2.
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 3, 2026
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 3, 2026, 7:43 AM ET / 11:43 UTC (Revision 5).

ClawSweeper review

What this changes

Moves cloud-worker placement transitions, draining, reconciliation, and terminal-failure persistence into database workers, with callers awaiting settlement.

Merge readiness

⛔ Blocked before merge - 2 items remain

This PR remains useful: current main still performs the targeted placement writes synchronously. No remaining actionable code or security finding was identified, and the previous generic configuration and data-model blockers are unsupported by the complete introduced diff.

Priority: P2
Reviewed head: 6e5de1de3fd427f26fc2f75c0705d9f740bfc891

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent internal cutover with meaningful worker-boundary coverage, successful exact-head CI, and no remaining actionable finding.
Proof confidence 🌊 off-meta tidepool Not applicable: Ordinary contributor proof is exempt under the supplied MEMBER classification. Inspected production-worker regressions cover transition revocation, successor custody, receipt loss, and observer ordering, with exact-head CI confirmed; no unresolved authority case requires an additional proof gate. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Ordinary contributor proof is exempt under the supplied MEMBER classification. Inspected production-worker regressions cover transition revocation, successor custody, receipt loss, and observer ordering, with exact-head CI confirmed; no unresolved authority case requires an additional proof gate. No stored-data contract changes.
Evidence reviewed 10 items Pinned introduction and clean checkout: Read the complete merge-base-to-head file list and introduced production and test hunks. The checkout is the pinned original head and remained clean. Endpoint drift and the stale test merge were not used to attribute changes.
Still necessary on current main: Fetched main retains synchronous transition and drain implementations in the placement store. The merged ledger and result-settlement work supplies prerequisites but does not implement this transition cutover.
Transaction and authority ownership: The extracted operations reread authoritative placement rows inside synchronous transactions. The existing mutation owner checks the physical database and caller authority at transaction and commit admission; new activation and reclaim callers forward their current lifecycle assertions.
Findings None None.
Security None None.

How this fits together

Gateway placement controls where an agent session executes and how its worker is reclaimed or recovered. Lifecycle requests enter this subsystem; committed placement facts then control execution authority, cleanup, and session notifications.

flowchart TD
  A[Session lifecycle requests] --> B[Gateway placement owner]
  B --> C[Live authority admission]
  C --> D[Database worker]
  D --> E[Exact placement transaction]
  E --> F[Committed receipt]
  F --> G[Authority and environment publication]
  G --> H[Execution and cleanup observers]
Loading

Before merge

  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus test growth production net +422 lines; tests and support net +254 lines Production growth supports worker dispatch, settlement receipts, and authority propagation; test growth protects the actual worker and lifecycle boundaries.

Stored data model

Persistent data-model change detected: unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep placement persistence under the existing worker writer, with exact transaction predicates and acknowledged facts published before dependent lifecycle work.

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

Not applicable as a user-facing bug reproduction: this is an internal execution refactor. Current-main source directly establishes the synchronous placement writes being moved.

Is this the best way to solve the issue?

Yes. Extending the existing worker dispatcher and receipt-publication owners avoids a competing persistence implementation while preserving current lifecycle semantics.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded internal reliability improvement that removes synchronous placement writes from the Gateway thread.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Ordinary contributor proof is exempt under the supplied MEMBER classification. Inspected production-worker regressions cover transition revocation, successor custody, receipt loss, and observer ordering, with exact-head CI confirmed; no unresolved authority case requires an additional proof gate. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction and clean checkout: Read the complete merge-base-to-head file list and introduced production and test hunks. The checkout is the pinned original head and remained clean. Endpoint drift and the stale test merge were not used to attribute changes. (6e5de1de3fd4)
  • Still necessary on current main: Fetched main retains synchronous transition and drain implementations in the placement store. The merged ledger and result-settlement work supplies prerequisites but does not implement this transition cutover. (src/gateway/worker-environments/placement-store.ts:371, c81d86e82f60)
  • Transaction and authority ownership: The extracted operations reread authoritative placement rows inside synchronous transactions. The existing mutation owner checks the physical database and caller authority at transaction and commit admission; new activation and reclaim callers forward their current lifecycle assertions. (src/gateway/worker-environments/placement-transitions.worker.ts:43, 6e5de1de3fd4)
  • Revocation, successor, and settlement coverage: Inspected regressions exercise real SQLite workers, reject revoked callers before transaction or commit, preserve successor claims, check captured activity, and distinguish committed lost replies from unknown outcomes. Receipt publication precedes claim-close observers. These tests were inspected, not rerun. (src/gateway/worker-environments/placement-turn-claims.worker.test.ts:113, 6e5de1de3fd4)
  • Configuration and stored-data concerns cleared: The complete introduced diff changes no schema installer, serialized format, configuration definition, default, retention rule, or updater. Existing SQL row values and terminal-failure policy move to the worker owner; added drain predicates protect runtime currentness. The historical generic compatibility checklist does not identify a remaining changed contract. Public docs: docs/reference/database-schemas/worker-access.md. (docs/reference/database-schemas/worker-access.md:687, 6e5de1de3fd4)
  • Public placement boundary: Gateway request context exposes placement readers and retirement, rather than the five changed store mutations. The reclaim callback retains its callable signature with an optional host assertion, and the SDK regression accepts the original plain callback. The body records the released-SDK audit against v2026.9.8; independent retrieval of additional release blobs was unavailable. (src/gateway/server-methods/shared-types.ts:408, 6e5de1de3fd4)

Likely related people:

  • steipete: 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 (4 earlier review cycles)
  • reviewed 2026-10-03T10:43:18.568Z sha f69fe0f :: blocked before merge. :: none
  • reviewed 2026-10-03T10:50:04.483Z sha f69fe0f :: blocked before merge. :: [P2] [P2] Include the transition worker's transitive wrapper imports | [P2] [P2] Await the remaining worker-owned integration transitions | [P2] [P2] Synchronize duplicate recovery coverage with abort admission | [P2] [P2] Preserve bookkeeping after accepted failed-worker teardown | [P2] [P2] Update the abandonment spy for the forwarded authority argument
  • reviewed 2026-10-03T11:12:14.566Z sha 6e5de1d :: blocked before merge. :: none
  • reviewed 2026-10-03T11:26:38.236Z sha 6e5de1d :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
Await remaining fixture transitions, settle duplicate recovery before asserting, and keep the standalone wrapper free of the application command worker. Finish admitted failed-worker teardown after caller revocation while preserving authorization for new Gateway materialization.
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 3, 2026
@steipete
steipete merged commit 063685e into main Oct 3, 2026
170 checks passed
@steipete
steipete deleted the dbasync/placetrans branch October 3, 2026 11:53
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…workers (openclaw#164252)

* refactor(gateway): move placement transition writes into workers

Run transitions, drain/reconcile and terminal failure settlement through
placementTurns and the existing shared-state writer. Preserve exact claims,
physical store identity, live grants, publication order and unknown-outcome
custody. Keep the current terminal-failure policy unchanged.

Validation: changed-file gate, 297 focused tests, database-worker ratchet,
zero import cycles and independent Codex review through P2.

* fix(gateway): preserve placement settlement through async cutover

Await remaining fixture transitions, settle duplicate recovery before asserting, and keep the standalone wrapper free of the application command worker. Finish admitted failed-worker teardown after caller revocation while preserving authorization for new Gateway materialization.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts 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