Repository navigation
fix: large session stores delay Gateway plugin startup - #181289
Conversation
Use the active-session index for recovery candidate discovery and defer marking through tracked post-ready work. Preserve channel, startup RPC, hook, and saved-input ordering, with current-state checks before deferred writes. Extract sidecar startup and canary tests to respect the line-cap ratchet. Fixes #181090.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis PR defers orphan marking until after plugin startup and uses the existing active-session index for recovery discovery. Example: Gateway startup with the reported 1.26 GB agent store.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR addresses a remaining startup dependency on main, preserves recovery admission ordering, and has passing exact-head CI; no actionable finding remains. Priority: P1 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherGateway startup coordinates plugin attachment, session database preparation, orphan marking, and recovery before admitting new conversation work. flowchart TD
A[HTTP listener] --> B[Plugin attachment]
B --> C[Startup completion]
C --> D[Tracked orphan marking]
E[Session database worker] --> D
D --> F[Client and channel admission]
D --> G[Saved input recovery]
G --> H[Chat admission]
Technical reviewBest possible solution: Use the existing tracked startup and recovery owners to unblock plugin attachment while preserving predecessor ordering and indexed candidate discovery. Do we have a high-confidence way to reproduce the issue? Current main demonstrably awaits marking before plugin attachment, and the PR records red-to-green ordering and query-plan regressions; the reported Windows timeout itself was not reproduced. Is this the best way to solve the issue? The change uses existing lifecycle and recovery owners, removes archived-row JSON inspection, and preserves admission barriers; the sidecar extraction replaces the original implementation without adding a competing scheduler. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 1532cce33d81. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +45, Tests +202, Docs +5, Other -1. Total +251 across 18 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 HistoryReview history (3 earlier review cycles)
Reviewed October 23, 2026, 1:51 AM ET / 05:51 UTC (Revision 4). |
|
Addressed all four findings from the original-head review in one repair batch: the projection fixture now releases startup preparation before holding post-start marking; the authorization fixture joins canonical input recovery; the query-plan observer covers both Local proof now covers 91 passing cases across the full focused run and the exact two-case suspension replay. Changed-file lint/format and both line-count ratchets pass; the PR body records the proof, costs, and remaining gaps. Cold Windows/live Gateway/channel proof is intentionally skipped under the maintainer's explicit campaign policy: focused local red/green regressions plus PR CI are the authorized proof, with no live e2e or remote leases. The body makes no Windows latency claim. @clawsweeper re-review |
|
🦞👀 Re-review progress:
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2b3592e6a5
ℹ️ 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".
| if (params.isRestartRecoverySuppressed() || params.getConfig() !== cfg) { | ||
| throw new Error("Gateway restart recovery state changed before orphan marking"); | ||
| } |
There was a problem hiding this comment.
Retry marking before opening startup RPC admission
When a hot reload publishes a new config object while this potentially long multi-store scan is running, this check throws after only part of the store set has been marked. markGatewayStartupMainSessionOrphans catches that exception and resolves normally, so the post-attach continuation treats mainSessionOrphansReady as fulfilled and unlocks agent and sessions.send; those RPCs can then start successor work before the later recovery sweep marks and resumes an interrupted predecessor. Retry the scan with the current config, or otherwise keep the admission barrier pending, rather than converting this state change into successful readiness.
AGENTS.md reference: AGENTS.md:L94-L96
Useful? React with 👍 / 👎.
|
Merged via squash.
|
…181470) e40d9f7 (#181289) intentionally completes startup before recovery admission, so gateway server test fixtures that connected immediately got UNAVAILABLE startup-sidecars, turning src/gateway/server/skill-library-read.test.ts and src/gateway/server.chat-metadata-boundary.test.ts red on main for every PR. The fixtures now await the canonical /startupz readiness signal before connecting. Test-only.
* fix(gateway): keep orphan marking off plugin startup path Use the active-session index for recovery candidate discovery and defer marking through tracked post-ready work. Preserve channel, startup RPC, hook, and saved-input ordering, with current-state checks before deferred writes. Extract sidecar startup and canary tests to respect the line-cap ratchet. Fixes openclaw#181090. * fix: preserve client admission during startup orphan recovery * test: align suspension checks with deferred orphan marking * test: remove unused recovery query lint suppression * fix: retain startup recovery admission across config reloads * test: use canonical agent config in startup recovery fixture
…penclaw#181470) 676b237 (openclaw#181289) intentionally completes startup before recovery admission, so gateway server test fixtures that connected immediately got UNAVAILABLE startup-sidecars, turning src/gateway/server/skill-library-read.test.ts and src/gateway/server.chat-metadata-boundary.test.ts red on main for every PR. The fixtures now await the canonical /startupz readiness signal before connecting. Test-only.
…es (#182615) Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs #182547 (the slow startup scan is already fixed on main by #176737 and #181289). Supersedes #173482. Thanks @VictorSesma and @hoangtohl. Co-authored-by: Victor <[email protected]>
…es (openclaw#182615) Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs openclaw#182547 (the slow startup scan is already fixed on main by openclaw#176737 and openclaw#181289). Supersedes openclaw#173482. Thanks @VictorSesma and @hoangtohl. Co-authored-by: Victor <[email protected]>
) Let the automation fixture settle its manual startup clock before client connection, retaining the Gateway helper cleanup owner. Migrate the visible-lane heartbeat proof from retired configuration and RPCs to a named-session automation. Preserve startup admission, authorization assertions, held-provider concurrency, and all existing timeouts. The automation, visible-lane, and unchanged fallback-image e2e each pass three consecutive local runs. The original patch has two clean isolated Codex reviews; the heartbeat delta has one additional clean review. Fixture regressions follow #181289 and #179387. Includes the separately landed duplicate-fallback-image fix #183921 through main; no product or SQL changes in this PR.
…claw#183847) Let the automation fixture settle its manual startup clock before client connection, retaining the Gateway helper cleanup owner. Migrate the visible-lane heartbeat proof from retired configuration and RPCs to a named-session automation. Preserve startup admission, authorization assertions, held-provider concurrency, and all existing timeouts. The automation, visible-lane, and unchanged fallback-image e2e each pass three consecutive local runs. The original patch has two clean isolated Codex reviews; the heartbeat delta has one additional clean review. Fixture regressions follow openclaw#181289 and openclaw#179387. Includes the separately landed duplicate-fallback-image fix openclaw#183921 through main; no product or SQL changes in this PR.
…es (#182615) Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs #182547 (the slow startup scan is already fixed on main by #176737 and #181289). Supersedes #173482. Thanks @VictorSesma and @hoangtohl. Release adaptation: production fix (readOnlyWorkerScope.exit around the queued publication, plus the agentDir normalization moved into the invalidation owner) applied unchanged; only the conflicting main-only throwSettledAggregate import was dropped. The prepared-harness integration-test fixture change was not needed on the baseline (its main-only DB admission setup is absent) and was dropped. The Gateway regression test was ported into the baseline describe block using its sendAgentRpc and setRuntimeAuthProfileStoreSnapshot; the main-only rows-cache cold-read step was omitted. It fails without the fix with "SQLite read-only worker scope closed". Co-authored-by: Victor <[email protected]> (cherry picked from commit 411bac2)
…es (#182615) Auth publication queued during Gateway startup inherited a temporary SQLite reader scope that startup closed before the work ran, so model publication and later reads failed with 'SQLite read-only worker scope closed' until restart. The scheduling owner now exits that reader scope when queuing, preserving the caller's own startup scope. Refs #182547 (the slow startup scan is already fixed on main by #176737 and #181289). Supersedes #173482. Thanks @VictorSesma and @hoangtohl. Co-authored-by: Victor <[email protected]> (cherry picked from commit 411bac2) Adapted for 2026.9.x: 9.x queues auth publication with publicationQueue.enqueue (main uses modelRuntimeDrain.runAfter), so the enqueue is wrapped in readOnlyWorkerScope.exit; the queue's previous.then(task) continuation otherwise captures the emitter's reader scope. Dropped main's normalizedEvent cleanup in prepared-model-runtime-auth-publication.ts and the source-delivery integration test mock change (unrelated refactors). beginPreparedModelRuntimePluginDrain does not exist on 9.x, so the regression closes the startup reader scope synchronously before the queued publication runs, then asserts publication completes, ensureOpenClawModelsJson sees no inherited reader scope, and an agent run on the affected agent completes.
Adapt openclaw#181289 to the release startup owner without introducing selective RPC unlock, saved-input replay, or new recovery ownership. Attach plugins, release existing database preparation even without worker placement, and start plugin services before scanning startup orphans. Keep channels, startup hooks, and the existing all-RPC readiness barrier behind the scan. Retain the scan in tracked startup work and reject config/suppression/abort changes through the existing synchronous writer guard. This deliberately does not import the newer 92-file replay prerequisite or make recovery post-ready. Existing FIFO, permissions, durability, shutdown settlement, and per-agent admission owners remain unchanged. Source-only review, node --check, and git diff --check passed. Product tests, build, typecheck, lint, and formatter were not run by task instruction. Parent review and focused hosted startup/admission proof remain required. (cherry picked from commit e40d9f7) Co-authored-by: vincentkoc <[email protected]> Co-authored-by: RomneyDa <[email protected]>
Fixes #181090
What Problem This Solves
Fixes delayed Gateway startup and plugin loading when orphan discovery takes a long time on a large session store.
User Impact
Plugin loading and startup completion can proceed before orphan marking finishes. Ordinary client connections, channels, startup-gated RPCs, startup hooks, and saved-input replay retain their recovery ordering; chat readiness remains gated until saved-input recovery completes. Failed marking logs a warning and leaves failed stores available to the existing recovery sweep. No configuration or schema changes are required.
Why This Change Was Made
The confirmed base still joins marking in
finishGatewayStartuplines 210–213. Main already moved candidate selection into the database worker (#176737) and removed cold-read writer reservations (#173408), but marking still blocked post-attach plugins. The remaining query inspected archived-row JSON instead of using the existing active-session index.The marking pass now runs under existing tracked post-start maintenance. Channel startup, startup hooks, and startup observers share its promise, and the checked-store handoff prevents duplicate discovery. Current configuration, cancellation, suppression, and session/run ownership are checked before deferred commits. If a config reload invalidates the pass, the same admission promise retries with current configuration and retains already-checked stores; both thrown errors and returned failed targets are handled. Ordinary storage failures retain the existing warning behavior. Candidate selection uses the indexed archive column and only hydrates eligible metadata, without full transcript reads.
Keeping admission barriers is intentional: pending final deliveries and replayed predecessor turns rely on marking. Ordinary connections open with the non-chat RPC surface after marking, so initial model snapshots and existing input aliases remain correctly ordered. Database preparation is released independently after plugin attachment. The query still examines active-session recovery facts; this is not a fixed-size cap on active rows. The small production increase preserves ordering and shutdown custody without another scheduler or timer. Existing sidecar code and canary tests moved into sibling owners to satisfy line limits without weakening checks.
Evidence
SCAN session_nodes; the active-index regression failed while six existing worker cases passed. The startup-ordering regression failed because channels started before the held marking gate./readyzremains gated. The catalog case receives its initial snapshot and retains draft/saved-session scopes.b744af539dbec1da9918cc17c97245d07eded145; the complete affected observer/post-attach run passes 85/85 cases with the fix.The first CI run exposed five failing jobs. The repair fixes the lost initial model snapshot by preserving connection admission, updates the projection and authorization fixtures to observe the correct completion signals, observes both SQLite
all()anditerate()for the query-plan test, and removes the stale line-count exemption. All four ClawSweeper findings on the original head are addressed by this batch. The following CI run passed every test job, including all PostgreSQL conformance shards, and exposed one unused lint suppression in the portable query observer. The cleanup removes that comment; CI-equivalent lint passes for every changed TypeScript file. A subsequent ClawSweeper P1 identified config invalidation releasing admission early. The current-config retry described above fixes that ordering defect while retaining completed-store bookkeeping. The preceding CI run 39902338229 validates the pre-retry headb744af539dbec1da9918cc17c97245d07eded145. CI run 39904004301 passed every runtime test job and found one test-fixture type error: the new config-reload test used retiredagents.list. The final test-only correction uses canonicalagents.entries; its owning Gateway test typecheck and both regression cases pass locally. ClawSweeper’s review of6bd06483da2c85615fa1190861afbfda747ec883confirms all five earlier findings are addressed and no actionable finding remains. Production is unchanged by this final fixture correction. Final exact-head CI run 39904978543 passed onb5169b6c3f625e5fc6c8ff236b95841e7ddd255f: 55 successful jobs, 25 skipped, no failures, including all three PostgreSQL conformance shards.The historical Windows 105-second timeout was not reproduced on Windows. Live Gateway/channel e2e, remote leases, broad local suites, and full local typechecks were skipped per explicit maintainer proof policy; PR CI is the broad gate. No Windows latency improvement is claimed from these local tests.
Local proof costs, scope, and other observed failures
The five-file Bun run took 782.17 seconds including worker preparation, transforms, and final artifact verification. It passed 89 cases and exposed two old readiness assertions in the suspension helper. After correcting those assertions while retaining shutdown/cancellation coverage, the exact two-case replay passed in 18.80 seconds; the other 77 startup cases were deliberately deselected. The Gateway project reported 674.56 seconds with 66% spent transforming. The worker project took 55.68 seconds. Real startup/projection behavior and cleanup took 95.336, 4.954, and 6.443 seconds; initial-turn authorization took 14.725 seconds; catalog connection/publication took 54.102 seconds. These existing integration fixtures exercise lifecycle and transport boundaries that the smaller worker/startup-owner tests do not.
An earlier separate run found two retained-memory reload phase failures:
restarts retained memory watchers after provider-only reload (pending)exhausted the existing approximately five-second service-stop deadline;recovers retained memory indexing after early restart failurereached recovery after injected checkpoint/restart failures before an assertion expectingreloading. A narrow diagnostic exposed the caught errors. These cases directly invoke the reload fixture without this startup path. They remain recorded observations, not claimed fixes or inherited-CI classifications.The earlier runtime/query proof used
fc2aa4af69d2. The config-reload repair inec4673cbeeb6adds two red/green cases and reruns both complete affected startup files: 85 passed in 135.74 seconds including transforms; the wrapper completed source verification successfully. The final fixture-only cleanupda77c8c8b365also passes the owning Gateway test typecheck and the two-case replay (37.96 seconds project / 47.76 seconds wrapper). Full branch autoreview on that final candidate completed scoped-clean P0–P2. Fresh main412c2e94a74011d9265e2d6bbedd83c1a1919c2awas then merged without conflicts, with no changes to the patch files and an identical stable patch ID. PR CI validates merged headb5169b6c3f625e5fc6c8ff236b95841e7ddd255f.Compared with that main: production +486/−441 (net +45), tests/support +354/−152 (net +202), docs +16/−11 (net +5), ratchet config +0/−1. Necessary production growth preserves existing admission ordering and tracked shutdown custody; most gross movement is the sidecar extraction.
Focused commands use
node scripts/run-vitest.mjswith explicit files; the two replays selected only the corrected suspension cases and the new config-reload regressions, respectively. Only actual config replacements trigger another marking pass; successful stores are retained in the checked set. Sustained config replacement can delay admission until a stable pass. No generic failure retry, longer timeout, new timer, or weaker production admission gate was added.