Repository navigation
perf(gateway): offload placement turn claims from the main thread - #158486
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 25, 2026, 10:16 PM ET / September 26, 2026, 02:16 UTC (Revision 6). ClawSweeper reviewWhat this changesThe branch moves Gateway placement turn claims and releases to the shared-state SQLite worker, updates callers to await them, and adds authority, recovery, and worker-access coverage. Merge readiness⛔ Blocked before merge - 2 items remain Keep open. Current main still performs placement claims and releases synchronously, and no merged PR replaces this worker offload. The latest commit only corrects test typing. No actionable defect was found; the measured latency cost has been explicitly accepted in the maintainer discussion. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway admits each local or cloud worker turn by recording an exclusive placement claim in shared state. That claim controls turn execution and must be released before another turn or a cloud dispatch can take over. flowchart LR
A[Incoming chat turn] --> B[Gateway placement admission]
B --> C[Shared-state worker]
C --> D[SQLite placement claim]
D --> E[Local or cloud execution]
E --> F[Exact-claim release]
F --> G[Next turn or dispatch]
Before merge
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep one placement owner using the shared-state broker for ordinary claims and releases, with live-authority fencing and exact-claim cleanup preserved as the separate dispatch recovery work evolves. Do we have a high-confidence way to reproduce the issue? Yes, at source level: current main calls the synchronous placement claim kernel from the Gateway, and the PR records an instrumented main-thread profile. This read-only review did not rerun the benchmark. Is this the best way to solve the issue? Yes. Moving the existing claim kernel through the shared-state writer follows the repository's worker-access contract while retaining the placement owner and its exact-claim barrier. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 873dbf97afbd. 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 (5 earlier review cycles)
|
|
|
@clawsweeper re-review Published |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Final head: |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Final head |
|
🦞👀 Re-review progress:
|
|
Merged via squash auto-merge.
|
…enclaw#158486) * perf(gateway): move placement turn claims off the main thread * test(gateway): drain placement workers before fixture cleanup * test(gateway): run placement claims through the host broker lane * test(agents): await the observed placement claim * fix(gateway): preserve placement claim transport boundaries * fix(gateway): retain turn cleanup through coordinator contention * fix(gateway): resolve placement claim CI lint failures * test(gateway): preserve placement waiter parameter types --------- Co-authored-by: Jason Sy <[email protected]>
What Problem This Solves
Concurrent turns block the Gateway main thread while placement claims acquire the shared-state coordinator and execute SQLite transactions. The main-isolate profile recorded 2,337 ms in SQLite
exec; its heaviest recorded stack (922 ms) was local-turn settlement through claim release and coordinator acquisition.User Impact
Turn admission and settlement await the shared-state worker, keeping claim/release SQLite work off the Gateway thread. Local-to-cloud dispatch barriers, live claim authority, exact-owner release, and restart recovery remain intact. No protocol, configuration, database schema, retention, or operator migration changes are required.
Why This Change Was Made
Local claims are necessary: cloud dispatch closes admission, interrupts local work, and waits for its exact claim before preparing the workspace. This moves the existing claim/release kernel through the shared-state broker instead of deleting that barrier. The broker retains FIFO and native settlement; live checks run at transaction and commit admission. Committed receipts publish authority and closure events even after a lost ordinary reply, and delayed receipts cannot revoke a later claim incarnation. Claim commands carry only declared data fields, and production activity timestamps are taken in the worker transaction.
Local forced completion and ordinary cleanup join one pending release. All affected callers await the async API. Tests use the existing process-based database-worker lane and drain workers before deleting fixtures. Native kernels remain for synchronous transaction composition and the existing workspace/recovery operations.
Related: #158467 migrates dispatch rather than per-turn claims. It overlaps the placement authority owner; when combining the changes, dispatch publication should use the same staged publication sequencing rather than adding an independent revision mechanism. #158120 only overlaps the shared worker command registries with an unrelated secret-store command.
Evidence
Original-head evidence (
dfca52f5)A warm component benchmark alternated native and worker claim/release pairs (A/B/A/B, four rounds of 100 pairs, same isolated database, Node 26.9.0 on a heavily loaded macOS host). Medians:
execcallsThis establishes removal of blocking SQLite/coordinator work. The isolated pair takes longer through the worker; it does not establish an end-to-end latency or CPU reduction. No full build or new swarm run was performed.
Final focused tests on Blacksmith Testbox
tbx_01m3dd8rv1xhpmgqpan8x18pfd, with candidate source hashes verified (node scripts/run-vitest.mjs <file> --maxWorkers=1):placement-turn-claims.worker.test.tsplacement-idle-sweep.test.tsgithub-personal-publication.test.tsserver.sessions.worker-placement-lifecycle.test.tsThe new worker tests exercise real broker admission, no host SQL/coordinator exec, FIFO, stale conditional release, precommit revocation, lost replies, and delayed publication across same-byte readmission. Most of the new file's wall cost was transformation; its six cases used about 1.4 s. The larger existing integration files exercise the real publication and session lifecycle boundaries.
A broader 70-file run took 515.66 s: 1,155 passed and six initially failed. Those failures exposed the extra-callback cloning defect, an omitted deletion waiter, and a stale idle-reclaim scheduling assumption. All three affected files pass after the owner/fixture fixes above. Initial thread-pool routing and fixture cleanup were also corrected; a missing await found by test typechecking was fixed.
node scripts/check-changed.mjs -- <changed files>passed formatting, the guards through dead-export scanning, production typing, all 25 core-test typecheck shards, extension-test typing, and test-root typing. The combined remote validation command ended with exit 255 after 32m22s just after core lint started; no lint diagnostic or completed lint result was returned, and the native provider reports the lease completed. Core lint and later guard steps remain unverified. This is recorded as an environment limitation; hosted PR CI remains authoritative and is not being awaited for this coordinator handoff. Provider run: https://github.com/openclaw/openclaw/actions/runs/36199851901.Production LOC: +522 / -52 (net +470). Tests, fixtures, and test routing: +912 / -621 (net +291). Docs: +10. Growth is required for worker transport, commit receipts, delayed-publication fencing, and uncertain-outcome custody; the authoritative SQL kernel is reused without duplicating its policy.
Deslop completed. Fresh independent Codex branch autoreview is scoped-clean at P0/P1, with no accepted/actionable findings. Earlier review attempts failed authentication before assessment; selecting the existing configured API route resolved that tooling issue.
Startup-failure cleanup correction (
b4bf4249c291)A failed local backend startup can encounter coordinator contention again while releasing its claim. The original PR handled committed releases with lost replies but still stranded a release that never committed. The correction retains the exact conditional-release obligation across typed precommit state-lifecycle contention, rechecks the captured database authority, and never replays the failed input or an uncertain write. Forced and ordinary completion share the same settlement promise, including a terminal refusal.
The inherited architecture-check failure is also fixed by moving the existing claim-input type into its leaf record contract. No configuration/default, wire protocol, stored schema, or migration changes are introduced. Peter Steinberger's original implementation and commit ancestry are preserved.
Verification of the correction
tbx_01m3dn3bwd7hdkcdhvsy80kebv, Linux Node 24.19.0, pinned pnpm 12.4.2: synthetic external CLI exits once after acquiring a real coordinator lock held for 6.5 seconds. On uncorrecteddfca52f5, the nextchat.sendfails with an active claim after unlock. On corrected production bytes, the next request succeeds, its assistant reply is inchat.history, and a fresh SQLite read shows the durable claim cleared. This is real Gateway/SQLite/broker proof, not live model inference.Same-host concurrency measurement
A controlled comparison keeps the Gateway and callers fixed and switches between the original synchronous claim kernel (including its equivalent conditional validate/release composition) and the worker-backed candidate. Each lane warms its Gateway, then completes 12 fixture turns in batches of four with concurrent health RPCs. The external executable is synthetic. This small workload is evidence of the tradeoff, not a production latency guarantee.
The offload removes main-thread claim SQLite work and reduces the worst observed stall, but this first concurrent sample is slower overall. No across-the-board latency or CPU improvement is claimed. The persistent cleanup repair and exact authority barriers are verified independently of that measurement. The temporary slow Gateway/benchmark fixtures are not added to per-PR CI.
Independent API-based review of the complete final candidate is scoped-clean through P2; all actionable findings were corrected before this commit.
Landing review decision and CI correction (
c64696d4461b)For this requested landing, accept the bounded measured latency cost: retaining the exact cleanup obligation and removing synchronous claim/coordinator SQLite work from the Gateway main thread are the priority. The measured slower turn/health p95 is explicit above; no general speedup is claimed. This follows ClawSweeper's recommendation after it found no actionable code defects. Configuration, protocol and stored-data compatibility are unchanged; no migration or operator action is needed.
Exact-head CI exposed four inherited lint errors. The follow-up only renames a shadowed local, preserves caught causes in existing aggregate errors, and forwards a test method through its store receiver. Focused type-aware lint is clean (21.2s); all 44 claim/lifecycle tests pass (92.26s command wall). Independent API review of this delta is clean through P2. The full touched lifecycle-test file was audited and its distinct failure/race/state-preservation cases retained. Final-head hosted CI and a fresh Crabbox replay remain pending, not assumed passed.
Final contention proof and test typing
c64696d4461bBlacksmith Testbox proof: all eight relevant source hashes matched; focused lint and 44 worker/lifecycle tests passed. The real isolated Gateway recovery test passed with a 6.5-second coordinator lock: the failed startup ran once, the nextchat.sendsucceeded,chat.historyretained its reply, and a fresh readonly SQLite query confirmed the claim was clear. Command exit 0. The lease is stopped.ce5e5075dd3ccorrects only the lifecycle test callback parameter types exposed by the full CI typecheck. It derives the tuple from the existing store method and preserves the receiver/return contract. Independent delta review and focused lint are clean; the affected Gateway-server type graph passed (51.8s), focused lint passed (23.1s), and all three targeted deletion tests passed in Blacksmith Testbox (command exit 0; lease stopped). Its source-capsule tree exactly matches the final published tree. Production bytes are unchanged from the verified recovery run.unknown-truncated-pull-filesdo not identify an actual data-model change.Landed
Merged as
3ed4948024e3a9df038db0f67b36f3491a604f07after the exact-head CI gate passed and the completed independent and ClawSweeper reviews found no actionable code/security defects. The documented bounded latency tradeoff is retained. This upstream landing does not update or restart any deployed Gateway.