Skip to content

fix(gateway): avoid blocking requests on lock polling - #197455

Merged
steipete merged 3 commits into
mainfrom
steipete/fix-gateway-lock-worker-observation-2424
Nov 12, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/fix-gateway-lock-worker-observation-2424

Conversation

@steipete

@steipete steipete commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Existing main-thread lock regression fails on base 24819901d92ee and passes with the fix. Actual child-process contention proves live-owner exclusion, timeout and acquisition after release.
  • 85 lock/heartbeat/contention tests passed. After finding and repairing an immediate-replacement cleanup regression, 91 tests across the directly affected owner, alias, native cleanup, recorded-lease and plugin-guard suites passed. The unchanged alias suite passes 2/2 on the exact base; its replacement case failed before the cleanup repair. Final focused run: 128.10 seconds including worker compilation and teardown; CI on production head 8e4f975 is green; the later consumer-test repair also has green exact-head CI.
  • pnpm check:changed completed. 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.
  • Exact-head CI run 43136140646 exposed 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.
  • The workspace refusal test now acquires a real Gateway owner, starts deletion through the actual SQLite worker, retires the owner while the operation awaits dispatch, and acquires a successor. The old deletion refuses with 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).
  • Two later PostgreSQL jobs failed the crash/ACK recovery fixture because it advanced only the Gateway main clock. The heartbeat worker kept real epoch, exposing a split-clock test setup after synchronous renewal was removed. The existing preload now carries one clock to Gateway threads. The exact failed case passes against a disposable local PostgreSQL 17 cluster: one case passed, seven deselected, 34.98 seconds in Vitest / 81.22 seconds for the full focused harness. The cluster was stopped and removed. This proves current-head crash/restart recovery, not a latest-stable upgrade.
  • pnpm deadcode:unused-files passes on repair head be34c44: both production and full-tree scans have zero entries.
  • Final core and affected test types, file-scoped lint, line cap and exact test allocation pass. Fresh complete-PR Codex P0–P2 review of the final staged candidate is scoped-clean, with no accepted/actionable findings.

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:

Operation Before After
Lock path stats 2,860 0
Descriptor stats 4,290 0
Lock opens 1,430 0
Lock reads 1,430 0
Lock closes 1,430 0
Selected-target native realpaths 715 715

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-counts with 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 c922dd3bdf86858aea4f6265f92b98e02171c597 includes this PR's production head 8e4f97562c03284cba5f396dfd50e06c0eacef09; 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.

Main-thread filesystem calls per 60-second window Before, five samples After, five samples
Each root/projection lock open 306, 306, 359, 306, 306 0, 0, 0, 0, 0
Each root/projection lock lstat 612, 612, 718, 612, 612 0, 0, 0, 0, 0
Descriptor fstat 1895, 1889, 2467, 1886, 1895 59, 50, 59, 50, 59

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 8e4f975 with 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 captured prepareAccess(), 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.

@clawsweeper

clawsweeper Bot commented Nov 12, 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 scripts Repository scripts size: M labels Nov 12, 2026
@steipete
steipete marked this pull request as ready for review November 12, 2026 01:40
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T02:31:06.032998Z 8e4f975 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 12, 2026
@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: Five measured windows each reopened each lock 306–359 times on the main thread.
  • After: The corresponding windows recorded zero main-thread opens of either lock.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused repair with serving-path measurements and concrete stale-authority coverage; the final consumer alignment preserves production behavior.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied serving-Gateway measurements exercise the unchanged production owner on APFS with an isolated Linux Docker sandbox and show zero routine main-thread lock opens after the fix; complementary real-owner SQLite proof rejects a retired owner's pending deletion before mutation, preserves rows and cache, and permits the successor's deletion.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Slow filesystem metadata operations can freeze unrelated Gateway requests and timers.
Reason: The maintainer-authored direction removes measured duplicate work while explicitly accepting delayed observation of manual lock tampering and retaining local retirement checks.

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
Reviewed head: be34c44d50299bb927b09d89f952ddab45278d3f

Before merge

None.

Findings

None.

Agent review details

How this fits together

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

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main necessity: The pinned introduction diff removes synchronous held-lock verification and expiry recovery; the fetched main retains the original behavior in the affected production modules. (src/infra/gateway-state-owner.ts:116, be34c44d5029)
  • Request custody and cleanup binding: Ordinary prepareAccess calls resolve the registered owner per request; captured cleanup supplies its original owner, and the returned guard rechecks identity after awaited worker verification. (src/infra/gateway-state-owner.ts:642, be34c44d5029)
  • Final-effect authority evidence: The real workspace deletion regression retires the original owner before awaited dispatch resumes, requires refusal with persisted rows and cache intact, and then proves successor-authorized deletion; the discussion records its passing run at fix(gateway): avoid blocking requests on lock polling #197455 (comment). (src/agents/workspace-state-store.test.ts:215, be34c44d5029)
  • Accepted observation tradeoff and serving proof: The maintainer-authored body explicitly accepts worker-observed manual lock loss and temporary refusal during overdue renewal, and supplies five before/after serving-Gateway filesystem-count windows with the environment and limits stated. (be34c44d5029)
  • Cleanup preserves replacement custody: Native cleanup and recorded-lease release await captured preparation; existing alias and lease regressions retain assertions that replacement locks and recorded leases survive ownership loss. (src/state/openclaw-agent-execution-cleanup.ts:179, be34c44d5029)
  • Final consumer repair and CI: The latest commit changes only the sandbox consumer test and allocation record, preserving production proof; current-head checks have no reported failure or timeout, with several checks still running or queued. (src/agents/sandbox/context.state-owner.test.ts:101, be34c44d5029)

Likely related people:

  • Vincent Koc: Raw commit e98a15b adds src/infra/gateway-state-owner-heartbeat.runtime.ts:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: e98a15b7d695; files: src/infra/gateway-state-owner-heartbeat.runtime.ts)

PR surface

Source -4, Tests +63, Docs +10, Other +84. Total +153 across 18 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 96 100 -4
Tests 9 140 77 +63
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 2 92 8 +84
Total 18 338 185 +153

Preflight source

Source 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

Metric Value Why it matters
Production versus regression LOC Production +96/-100; tests and support +140/-77 Runtime code shrinks by four lines; net regression growth covers worker loss, expiry, stale-owner effects, and affected consumers.
Benchmark flag One new flag: --fs-counts The existing performance script separates filesystem counting from timing and allocation measurements.

Labels

Label changes:

  • add P2: Synchronous lock metadata operations can stall unrelated Gateway requests under slow storage, making this a meaningful responsiveness repair.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Synchronous lock metadata operations can stall unrelated Gateway requests under slow storage, making this a meaningful responsiveness repair.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-12T01:58:15.388Z sha f673f89 :: needs real behavior proof before merge. :: [P1] Resolve reusable access ownership for each request | [P2] Migrate the restart-recovery consumer to asynchronous observation
  • reviewed 2026-11-12T02:32:58.310Z sha 8e4f975 :: needs maintainer review before merge. :: none

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.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime cli CLI command changes agents Agent runtime and tooling size: L and removed size: M labels Nov 12, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressing all six open items from the review of f673f89, against 8e4f97562c03284cba5f396dfd50e06c0eacef09:

  1. Real behavior proof: replaced the mocked refusal case with real Gateway-owner and SQLite-worker deletion. The pending operation passes its initial synchronous host admission, then the original owner releases and a successor acquires before awaited worker dispatch resumes. The stale operation refuses; persisted setup/attestation rows and the workspace cache remain unchanged. The successor then deletes state and retires the cache. The frozen workspace/MCP run passes 24/24 in 43.69 seconds including preparation and teardown. The PR body records this proof. Existing-state restart coverage is not claimed as a latest-stable upgrade; this change has no schema or persisted-format change.
  2. Reusable owner lookup (P1): fixed per-request lookup inside prepareAccess. Only captured cleanup preparation supplies the original owner. Exact-head CI failures were reproduced locally; lease/transcript consumers and the MCP suite now pass. No inherited-failure classification is used.
  3. Restart recovery consumer (P2): migrated the existing restart fixture to the actual heartbeat worker and await its loss publication. It still asserts successful close/restart/custody reacquisition when restart-intent reading rejects. The selected regression passes; the other 174 CLI cases passed in the preceding run.
  4. Security attention: the real-effect proof in item 1 exercises the captured owner identity/accepting check, retained immediately before operation admission. The asynchronous preparation guard rechecks the original generation after worker verification. Selected-path alias validation remains intact.
  5. Merge risk: item 1 proves refused old-owner effects and successful successor effects through the real database owner. It retains actual row/cache assertions rather than replacing them with a guard-spy expectation. Manual filesystem tamper is still the stated worker-observation tradeoff; immediate in-process retirement is preserved.
  6. Original request ownership intent: restored. captureStateDatabaseAccess does not pin a process owner for ordinary request preparation. Its existing process-owner descriptor remains captured for native ownership, while each prepareAccess request selects current custody and returns that request's final guard. Cleanup alone uses the explicit original owner.

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

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

The final audit found and repaired one missed consumer assertion on 8e4f975: the sandbox custody test expected two synchronous lock stats. Head be34c44d50299bb927b09d89f952ddab45278d3f changes only that test and its exact allocation record (+2 lines). It now requires zero lock polling, uses the actual heartbeat worker through captured prepareAccess() to verify manual physical loss, then requires the retained callback to refuse both before and after a successor acquires valid custody. The separate immediate local-release case remains intact. All four consumer cases, targeted lint/format/allocation, and fresh Codex P0–P2 review pass. Production source and prior workload measurements are unchanged; the body retains the discovered failure and distinguishes prior-head proof. The previous six-item resolution remains applicable.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 12, 2026
@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. labels Nov 12, 2026
@steipete
steipete merged commit a14127f into main Nov 12, 2026
168 of 170 checks passed
@steipete
steipete deleted the steipete/fix-gateway-lock-worker-observation-2424 branch November 12, 2026 06:51
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 13, 2026
* 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
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 17, 2026
…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]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: L 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