Skip to content

perf(gateway): eliminate local placement claim round trips - #178098

Merged
steipete merged 3 commits into
mainfrom
dbasync/statefuse
Oct 20, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/statefuse

Conversation

@steipete

@steipete steipete commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • Accepted edge: direct SQL readers of worker_session_placements no longer see plain-local turn_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.
  • Accepted edge: a crash loses the process-local claim immediately; restarted placement readers see no active local owner. Committed dispatch progress and publication receipts remain durable and use their existing recovery paths.
  • Accepted edge: a session used only for plain-local turns may have no durable placement row after restart. getAsync/listAsync then 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.
  • Accepted edge: a shared GitHub publication request accepted by the final source-admission grant may finish recording after its plain-local turn releases. Recording is bookkeeping; the GitHub executor still checks current requester and workspace authority before external effects.
  • Accepted edge: a local turn that releases after shared-publication orphan recovery captures its claim snapshot retains its publication claim until the next recovery pass. That retained receipt grants no additional execution authority.

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 flags formatKeyboardShortcutCombo and DirectDictationTextarea, full-tree flags only DirectDictationTextarea, scripts has no findings. Three UI line suppressions and core graph-root limits are also inherited; no baseline was relaxed. Exact repaired head 744fe651c18ab0493f948a803d98f53f464d4261 has renewed PostgreSQL/authority approval and passes all three PostgreSQL conformance shards in CI run 39381449375.

Measured base a860374eede6b95d64200a97e28e8940aeb0469f → candidate a590cfacdf5ceab5df3994b8dd37345339c1b1fb; frozen v3.1, M,C ×3.

Phase Base SQL / requests / MAIN median [range] Candidate SQL / requests / MAIN median [range]
Whole workload 3087 [3080–3100] / 855 [851–855] / 98 [98–99] 3045 [3045–3081] / 822 [820–843] / 98 [98–98]
Warm causal turn 51 [51–51] / 15 [15–15] / 0 [0–0] 49 [49–49] / 13 [13–13] / 0 [0–0]
Connect + first turn 523 [521–536] / 125 [122–128] / 0 [0–0] 523 [522–525] / 124 [123–125] / 0 [0–0]
Second session / spawn 490 [489–495] / 127 [126–128] / 0 [0–0] 485 [484–485] / 121 [120–121] / 0 [0–0]
Warm request family Base SQL / requests Candidate SQL / requests
appendSqliteTrajectoryRuntimeEventsWithWriter 1 / 1 1 / 1
batch 11 / 1 11 / 1
commitSessionEntryPatch 4 / 1 4 / 1
placementTurns.claim 1 / 1 0 / 0
placementTurns.releaseIfOwned 1 / 1 0 / 0
prepareTranscriptPayload 18 / 2 18 / 2
record-event 2 / 2 2 / 2
recordProviderPrompt 0 / 1 0 / 1
session.messageRewrite.modelPrompt 5 / 1 5 / 1
statement 1 / 1 1 / 1
trackSessionEntryCacheWrite 7 / 2 7 / 2
withTranscriptLockSettlement 0 / 1 0 / 1

Representative 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/failed progress; 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 is UPDATE ... 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. runSqliteSingleStatementSync already routes PostgreSQL through that owner. After: both transactions disappear. The estimate counts BEGIN and 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-claim UPDATE ... RETURNING *, worker-tool cleanup where applicable, pending-workspace-result selection and commit admission. On PostgreSQL, runPostgresTransactionSync acquires 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_SCOPE exclusion. 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 SELECT with 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

  1. Per-engine statements, request counts and boundaries are described above. Retained PostgreSQL writes lock before authoritative reads; measured counts are above and renewed exact-head PostgreSQL approval and conformance are complete.
  2. Every write transaction stays in one store. Asynchronous preparation precedes it; authoritative durable rows are read under its transaction owner.
  3. Participant recording and the inheritance joins in session-create-inheritance.ts, subagent-spawn-request.ts and acp-spawn.ts retain their existing visibility point.
  4. completeTurn and final entry-patch rollback are unchanged.
  5. Audit start/end retain their existing behavior; audit batching is separate work.
  6. Mixed local/remote exclusion remains under the placement owner. Local claims check its reservation; dispatch reserves before awaiting and preserves the predecessor until release; remote admission requires the durable environment/state/epoch predicates. PERSONAL_SCOPE also 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.

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.
@clawsweeper

clawsweeper Bot commented Oct 20, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T06:52:42.216549Z 744fe65 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: XL labels Oct 20, 2026
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 744fe651c18ab0493f948a803d98f53f464d4261
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/gateway/worker-environments/placement-authority-owner.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/placement-turn-authority.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.
  • src/gateway/worker-environments/placement-turn-authority.types.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This 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.

  • Before: Claim and release require two state-worker requests and two SQLite writes.
  • After: The existing placement owner handles both operations without SQL or worker requests.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful owner-approved optimization, but concrete consumer regressions and incomplete authority and upgrade evidence prevent a pass.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) Security review found an item that needs attention.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary local turns incur avoidable placement bookkeeping through the database worker.
Reason: The feature owner approved the direction and expressly accepted the visibility and restart tradeoffs; removing two warm-path worker requests has concrete value.

Regression provenance

Possible 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
Reviewed head: a590cfacdf5ceab5df3994b8dd37345339c1b1fb

Before merge

  • Add real behavior proof - Authority-chain proof required: exercise the changed local-claim admission and durable publication recovery with an allowed requester, then revoke or reassign that requester and demonstrate rejection before GitHub I/O. Supplied owner tests and mocked publication commands do not establish that final boundary. The body explicitly leaves Gateway workload measurements and exact-head PostgreSQL conformance pending; no latest-stable upgrade run establishes compatibility of existing claims and publication receipts. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Overlay local claim authority in environment-owner reads (P2) - readEnvironmentOwner still returns the database placement directly. Once a failed placement retains a process-local predecessor claim, this returns turnClaim: null even though the placement owner retains the claim. installWorkerPlacementReconcileGuard uses that field to block provider reconciliation, so cleanup can proceed while the claim remains active. Exact-head CI records the unexpected destroy callback in server-worker-placement-startup-cleanup.test.ts:480. Apply the existing owner overlay before returning this reader's result.
  • Detach public placement results after applying the local overlay (P2) - The warm getManyAsync path clones its cached placement and then calls decorate, which replaces the clone's turnClaim with the owner's deeply frozen claim. After claimTurn, assigning to (await store.getAsync(sessionId)).turnClaim.claimId therefore throws instead of modifying the caller-owned result. Owner-only list/getWithMove results can also expose the frozen placement itself. Preserve the public mutable-result contract by copying at the public adapter after the overlay, while keeping internal owner facts frozen.
  • Migrate the remaining plain-local SQL fixture caller (P2) - The new rejection removes plain-local support from createPlacementTurnClaimOps, but session-row-projection.entry-placement.test.ts:122 still calls it through createPlacementTurnClaimFixtureOps with owner.kind local and no environment. The test now fails at this throw, as confirmed by exact-head CI. Move that case to the existing placement owner and retain its projection assertion using a supported publication path.
  • Resolve security review attention item - Source retains effect-time requester and workspace guards, but recovered publication authority needs final-effect validation.
  • Resolve merge risk - Persisted publication receipts now survive their process-local claim, but rejection of a revoked or reassigned requester before a resumed GitHub effect has not been demonstrated.
  • Complete next step - Attribute the test-types failure and update remaining consumer tests whose persistence or rejection expectations changed, preserving their independent contracts.
  • Improve patch quality - Show allowed publication recovery and rejection after requester revocation or reassignment before the final GitHub effect.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Public placement result mutability - a13e869: Public SDK results must remain independently mutable without altering retained owner facts.

Findings

  • [P2] Overlay local claim authority in environment-owner reads — src/gateway/worker-environments/placement-store.ts:352
  • [P2] Detach public placement results after applying the local overlay — src/gateway/worker-environments/placement-read-store.ts:23-25
  • [P2] Migrate the remaining plain-local SQL fixture caller — src/gateway/worker-environments/placement-turn-claims.ts:117-119

Provenance

  • Public placement result mutability changes intended behavior without addressing why it exists (a13e869: Public SDK results must remain independently mutable without altering retained owner facts.)

Tests

  • Missing end-to-end proof: Supply the pending Gateway workload and PostgreSQL results, latest-stable upgrade/restart coverage with receipts intact, and allowed-versus-revoked publication recovery through the final effect; the warm work-count base-red result is already reported.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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:

  • [P2] Overlay local claim authority in environment-owner reads — src/gateway/worker-environments/placement-store.ts:352
    readEnvironmentOwner still returns the database placement directly. Once a failed placement retains a process-local predecessor claim, this returns turnClaim: null even though the placement owner retains the claim. installWorkerPlacementReconcileGuard uses that field to block provider reconciliation, so cleanup can proceed while the claim remains active. Exact-head CI records the unexpected destroy callback in server-worker-placement-startup-cleanup.test.ts:480. Apply the existing owner overlay before returning this reader's result.
    Confidence: 0.97
  • [P2] Detach public placement results after applying the local overlay — src/gateway/worker-environments/placement-read-store.ts:23-25
    The warm getManyAsync path clones its cached placement and then calls decorate, which replaces the clone's turnClaim with the owner's deeply frozen claim. After claimTurn, assigning to (await store.getAsync(sessionId)).turnClaim.claimId therefore throws instead of modifying the caller-owned result. Owner-only list/getWithMove results can also expose the frozen placement itself. Preserve the public mutable-result contract by copying at the public adapter after the overlay, while keeping internal owner facts frozen.
    Confidence: 0.99
  • [P2] Migrate the remaining plain-local SQL fixture caller — src/gateway/worker-environments/placement-turn-claims.ts:117-119
    The new rejection removes plain-local support from createPlacementTurnClaimOps, but session-row-projection.entry-placement.test.ts:122 still calls it through createPlacementTurnClaimFixtureOps with owner.kind local and no environment. The test now fails at this throw, as confirmed by exact-head CI. Move that case to the existing placement owner and retain its projection assertion using a supported publication path.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Verify resumed publication authority (recommended)
    Exercise an accepted local publication receipt through recovery, showing allowed execution and rejection after requester revocation or reassignment before GitHub I/O.

Provenance checked

  • Plain-local claim and release durability changes intended behavior with a stated reason (91082d3: The prior optimization retained conditional durable DML and committed publication while removing SQLite transaction envelopes.)
  • Placement authority and lifecycle ownership keeps the original intent (8d86209: The placement owner retains committed postimages while worker operations own durable changes and effect-time guards retain live authority.)
  • GitHub publication admission and recovery changes intended behavior with a stated reason (5b24226: Workers own durable publication receipts while coordinators retain execution, workspace exclusion, and requester authority.)

Testing

Proof path: in-process harness.

Security

Needs attention: Source retains effect-time requester and workspace guards, but recovered publication authority needs final-effect validation.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3ed4948 adds src/gateway/worker-environments/placement-turn-claims-store.ts:40 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3ed4948024e3; files: src/gateway/worker-environments/placement-turn-claims-store.ts)

PR surface

Source +357, Tests +55, Docs +1. Total +413 across 26 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 19 623 266 +357
Tests 6 294 239 +55
Docs 1 12 11 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 929 516 +413

Review metrics

Metric Value Why it matters
Production versus test changes Production +623/−266; tests +294/−239 Growth implements local admission, settlement, reader overlays, and publication recovery under the existing owner; no unnecessary parallel manager was identified.

Labels

Label changes:

  • add P2: This is a normal-priority optimization with concrete reader and consumer regressions to repair before merge.
  • add merge-risk: 🚨 compatibility: Public placement results acquire frozen owner references despite the documented mutable-result contract.
  • add merge-risk: 🚨 security-boundary: Local publication admission moves out of SQL while durable receipts can outlive the claim; final-effect revocation evidence is required.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: This is a normal-priority optimization with concrete reader and consumer regressions to repair before merge.
  • merge-risk: 🚨 compatibility: Public placement results acquire frozen owner references despite the documented mutable-result contract.
  • merge-risk: 🚨 security-boundary: Local publication admission moves out of SQL while durable receipts can outlive the claim; final-effect revocation evidence is required.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 20, 2026, 2:02 AM ET / 06:02 UTC.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +131 to +134
const pending = owner.localMutationSettlements.get(claim.sessionId);
if (pending?.size) {
await Promise.all(pending);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

@steipete
steipete merged commit 4e72ef2 into main Oct 20, 2026
163 of 164 checks passed
@steipete
steipete deleted the dbasync/statefuse branch October 20, 2026 07:04
steipete added a commit that referenced this pull request Oct 20, 2026
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.
steipete added a commit that referenced this pull request Oct 20, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
…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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
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.
steipete added a commit that referenced this pull request Oct 21, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
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.
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: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. security-sensitive-changed size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant