Repository navigation
perf(state): avoid synchronous lease reads during reloads - #183336
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. |
Reuse the process-bound native lease owner’s confirmed expiry and lifetime at reload and plugin checkpoints. Keep explicit durable assertions, maintenance, renewal and worker commit authority intact. This removes repeated main-thread ownership reads without a schema or lease SQL change.
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 changesAdds a real-Gateway reload benchmark and carries the native lease owner's lifetime and confirmed expiry through reload checkpoints. Example: Change messages.ackReaction to 🧪 through config.set.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 6 items remain Keep this PR open: it addresses measured reload overhead, but adds synchronous SQL to existing plugin worker checkpoints and breaks an affected reload test fixture. Priority: P2 Before merge
Findings
Provenance
Tests
Agent review detailsHow this fits togetherAuthenticated configuration writes and file observations enter the Gateway reload coordinator, which uses plugin lifecycle leases to prepare and publish configuration, credentials, and plugin generations. flowchart LR
A[Config RPC or file observation] --> B[Gateway reload coordinator]
B --> C[Plugin lifecycle lease]
C --> D[Native lease owner]
D --> E[Durable lease storage]
C --> F[Config and plugin publication]
Technical reviewBest possible solution: Reuse the existing lease owner while preserving SQL-free plugin worker checkpoints, completing the consumer cutover, and qualifying the changed publication boundary. Do we have a high-confidence way to reproduce the issue? Source inspection and the recorded Gateway baseline establish repeated lease SELECTs; exact-head CI independently exposes the introduced worker-checkpoint SQL and missing test capability. Is this the best way to solve the issue? Carrying the existing owner's recorded lifetime is a focused approach, but its shared checkpoint must preserve existing SQL-free worker behavior. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 0eb9d17cee48. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: Final-effect refusal remains unproven for the changed lease capability, although source inspection establishes no concrete authorization bypass. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +10, Tests +77, Other +271. Total +358 across 13 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 25, 2026, 3:22 AM ET / 07:22 UTC. |
Three fork test files merged cleanly but broke against seams upstream changed in the jump window: - session-recipient-authority.caller-thread: the maintenance owner fixture now provides assertCurrent, which OpenClawStateLeaseContext requires since openclaw#183336 (tsgo:core:test TS2741 at the merge). - session-delivery-queue-runtime: upstream removed withRuntime and builds the runtime fixture through withSessionDeliveryQueue (openclaw#183214). The capacity retry case does the same: each bound still gets a fresh queue and clock, with the same teardown order. The clock-jump case takes upstream's r.start() back: the wake assertion that the fork's pendingSweep: false served was removed upstream. - diagnostic.continuation-queue: upstream dropped the startDiagnosticHeartbeat test-support export (openclaw#183134); the enabled-config variant is the same call. RED at the merge 86ed749: withRuntime is not defined; startDiagnosticHeartbeatForTest is not a function; TS2741. GREEN: 20/20, 2/2, 9/9 solo, and tsgo:core:test passes. Assertions are unchanged. Refs karmaterminal/openclaw-bootstrap#1727 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…83336) Reuse the native lease owner's confirmed lifetime at config reload and plugin checkpoints while preserving durable assertions, worker commit checks, and the final invoker validation before publication. Synthetic real-Gateway comparisons reduce warm MAIN lease reads from 27 to 0 (total SQL 85 to 58), and plugin-toggle MAIN reads from 51 to 0. The measured request-p95 increase from 26 to 32 was accepted after attribution; whole-workload request medians remain 359 to 358. Explicit lease-loss and cancellation coverage remains.
What Problem This Solves
Config reload and plugin lifecycle callbacks repeatedly query lease ownership on the Gateway main thread, even though the native lease owner already holds the confirmed expiry and lifetime state. The synthetic real-WebSocket comparison reproduces 27 MAIN reads per warm reload and 51 per plugin toggle; the candidate reduces both to zero.
User Impact
Reloads and plugin enable/disable keep their existing results while removing synchronous ownership queries. Explicit durable assertions, worker commit checks, acquisition, renewal, release, maintenance, and lease-loss rejection stay intact. No operator action or schema migration is required.
Why This Change Was Made
Expose the existing owner's current lifetime/expiry fact separately from durable
assertOwned(), and carry it through reload checkpoints. Fast implicit entry/return applies only to native, process-bound, non-worker-heartbeat, current-schema invocations. The owner uses the expiry returned by successful persistence andDate.now(); unknown renewal cannot extend it. There is no new cache, generation, fence, handshake, SQL text, or transaction change.Final effect checks remain. In particular, the outer
publication.assertInvokerOwned()is restored immediately beforeruntime.publish(). A post-await plugin checkpoint also stays because it checks drain, cancellation, and requester state. Accepted edge: arbitrary out-of-band SQL edits during the confirmed lifetime are detected at the next durable assertion/commit; supported live writes have one Gateway owner and offline maintenance requires exclusive custody. Production delta: +33/−23 lines, net +10, accepted by the maintainer.Evidence
The maintainer accepted the count-regression tradeoff; final exact-head CI passed. The third pair triggered the preregistered stop: warm request p95 26 → 32 (+23.1%). This is not described as passing or hidden within spread. All three pairs have zero candidate runtime MAIN SQL. The final test-only CI correction adds the required isolation explanation to a test mock and prunes its obsolete baseline entry; the mock-export guard passes with 7,013 grandfathered factories. It changes no production behavior.
Preregistered acceptance
Flow: isolated current-head Gateway with its own synthetic config, workspace, state and loopback port; token-authenticated config.get/config.set; hybrid reload strategy with the normal debounce; six hot-compatible config changes (first cold, five warm), bundled Diffs enable/disable, then one connected idle minute. config.set persistence is followed by config.get until its raw revision matches that exact write acknowledgement and its applied revision matches the persisted resolved revision. No operator data or external provider is used.
Workload:
node --import ./scripts/tsx.mjs scripts/bench-reload-lease.mts --out <fresh-internal-dir> --observer <frozen-v3.1.5>/observer.cjs --samples 6 --idle-seconds 60 --cpu-profile, with the frozen causality preload, internal temporary/cache roots, and ordinary proof slot. First run without--cpu-profilefor counts, then repeat with the flag for per-thread profiles. Capture native SQL, worker requests and MAIN statements. Each action cell includes its following one-second settle phase so post-publication cleanup cannot disappear from the counts. Attribute every MAIN state_leases shape to its caller and protected effect; report repeated checkpoints separately from actual effects.Acceptance for a production candidate: MAIN lease SELECTs must reach zero throughout reload/plugin/idle, or every retained statement must have a documented effect and reason. Total SQL and requests for touched operations must fall or hold, warm non-regression must hold, and existing lease-loss tests must still stop publication/activation/restart. No new generations, fences, freshness probes, schemas or caches. Moving a kept check to the worker alone is not a total-work saving.
Comparison: same-platform alternating M/C pairs, three pairs when campaign load/disk gates allow; otherwise one pair with explicit source attribution. At least five warm action samples per arm; cold, warm, plugin and idle cells reported separately as median/p95/min/max, with per-operation deltas. Timing/CPU-speed A/B requires the timing mkdir lock and load below 24, five samples per arm, no worse user-facing metric; any adverse 20% cell stops. Under load, counts/profiles only, no latency or CPU-speed claim.
Completed three-pair comparison
Production base
bac203a331efd320a9441d9e1e4c83dfa6517352, candidatea0b8c1c3e3426612bddaa18d050643daaafeeff7. Same platform, M/C/M/C/M/C, frozen observer v3.1.5 (37 hashes verified), six config changes, plugin enable/disable, connected idle minute. Each action includes completed owner releases and its one-second settle; all requested persisted/applied revisions completed and observer errors were zero. The saved first baseline arm was reused; no baseline rebuild. Starting load was 33.08, so these are counts, not latency/CPU-speed evidence.Cells show median [min–max], p95. Cold and warm remain separate.
The 15 warm MAIN counts are exactly 27 → 0; all six plugin-toggle comparisons are 51 → 0. Candidate MAIN remains only during boot (64–65, including one lease SELECT) and shutdown (5); runtime reload/plugin/idle MAIN is zero. Idle MAIN was already zero on the reproduced baseline, so no idle saving is claimed.
The third pair's first warm cell adds three execute requests, two plugin metadata reads, one usage-cost refresh and one memory prewarm, minus one periodic scan. Stacks identify one extra acquisition, one snapshot application and one lower-level broker operation among the executes; the extra reload-scope work is explicitly included, not dismissed as generic noise. Later warm cells include catalog/deferred-migration and deletion/topology readers. Third-pair whole requests rise 359 → 372; pooled whole medians are 359 → 358. The maintainer accepted this attributed overlap after the stop. An additional check of the existing ledgers finds two acquisition requests in every baseline warm sample; the candidate has two in 14/15 and three only in the spiking sample. All plugin actions have two on both arms. Cold acquisition requests match per pair (2/2/3). This is not a per-reload increase. The isolated extra scope remains a named follow-up; all its work stays included in the table. No repeated runs were used to chase the spike away.
A separate candidate attribution run used the existing measured build and captured 30 thread CPU profiles with zero observer errors. Lease-verification samples were confined to a worker profile (four inclusive samples); MAIN had zero. The earlier baseline attribution covered 32 threads. These are profile attributions under load, not a matched CPU-speed comparison.
Behavior, reviews, and CI
The no-MAIN regression is red on the base (
[0,1]) and green on the candidate ([0,0]). Native admission 10/10 and seven reload/plugin owner files 454/454 pass on the final production source. Explicit SQLite and PostgreSQL durable lease-loss cases also pass. The worker TIMER observation test was already green before the correction; the genuine red/green regression captures the direct native checkpoint's cancellation error outside final unwind normalization.Two isolated Codex production reviews and the permitted focused CI/PG correction reviews are scoped-clean. The final PG delta restores
assertActive()and the outer invoker check. PG approval carries for these precise changes; exact-head CI run 40177729778 completed successfully, including all three PostgreSQL conformance shards, types, lint, architecture, source contracts, baseline ratchets, and the aggregate CI gate. Final head217b048e5bb21e9e75d6483b8cef573959c61739adds only the mock-isolation explanation and shrink-only baseline bookkeeping; all production and benchmark blobs are identical to the measureda0b8c1c3e34. Ona0b8c1c3e34, the only observed static failure was the new test mock's missing isolation explanation. The final test-only commit fixes it and shrinks the obsolete baseline entry; the local mock-export guard and formatting checks pass. Local script types were blocked before the compiler by the mandated internal virtual-store containment check; passing CI types provide that proof. Targeted type-aware lint, formatting, and diff checks pass.The final shared PR index audit on
217b048e5bb2covers 66 peers. Sixty-four have identical conflict paths/regions. The maintainer accepted the test-only mock/import overlap with #183279, its required one-line obsolete baseline-row deletion, and the required fixture capability inside #161900's existing add/add conflict. The two newly indexed PRs (#183443 and #183445) and updated #183248 remain conflict-free. No new production conflicts.The final canonical Knip scan exits 1 with 26 script, 20 production, and 16 full-tree occurrences. Every finding and all scanner/config/package inputs are byte-identical to the PR merge base and outside the changed files. The maintainer accepted them as inherited; retained lease helpers still have live consumers, and this change removes no helper's last use. This is attributed inherited debt, not a clean Knip result.
Final head
217b048e5bb21e9e75d6483b8cef573959c61739has a successfulopenclaw/ci-gate; security and dependency review also passed. The final shared-index refresh still contains the same 66 peer heads and adds no conflict delta.The maintainer waived the published-driver update cell: no persisted schema, format, config, migration, update command, or Doctor behavior changes. The queued Testbox attempt was canceled and verified completed with no host; it is not claimed as passing proof.