Repository navigation
perf(gateway): eliminate local placement claim round trips - #178098
Conversation
Move local claim admission, release, reader projections and publication reservations into the existing placement owner. Keep remote claims and dispatch/publication receipts durable; remove local claim/release worker writes. Local claims disappear on restart, matching startup cleanup; direct SQL readers no longer observe them.
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
|
Codex review: needs real behavior proof before merge. What this changesThis PR moves plain-local placement claims into the existing Gateway owner while retaining durable remote claims and publication receipts. Example: A warmed local turn acquires claim local-claim-1 and releases it.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Regression provenancePossible regression — probable (reviewed change; failure trace). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 10 items remain Keep this PR open: the owner-approved optimization has value, but the reader cutover breaks recovery visibility and mutable placement results, and an existing fixture still calls the removed SQL path. Priority: P2 Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherThe placement subsystem admits session turns and coordinates dispatch, workspace exclusion, recovery, and publication; callers supply session and claim identities and receive placement facts and live authority checks. flowchart TD
A[Session turn] --> B[Placement owner]
B --> C[Local claims in memory]
B --> D[State worker]
D --> E[Durable remote claims and receipts]
B --> F[Placement readers and recovery]
E --> G[GitHub publication executor]
Technical reviewBest possible solution: Complete the cutover through the existing placement owner, detach public results after applying owner facts, and preserve durable recovery and final-effect authorization. Do we have a high-confidence way to reproduce the issue? Source confirms the existing worker round trips and the introduced reader defects; exact-head CI independently records recovery and fixture failures, and no target code was executed during this review. Is this the best way to solve the issue? Using the existing placement owner is appropriate, but the cutover must cover every authority reader and preserve mutable public adapters. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 4fe2305c6708. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: Source retains effect-time requester and workspace guards, but recovered publication authority needs final-effect validation. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +357, Tests +55, Docs +1. Total +413 across 26 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 20, 2026, 2:02 AM ET / 06:02 UTC. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 744fe651c1
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const pending = owner.localMutationSettlements.get(claim.sessionId); | ||
| if (pending?.size) { | ||
| await Promise.all(pending); | ||
| } |
There was a problem hiding this comment.
Drain newly accepted mutations before releasing the local claim
When releaseTurn is already awaiting one settlement, another permitted same-session mutation—such as placementTurns.fail or a second dispatch—can add a promise to localMutationSettlements; Promise.all(pending) snapshots the set only once, so the release can publish turnClaim: null, wake release waiters, and let dispatch continue while that later accepted write is still unsettled. Keep draining until the settlement set is empty, or close mutation admission before taking the snapshot, so every accepted write is settled before claim release.
AGENTS.md reference: AGENTS.md:L95-L95
Useful? React with 👍 / 👎.
Plain-local claims moved into the Gateway placement owner in #178098. Startup cleanup clears legacy persisted claims, so it cannot release the live claim used to arrange this stale-finally regression. Release the captured claim through the current owner before reusing its run ID. Keep the replacement-identity and final-cleanup assertions; the negative control still fails if the claim-ID fence is removed.
Replay real chat and session.message frames through the existing Control UI consumers. Require a cleared live run, stream and segments, and require the displayed assistant messages to match persisted history exactly. Preserve the saved partial, publication, terminal failure receipt, fallback, request-count and settled-write assertions. The transcript publication barrier can release a terminal in place of a held clearing delta. The previous delta-only fold missed that canonical handoff; in-process local claim release in #178098 exposes this ordering more readily. The publication contract itself predates the window in #174087. Both affected real-Gateway files pass on Node and pinned Bun. Targeted test-graph typecheck, lint and formatting pass, and independent P0-P2 review is clean.
…178098) Keep plain-local turn claims, reservations, dispatch handoff and release under the existing Gateway placement owner. Route placement and personal publication readers through owner facts while retaining durable remote claims and dispatch/publication recovery. Accepted edge: local-only turn claims disappear on process exit and no longer appear in raw SQL; startup already discards these leases. Preserve live local predecessors in startup cleanup reads and detach caller-owned results. Three alternating frozen workload pairs measure warm turns at 51 SQL / 15 requests -> 49 / 13, with 0 main-thread SQL. Attributable whole-workload savings are 33 SQL and 34 requests. Focused owner, recovery and consumer tests and independent Codex review cover the change.
Plain-local claims moved into the Gateway placement owner in openclaw#178098. Startup cleanup clears legacy persisted claims, so it cannot release the live claim used to arrange this stale-finally regression. Release the captured claim through the current owner before reusing its run ID. Keep the replacement-identity and final-cleanup assertions; the negative control still fails if the claim-ID fence is removed.
Replay real chat and session.message frames through the existing Control UI consumers. Require a cleared live run, stream and segments, and require the displayed assistant messages to match persisted history exactly. Preserve the saved partial, publication, terminal failure receipt, fallback, request-count and settled-write assertions. The transcript publication barrier can release a terminal in place of a held clearing delta. The previous delta-only fold missed that canonical handoff; in-process local claim release in openclaw#178098 exposes this ordering more readily. The publication contract itself predates the window in openclaw#174087. Both affected real-Gateway files pass on Node and pinned Bun. Targeted test-graph typecheck, lint and formatting pass, and independent P0-P2 review is clean.
4e72ef2 (#178098) moved plain-local turn claims into the in-process Gateway placement owner, so sessions used only for local turns no longer write worker_session_placements rows. Two e2e tests kept reading raw SQL and have been red on main since: the five explicit global-ownership cases in gateway-rpc-chat (expected [] to equal both owners' local rows) and scheduled cron retirement (expected undefined to match a live local claim). The child-process chat test now reads each owner's row through sessions.describe (agent, key, canonical session id, local placement, no active run). Because session rows do not expose the turn claim, it also runs one more agent turn per owner: a leaked local claim rejects that claim with ActiveTurnClaimError. The in-process cron test reads through createWorkerSessionPlacementStore, which shares the placement authority owner, keeping its live-claim, drain-retention and retirement checks. Proof: the ownership cases fail 5/5 on main fbc99b8 and at 4e72ef2, and pass 5/5 on its parent c34e0c9 with the old assertion; all 9 pass with this change. Cron retirement fails on main and passes with this change.
2826ddc (openclaw#178098) moved plain-local turn claims into the in-process Gateway placement owner, so sessions used only for local turns no longer write worker_session_placements rows. Two e2e tests kept reading raw SQL and have been red on main since: the five explicit global-ownership cases in gateway-rpc-chat (expected [] to equal both owners' local rows) and scheduled cron retirement (expected undefined to match a live local claim). The child-process chat test now reads each owner's row through sessions.describe (agent, key, canonical session id, local placement, no active run). Because session rows do not expose the turn claim, it also runs one more agent turn per owner: a leaked local claim rejects that claim with ActiveTurnClaimError. The in-process cron test reads through createWorkerSessionPlacementStore, which shares the placement authority owner, keeping its live-claim, drain-retention and retirement checks. Proof: the ownership cases fail 5/5 on main f440237 and at 2826ddc, and pass 5/5 on its parent 4dca31e with the old assertion; all 9 pass with this change. Cron retirement fails on main and passes with this change.
What Problem This Solves
Ordinary local turns perform two avoidable database writes and state-worker round trips to claim and release their placement.
User Impact
User impact: warmed local turns acquire and release placement through the Gateway's existing owner, with zero SQL statements or worker requests for that pair. Remote worker and remote-exec claims remain durable; no configuration or migration is required.
The following timing and visibility changes are accepted:
worker_session_placementsno longer see plain-localturn_claim_*values or timestamps caused solely by local claim/release. Gateway placement APIs and authority projections see the owner-published claim; their notifications can arrive before the former asynchronous worker-reply boundary.getAsync/listAsyncthen return no placement instead of a cleared local row; its next local turn creates the in-process placement. Remote affinity and committed dispatch progress remain durable.Why This Change Was Made
The Gateway owns the lifetime of plain-local claims (
owner.kind === "local" && owner.environmentId === undefined), and startup already clears abandoned local claims. The existing placement owner now supplies their authoritative state. A cold owner can still load an existing placement once; warmed claims need no freshness query.This moves the complete responsibility: placement reads and authority projections consume owner facts, dispatch and GitHub workspace reservations close admission before awaiting, durable dispatch receipts retain the draining local predecessor, and release joins accepted lifecycle mutations before notifying waiters. Retirement also handles owner-only placements. Shared GitHub publication validates local claims at its existing final source grant and carries live-local claims in its existing orphan-recovery request.
Multi-process safety comes from root custody (Gateway lock, embedded lock, local-state owner, maintenance); a foreign process constructing its own placement store is out of contract.
The plain-local SQL UPSERT/release branches and unused receipt-staging path are deleted. Remote claims retain their conditional SQL, transaction admission, exact-claim release and commit receipts. There is no schema or cross-store transaction change.
Evidence
Three alternating frozen-v3.1 pairs completed with clean source/build pins and no surviving fixture processes. All 60 causal warm turns have the same counts within their side: 51 SQL / 15 requests / 0 MAIN → 49 / 13 / 0. Every pair removes 17 claims and 17 releases over the whole workload (−34 SQL, −34 requests). Owner-only retirement adds one statement and no request, for an attributable net −33 SQL / −34 requests. The second pair's raw whole-workload SQL increases by one; raw totals include unrelated timed work and are not used to inflate the attributable saving. Latency is unmeasured on this loaded host.
The five shared-read families have no causal warm reads on either side. Whole-workload SQL medians [range] are exact-entry 18 [18–19] → 18 [18–19], actor hydration 10 [10–10] → 10 [10–10], entry-cache snapshots 7 [7–7] → 7 [7–7], row facts 19 [19–21] → 19 [19–19], and watermarks 4 [4–4] → 4 [4–4].
The warm work-count regression fails on the base for the intended reason: two worker requests instead of zero. Initial focused owner/publication/recovery proof passed 146 tests in seven files. Initial CI 39375163837 passed all three PostgreSQL conformance shards but found a real missing owner overlay in the startup cleanup reader, plus stale consumer fixtures. The repair overlays that reader and preserves detached caller-owned results. Main was integrated for its unrelated UI type-error fix (#178096).
Measurement scope: the six-arm results below are pinned to the initial implementation, before the reader repair and main integration. The repair changes an environment-owner read that does not execute in any measured arm, plus returned-object ownership and tests; it changes no SQL or request shape. The second and final Codex P0–P2 review is scoped-clean. The repaired head passes all 125 focused owner, recovery and consumer tests, including the zero-request regression and startup provider-safety case. Production and affected test typechecks, changed-file type-aware lint, formatting, source/worker/dialect contracts, Madge and Knip files/dependencies pass. The export scan is identical on integrated main
f4484758021: production flagsformatKeyboardShortcutComboandDirectDictationTextarea, full-tree flags onlyDirectDictationTextarea, scripts has no findings. Three UI line suppressions and core graph-root limits are also inherited; no baseline was relaxed. Exact repaired head744fe651c18ab0493f948a803d98f53f464d4261has renewed PostgreSQL/authority approval and passes all three PostgreSQL conformance shards in CI run 39381449375.Measured base
a860374eede6b95d64200a97e28e8940aeb0469f→ candidatea590cfacdf5ceab5df3994b8dd37345339c1b1fb; frozen v3.1, M,C ×3.appendSqliteTrajectoryRuntimeEventsWithWriterbatchcommitSessionEntryPatchplacementTurns.claimplacementTurns.releaseIfOwnedprepareTranscriptPayloadrecord-eventrecordProviderPromptsession.messageRewrite.modelPromptstatementtrackSessionEntryCacheWritewithTranscriptLockSettlementRepresentative exact causal request order (second warm turn):
M1: withTranscriptLockSettlement (0 SQL), batch (11 SQL), statement (1 SQL), trackSessionEntryCacheWrite (3 SQL), placementTurns.claim (1 SQL), prepareTranscriptPayload (8 SQL), record-event (1 SQL), session.messageRewrite.modelPrompt (5 SQL), recordProviderPrompt (0 SQL), prepareTranscriptPayload (10 SQL), placementTurns.releaseIfOwned (1 SQL), appendSqliteTrajectoryRuntimeEventsWithWriter (1 SQL), record-event (1 SQL), commitSessionEntryPatch (4 SQL), trackSessionEntryCacheWrite (4 SQL).
C1: withTranscriptLockSettlement (0 SQL), batch (11 SQL), statement (1 SQL), trackSessionEntryCacheWrite (3 SQL), prepareTranscriptPayload (8 SQL), record-event (1 SQL), session.messageRewrite.modelPrompt (5 SQL), recordProviderPrompt (0 SQL), prepareTranscriptPayload (10 SQL), record-event (1 SQL), appendSqliteTrajectoryRuntimeEventsWithWriter (1 SQL), commitSessionEntryPatch (4 SQL), trackSessionEntryCacheWrite (4 SQL).
Crash recovery, PostgreSQL transaction shapes, ownership checklist and change size
Crash recovery
Previously, a crash between local claim and release commits left a persisted claim for startup to clear. The claim now disappears with its owner. A crash after durable dispatch commits still leaves
requested/failedprogress; the vanished local predecessor no longer blocks existing startup recovery. Before dispatch commits, a crash leaves no new dispatch progress. Startup retains its legacy persisted-local-claim cleanup for upgrades.Publication receipts remain durable. After a crash, the restarted owner has no corresponding local claim, so orphan recovery can clear that receipt's claim and resume through current requester/workspace authority. The accepted snapshot edge can delay this until the next recovery pass.
Per-engine SQL and transaction shapes
SQLite plain-local, before: two separate worker requests, each using the admitted single-statement path. Claim is
INSERT ... SELECT ... WHERE NOT EXISTS(active PERSONAL_SCOPE lease) ON CONFLICT(session_id) DO UPDATE ... WHERE identity/local-state/claim-admissibility RETURNING *. Release isUPDATE ... SET turn_claim_* = NULL, updated_at_ms = ? WHERE exact-claim AND NOT EXISTS(pending-result) AND local/requested/failed-state RETURNING *. The existing helper retains an outer transaction when one owns the connection. After: owner publication only, with zero SQL or requests for warmed claim/release.PostgreSQL plain-local, before: each request uses
BEGIN ISOLATION LEVEL READ COMMITTED→SELECT pg_advisory_xact_lock(...)→ conditional DML →COMMIT.runSqliteSingleStatementSyncalready routes PostgreSQL through that owner. After: both transactions disappear. The estimate countsBEGINand advisory-lock selection as two statements, although the existing transaction owner sends them together; this PR adds no bridge batching.Durable remote claim/release, both engines, before and after: one state-worker request per operation under the existing managed write transaction. Claim retains conditional
UPDATE ... RETURNING *, pending-workspace-result selection and commit admission. Release retains exact-claimUPDATE ... RETURNING *, worker-tool cleanup where applicable, pending-workspace-result selection and commit admission. On PostgreSQL,runPostgresTransactionSyncacquires its advisory lock before entering the callback: the lock precedes the conditional DML's authoritative predicates, diagnostic reads and subsequent state reads. SQLite retains its managed write transaction.Remote predicates retain session/agent/key identity, execution mode, active state (or draining for reclaim), environment/owner epoch, admissible claim tuple and
PERSONAL_SCOPEexclusion. Release retains exact claim, pending-result exclusion and mode/state/environment/epoch constraints, including worker claim epoch. Removing the plain-local alternatives leaves remote stored fields and successful SQL semantics unchanged. All three PostgreSQL conformance shards pass on the repaired head in CI run 39381449375.Shared publication insert: the existing source reservations and destination transaction remain. Plain-local claims replace the destination placement-claim
SELECTwith the final source grant's owner check. Remote-exec and worker claims retain the SQL check. The PostgreSQL destination lock still precedes its authoritative reads.Shared orphan recovery, before: write transaction → select pending receipts → select pending results → select placements → defer selected rows → commit. After: the existing request carries the owner snapshot; claimless rows and matching live-local claims are filtered immediately after receipt selection. If durable candidates remain, the existing reads/writes continue under the same transaction. PostgreSQL locks before receipt selection.
All retained SQL uses the dialect layer. No advisory lock moves into a writable CTE. No transaction spans state and agent databases; synchronous write callbacks contain no await.
PostgreSQL and ownership checklist
session-create-inheritance.ts,subagent-spawn-request.tsandacp-spawn.tsretain their existing visibility point.completeTurnand final entry-patch rollback are unchanged.PERSONAL_SCOPEalso reserves the owner before awaiting SQL leases. The focused tests exercise local-to-dispatch exclusion, worker claims and local-to-remote-exec-to-restart transitions.Change size
Whole change: 30 files, +970 / −527 lines (net +443), including the new local-turn module. Production: +631 / −267 (net +364).
The growth supplies responsibilities previously implicit in SQL: cold placement adoption, local exclusion, accepted-mutation settlement, consistent reader projections, owner-only retirement and publication admission/recovery. These live under the existing owner. The deleted plain-local SQL and receipt-staging paths offset part of that cost.