Repository navigation
fix(gateway): avoid blocking requests on lock polling - #197455
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 Summary: ✅ CompletedThis 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 maintainer review before merge. What this changesThis PR replaces routine synchronous ownership-lock polling with retained owner state and worker observations, while freshly verifying custody before cleanup. Example: A serving Gateway processes a synthetic sandbox workload while holding its root and projection locks.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR addresses a concrete Gateway responsiveness problem, and the earlier ownership and restart-consumer findings are resolved; no actionable defect remains in the reviewed diff. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe state-owner subsystem admits Gateway database operations and cleanup, consuming process custody and physical lock observations to permit work or report ownership loss. flowchart TD
A[Gateway requests] --> B[Registered state owner]
B --> C[Retained liveness guards]
B --> D[Heartbeat worker]
D --> E[Root and projection locks]
D --> B
C --> F[Database effects and cleanup]
Technical reviewBest possible solution: Keep physical verification with the existing heartbeat owner, retain immediate local revocation, and bind cleanup preparation to its original custody. Do we have a high-confidence way to reproduce the issue? Current main synchronously verifies held locks and performs expiry recovery on the caller thread, establishing the blocking path; this read-only review ran no target code. Is this the best way to solve the issue? The change removes duplicate verification through existing owners, preserves request-specific custody, and repairs affected cleanup and restart consumers without adding runtime machinery. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against ff148c221cf5. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource -4, Tests +63, Docs +10, Other +84. Total +153 across 18 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. 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 HistoryReview history (2 earlier review cycles)
Reviewed November 12, 2026, 12:16 AM ET / 05:16 UTC (Revision 3). |
Resolve ordinary database ownership per request while keeping cleanup bound to its captured process owner. Exercise real workspace mutation refusal and successor success, migrate restart loss observation, and keep the PostgreSQL crash fixture clock coherent across worker threads.
|
Addressing all six open items from the review of
The two later PostgreSQL CI failures also share one repaired fixture: its recovery preload now uses the same injected epoch across Gateway threads. The exact failed crash/ACK case passes locally against disposable PostgreSQL 17 (34.98 seconds Vitest, 81.22 seconds full harness), and the cluster was stopped and removed. No synchronous production renewal fallback was restored. Fresh local Codex P0–P2 review: scoped-clean, no accepted/actionable findings in the complete staged candidate. Production delta remains −4 lines; tests are +61 with the matching allocation record. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
The final audit found and repaired one missed consumer assertion on @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
* fix(gateway): avoid blocking requests on lock polling * fix(gateway): preserve request custody across lock observation changes Resolve ordinary database ownership per request while keeping cleanup bound to its captured process owner. Exercise real workspace mutation refusal and successor success, migrate restart loss observation, and keep the PostgreSQL crash fixture clock coherent across worker threads. * test(sandbox): verify worker-observed lock loss
…tbeat age check Upstream a14127f (openclaw#197455) inspects state-owner renewal age with Date.now bound when the heartbeat module loads. The custody-conjecture scenario simulates each crash with vi.resetModules() under a frozen fake clock, so the reloaded heartbeat compares that clock with its worker's real beats and every case failed "renewal is overdue". Keep the real worker, registration and verification; skip only the parent-side wall-clock age check. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tbeat age check Carried to the pure candidate (stage 2) from the chain. Upstream a14127f (openclaw#197455), now merged, checks state-owner renewal age with Date.now bound when the heartbeat module loads. The custody-conjecture scenario simulates each crash with vi.resetModules() under a frozen fake clock, so the reloaded heartbeat compares that clock with its worker's real beats: 26 of 26 cases failed "Gateway state ownership renewal is overdue" at f8ee3d2. Keep the real worker, registration and verification; skip only the parent-side wall-clock age check. Refs openclaw#129388 (cherry picked from commit f2a5c7b) Co-Authored-By: Claude Opus 5.5 <[email protected]>
What Problem This Solves
Fixes Gateway requests and timers synchronously reopening both ownership lock files, allowing a host filesystem stall to block the Gateway event loop.
User Impact
Live Gateway ownership checks now consume the existing owner's state and worker observations. Supported peers still cannot reclaim a live process's exclusive-create lock. Manual lock removal or replacement is detected on the worker's next observation; native and recorded-lease cleanup explicitly await that observation before choosing settlement or loss recovery.
This change removes repeated lock-file probes and synchronous expiry recovery. Selected-path alias validation and offline schema custody retain their existing physical checks; remaining runtime alias I/O is follow-up work.
Why This Change Was Made
The heartbeat worker already owns physical lock verification. Per-effect host rereads duplicated that responsibility. Expired custody now refuses work until asynchronous recovery finishes. Captured cleanup preparation stays bound to the original owner and canonical target, preserving immediate in-process retirement and successor exclusion. Ordinary reusable database handles continue resolving the current owner separately for every request.
Production code: −4 lines. Regression coverage: +63 lines, with an exact allocation record. The existing benchmark gains a filesystem-count mode. No configuration, dependency or SQLite schema changes.
Evidence
24819901d92eeand passes with the fix. Actual child-process contention proves live-owner exclusion, timeout and acquisition after release.8e4f975is green; the later consumer-test repair also has green exact-head CI.pnpm check:changedcompleted. Its three failures were the changed owner's line cap and two benchmark style issues; those were repaired and the failed checks rerun. Core, 29 test type graphs, scripts, dead-export scans and the remaining guards passed. Final affected type graphs and file-scoped lint passed. No inherited failure exception is claimed.43136140646exposed two introduced defects: ordinary reusable access incorrectly pinned a temporary schema owner, and a restart fixture still expected synchronous loss delivery. Restored per-request ownership discovery, retained capture only for cleanup, and migrated the fixture to actual heartbeat-worker loss. No failure is classified as inherited. Local repair proof: 113 owner/heartbeat/alias/lease/transcript tests, the repaired restart case (the other 174 CLI cases already passed), and a frozen 24-test workspace/MCP run pass.GatewayStateOwnerContentionError, the persisted rows and workspace cache remain intact, and successor-authorized deletion removes them. This replaces the previous mocked guard; it adds no test-only production seam. The final workspace/MCP run took 43.69 seconds including compiler reuse and teardown (28.09 seconds in Vitest).pnpm deadcode:unused-filespasses on repair headbe34c44: both production and full-tree scans have zero entries.The same real acquisition and captured-assertion path produced these main-thread JavaScript filesystem-call counts. These are 715 retained assertions, normalized to a fixed operation count, rather than a serving-Gateway minute:
Six count samples per side matched. Separate uninstrumented loops measured median wall time 35.826→1.545 ms and process CPU 37.666→1.840 ms. First two A/A controls were 35.548/37.162 ms before and 1.288/1.415 ms after. Five separate allocation samples measured median 6,970,784→303,408 bytes per 715 assertions. The host had concurrent fixture work, so these are owner-work comparisons, not production latency claims. The later cleanup repair does not change this retained assertion loop.
Rerunnable counter:
scripts/perf/gateway-state-owner-measure.ts --fs-countswith an existing synthetic fixture. Its smoke run reproduced 715 native realpaths and zero lock calls; native-libc and worker calls are excluded. The serving-Gateway comparison below independently confirms the lock-call removal.Serving-Gateway confirmation
Five successful 60-second windows used the same synthetic sandbox workload before and after. The candidate union tree
c922dd3bdf86858aea4f6265f92b98e02171c597includes this PR's production head8e4f97562c03284cba5f396dfd50e06c0eacef09; the subsequent repair changes only a consumer test and its allocation record. The fixture has 5,000 populated/indexed sessions and a materialized synthetic agent database of 37,581,479,936 logical bytes (37,581,709,312 allocated bytes), approximately 35 GiB. Its immutable background project/worktree inventory has 62,000 files × 17,742 bytes, approximately 1.1 GB; the active agent workspace is smaller. The Gateway runs on host APFS with an isolated local Linux Docker sandbox, not a full btrfs Gateway fixture. No production data was copied.These are measured Gateway main-thread calls, separate from the owner assertion loop above. Remaining filesystem owners are outside this PR, and the completed combined-candidate A1/B/A2 timing campaign retains loaded-host controls and is not presented as a tail-latency improvement. The reproducible Gateway harness is tracked in #197504.
Prior production-head CI run 43141632189 is green on
8e4f975; old-head checks are superseded. ClawSweeper's review on that prior head has zero open items and zero findings, following the six-item resolution.A late consumer audit found an unchanged sandbox test still expecting two main-thread lock stats and immediate manual-unlink refusal. It fails on exact
8e4f975with zero stats; this is a missed consumer alignment in this PR, not an inherited failure. The repair requires zero lock polling, asks the real heartbeat worker to verify physical loss through capturedprepareAccess(), and then requires refusal and successor exclusion. The separate immediate-release consumer remains intact. All four cases pass (87.71 seconds including compilation; the physical-loss case takes 55 ms), and fresh Codex P0–P2 review plus targeted lint pass. Production code is unchanged. Repair head:be34c44d50299bb927b09d89f952ddab45278d3f. Its exact-head CI 43159457305 is green; 24 old-head checks are superseded. The latest ClawSweeper review explicitly covers this head and has zero open items or findings. Fresh native preparation binds these completed gates before merge.