Repository navigation
fix(gateway): small agents stay unavailable until larger agents finish startup preparation - #165107
Conversation
…r agents Deferred startup recovery chained every agent's whole preparation (secrets refresh, session migration, model refresh) through one FIFO, so a 12 MB agent waited ~36 minutes behind two slower agents on a starved Gateway, and nothing was logged between deferral and recovery. Open and session migration now run per agent (two open slots, four migration slots, readiness awaited without a slot). Only credential/model publication and final admission keep the FIFO turn, with the existing config, revision, auth-store, model and deletion checks. Migration uses the same agent-database configuration guard as the open step. Recovery and degraded lines now carry elapsedMs and phaseDurationsMs, and a 60 s progress warning names each pending agent's phase and, while waiting for publication, the agent holding the turn.
|
🦞👀 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: blocked before merge. Reviewed October 4, 2026, 6:24 PM ET / 22:24 UTC (Revision 2). ClawSweeper reviewWhat this changesThe PR prepares deferred agents’ sessions concurrently, preserves serialized credential and model publication, and adds startup progress diagnostics. Merge readiness⛔ Blocked before merge - 1 item remains The fix remains necessary: current main still serializes deferred session preparation. No blocking patch defect was found, and the new real-Gateway evidence supports the improvement. The earlier data-model compatibility blocker is resolved because no persisted contract changes. Priority: P1 Review scores
Verification
How this fits togetherGateway startup inspects and prepares each agent’s databases before allowing sessions to use them. Deferred admission keeps an agent unavailable until its session preparation, credentials, models, and final ownership checks complete. flowchart TD
A[Agent databases] --> B[Background inspection]
B --> C[Bounded database opening]
C --> D[Startup recovery readiness]
D --> E[Concurrent session preparation]
E --> F[Serialized credentials and models]
F --> G[Final ownership and deletion checks]
G --> H[Agent sessions available]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +141, Tests +421, Docs +13. Total +575 across 5 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep agent-local session preparation bounded and independent while one publication owner preserves global credential revisions and final admission checks. Do we have a high-confidence way to reproduce the issue? Yes: current-main source serializes complete deferred preparation, and the supplied real-Gateway reproduction observes the tiny agent waiting behind large transcript rebuilds. This read-only review did not execute that reproduction. Is this the best way to solve the issue? Yes: splitting agent-local preparation from global publication repairs the existing owner’s scheduling boundary without adding configuration or changing stored formats. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against b48245c41428. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
|
Maintainer response to the "Add data-model compatibility proof" item: this PR changes no stored data, schema, or migration. It changes only in-process scheduling of startup preparation (which steps run per agent and which share the serialized publication turn) and adds log fields. No SQLite schema version, table, row shape, config key, Doctor transform, or on-disk artifact is added or changed. The same agent databases, written by the same session-migration code, are opened before and after this change. Upgrade and rollback behavior are unchanged: a downgraded Gateway runs the old serialized order over identical files. The CPU-contention reproduction is now in the PR body; the tiny agent was admitted at T+89 s instead of T+1534 s. |
|
Merged via squash.
|
…r agents (openclaw#165107) Deferred startup recovery chained every agent's whole preparation (secrets refresh, session migration, model refresh) through one FIFO, so a 12 MB agent waited ~36 minutes behind two slower agents on a starved Gateway, and nothing was logged between deferral and recovery. Open and session migration now run per agent (two open slots, four migration slots, readiness awaited without a slot). Only credential/model publication and final admission keep the FIFO turn, with the existing config, revision, auth-store, model and deletion checks. Migration uses the same agent-database configuration guard as the open step. Recovery and degraded lines now carry elapsedMs and phaseDurationsMs, and a 60 s progress warning names each pending agent's phase and, while waiting for publication, the agent holding the turn.
Remove speculative registry retargeting, reader custody and generation protocols, reconcile priority reservations and successor handoffs. Keep one current-authority check at effects, atomic projection finalization, bounded resources and ordinary write-capable shutdown settlement. Retain simple session-boundary fairness for the production incident recorded in #165107 and bounded backoff for the human report #115908. Unsupported mid-call topology changes and failed derived projection preparation are best effort until the next request or restart. No schema, stored-data, retention, permission or public API change. Validation: 36 focused history/bootstrap tests pass; corrected Testbox shutdown and registry controls pass; both import-cycle checks report zero cycles; core typecheck and targeted lint pass. Review findings addressed, including empty archive-path semantics and immediate async-consumer rejection handling. Publication remains blocked before PR/merge: still-open heartbeat PR #167796 protects session-logical-entry-read.worker.test.ts, whose obsolete pending-registration assertions require a scope exception. Full sessions proof is incomplete. Unchanged baseline suppression and UI test-root budget failures are recorded in the lane ledger.
Remove speculative registry retargeting, reader custody and generation protocols, reconcile priority reservations and successor handoffs. Keep one current-authority check at effects, atomic projection finalization, bounded resources and ordinary write-capable shutdown settlement. Retain simple session-boundary fairness for the production incident recorded in #165107 and bounded backoff for the human report #115908. Unsupported mid-call topology changes and failed derived projection preparation are best effort until the next request or restart. No schema, stored-data, retention, permission or public API change. Validation: 36 focused history/bootstrap tests pass; corrected Testbox shutdown and registry controls pass; both import-cycle checks report zero cycles; core typecheck and targeted lint pass. Review findings addressed, including empty archive-path semantics and immediate async-consumer rejection handling. Publication remains blocked before PR/merge: still-open heartbeat PR #167796 protects session-logical-entry-read.worker.test.ts, whose obsolete pending-registration assertions require a scope exception. Full sessions proof is incomplete. Unchanged baseline suppression and UI test-root budget failures are recorded in the lane ledger.
Remove speculative registry retargeting, reader custody and generation protocols, reconcile priority reservations and successor handoffs. Keep one current-authority check at effects, atomic projection finalization, bounded resources and ordinary write-capable shutdown settlement. Retain simple session-boundary fairness for the production incident recorded in #165107 and bounded backoff for the human report #115908. Unsupported mid-call topology changes and failed derived projection preparation are best effort until the next request or restart. No schema, stored-data, retention, permission or public API change. Validation: 36 focused history/bootstrap tests pass; corrected Testbox shutdown and registry controls pass; both import-cycle checks report zero cycles; core typecheck and targeted lint pass. Review findings addressed, including empty archive-path semantics and immediate async-consumer rejection handling. Publication remains blocked before PR/merge: still-open heartbeat PR #167796 protects session-logical-entry-read.worker.test.ts, whose obsolete pending-registration assertions require a scope exception. Full sessions proof is incomplete. Unchanged baseline suppression and UI test-root budget failures are recorded in the lane ledger.
…ling (#168991) * refactor(sessions): simplify history request capture and list reads Clone typed history parameters once while retaining entry and environment pruning. Let the native list reader validate the selected file instead of repeating host stat probes around dispatch. A replacement immediately after the native read is best effort; consumer authority and multi-store checks remain. Provenance: request capture from #147914; redundant host probes from #165470. Net production reduction: 94 lines. Focused proof: 123 tests passed; core typecheck and independent review passed. Existing lint-suppression allowlist failure in untouched #168002 test-support files is not changed. * refactor(sessions): simplify read and reconcile lifecycles Remove speculative registry retargeting, reader custody and generation protocols, reconcile priority reservations and successor handoffs. Keep one current-authority check at effects, atomic projection finalization, bounded resources and ordinary write-capable shutdown settlement. Retain simple session-boundary fairness for the production incident recorded in #165107 and bounded backoff for the human report #115908. Unsupported mid-call topology changes and failed derived projection preparation are best effort until the next request or restart. No schema, stored-data, retention, permission or public API change. Validation: 36 focused history/bootstrap tests pass; corrected Testbox shutdown and registry controls pass; both import-cycle checks report zero cycles; core typecheck and targeted lint pass. Review findings addressed, including empty archive-path semantics and immediate async-consumer rejection handling. Publication remains blocked before PR/merge: still-open heartbeat PR #167796 protects session-logical-entry-read.worker.test.ts, whose obsolete pending-registration assertions require a scope exception. Full sessions proof is incomplete. Unchanged baseline suppression and UI test-root budget failures are recorded in the lane ledger. * test(sessions): retire obsolete registry interleavings * test(sessions): retire obsolete history lifecycle guards * test(sessions): retire obsolete read lifetime assertions * test(sessions): keep reclamation checks at the write boundary * test(sessions): retire obsolete incognito reconcile handoffs * test(sessions): retire remaining registry and handoff fixtures * refactor(sessions): remove unused registry settlement waiters * fix(sessions): bound reconcile admission and close readiness safely * style(sessions): format merged target cache imports * test(sessions): decouple cross-agent recovery ordering * fix(sessions): keep registry settlement independent of callers * fix(sessions): reauthorize incognito context publication * fix(sessions): preserve absent incognito context reads
…ling (openclaw#168991) * refactor(sessions): simplify history request capture and list reads Clone typed history parameters once while retaining entry and environment pruning. Let the native list reader validate the selected file instead of repeating host stat probes around dispatch. A replacement immediately after the native read is best effort; consumer authority and multi-store checks remain. Provenance: request capture from openclaw#147914; redundant host probes from openclaw#165470. Net production reduction: 94 lines. Focused proof: 123 tests passed; core typecheck and independent review passed. Existing lint-suppression allowlist failure in untouched openclaw#168002 test-support files is not changed. * refactor(sessions): simplify read and reconcile lifecycles Remove speculative registry retargeting, reader custody and generation protocols, reconcile priority reservations and successor handoffs. Keep one current-authority check at effects, atomic projection finalization, bounded resources and ordinary write-capable shutdown settlement. Retain simple session-boundary fairness for the production incident recorded in openclaw#165107 and bounded backoff for the human report openclaw#115908. Unsupported mid-call topology changes and failed derived projection preparation are best effort until the next request or restart. No schema, stored-data, retention, permission or public API change. Validation: 36 focused history/bootstrap tests pass; corrected Testbox shutdown and registry controls pass; both import-cycle checks report zero cycles; core typecheck and targeted lint pass. Review findings addressed, including empty archive-path semantics and immediate async-consumer rejection handling. Publication remains blocked before PR/merge: still-open heartbeat PR openclaw#167796 protects session-logical-entry-read.worker.test.ts, whose obsolete pending-registration assertions require a scope exception. Full sessions proof is incomplete. Unchanged baseline suppression and UI test-root budget failures are recorded in the lane ledger. * test(sessions): retire obsolete registry interleavings * test(sessions): retire obsolete history lifecycle guards * test(sessions): retire obsolete read lifetime assertions * test(sessions): keep reclamation checks at the write boundary * test(sessions): retire obsolete incognito reconcile handoffs * test(sessions): retire remaining registry and handoff fixtures * refactor(sessions): remove unused registry settlement waiters * fix(sessions): bound reconcile admission and close readiness safely * style(sessions): format merged target cache imports * test(sessions): decouple cross-agent recovery ordering * fix(sessions): keep registry settlement independent of callers * fix(sessions): reauthorize incognito context publication * fix(sessions): preserve absent incognito context reads
What Problem This Solves
Fixes: after a Gateway restart, an agent whose database is tiny stays unavailable (
UNAVAILABLE … has not completed startup inspection and preparation) for as long as every earlier deferred agent takes to finish its own startup preparation, with no log output while it waits.User Impact
User impact: each deferred agent becomes available as soon as its own database is opened and its sessions are prepared; a large or slow agent no longer holds smaller agents' sessions, cron jobs, and chat history hostage. Operators now see per-agent phase durations on recovery/failure and a progress warning every 60 s while recovery is pending. No config, schema, or stored-data changes.
Why This Change Was Made
Deferred startup recovery ran each agent's whole preparation (credentials refresh, session migration, model refresh) through one FIFO. Opening the database and session migration are agent-local and now run per agent (two concurrent opens as before, up to four concurrent session migrations, readiness awaited without holding a slot). Only credential/model publication and the final admission keep the serialized turn, because the secrets snapshot is global and each refresh can include only admitted or borrowed auth stores. All existing authority checks on that turn (config identity, secrets revision, auth store, prepared model, deletion journal) are unchanged. Migration uses the same agent-database configuration guard the open step already used. No deadline fails a slow agent; slowness is now visible instead of silent.
Evidence
Production incident (OpenClaw 2026.9.8, three agents, host load 50–70): all three deferred agents finished their writable open, including a 44 s full integrity check on a 1.69 GB store, within ~6 minutes of startup. Their recoveries then completed strictly one after another, at +22 min, +41 min, and +42 min. The last agent's store was 12 MB and its own preparation took 64 s; the other ~36 minutes were spent waiting for the FIFO. The Gateway main thread was saturated (event-loop utilization 1.0, p99 delay 1–3.7 s), so each preparation crawled, and nothing was logged between the deferral warning and recovery. Integrity checks, activation timing, and reindexing were ruled out from the same log.
Regression test (
src/gateway/server-agent-database-startup.preparation.test.ts, realwithAgentDatabaseStartupAdmission+activateGatewayAgentDatabaseStartup). On the original code it fails as in the incident: the small agent staysagent-database-inspection-pendingwhile the large agent's session migration is blocked. With the fix it passes. The same test lets the small agent's secrets publication replace the runtime config mid-migration and checks that the large agent still recovers. It also covers the phase durations, the progress warning with fake time, and timer cleanup. Other cases cover holding the publication turn through models and the final deletion check, the readiness wait happening outside the migration pool, and refusal on agent removal, database move, deletion, and shutdown.Checks:
server-agent-database-startup.preparation.test.ts7 passed;server-agent-database-startup.test.ts(real native admission lifecycle) 12 passed;pnpm tsgo, scoped oxlint, oxfmt,git diff --checkclean. Codex autoreview (P2 threshold): scoped-clean.Consumer suites: all 11 test files that import the startup admission owner (preflight lifecycle/schema-only/startup-index/startup-prepared, admission, update canary, spawn broker, doctor container upgrade, run-main, and both Gateway startup files) passed on Blacksmith Testbox
tbx_01m44b4ffw6da35gjk3jfzz78qat this head: 106 tests, exit 0.Synthetic reproduction under CPU contention (real Gateway from a fresh build, isolated state, three agents: two ~1.6 GB stores with 128/144 pending transcript-projection rebuilds, one 672 KiB store; agents SIGKILLed for stale leases without clean-close receipts; Gateway pinned to 2 cores shared with 4
stress-ngworkers; per-agent scoped history RPC polled every 5 s). The tiny agent sorts after the large ones, matching production ordering:On the base, the tiny agent passed its integrity gate at T+57 s, then waited 24.6 min behind both large agents' transcript rebuilds. On the fix, it recorded zero migration-permit wait and zero publication wait while both large migrations were still running. The new phase durations attribute the slow phase directly: the large agents spent 1,034 s and 1,879 s in
migration; secrets, models, and publication took about 2–3 s each. Progress warnings fired every 60 s with the current phase. No agent ended degraded.Caveat on the large-agent rows: the base ran on AWS
c7a.8xlarge(32 vCPU) and the fix on Hetznerccx33(8 vCPU) after two AWS allocation failures, so absolute times are not hardware-matched. The transcript-reconcile pool has a single worker (MAX_WORKERS = 1insession-transcript-reconcile-pool.ts), so the two large rebuilds now interleave in that worker instead of running one after the other. The first large agent can therefore finish later than it would have at the head of the old FIFO. This PR does not change that pool; per-store prioritization there is a possible follow-up.