Repository navigation
perf(gateway): first message after startup stalls on lazy model-catalog and plugin-registry loads - #118465
perf(gateway): first message after startup stalls on lazy model-catalog and plugin-registry loads#118465zeroaltitude wants to merge 14 commits into
Conversation
…yping latency Two changes for the Discord presence-indicator latency investigation: Ingress pruning moves from pruneIntervalMs: 0 (a legacy-behavior carryover from the durable-ingress migration) to the standard hourly cadence. The old setting ran a write transaction with unindexed updated_at sorts on the shared state DB ahead of EVERY inbound Discord message — pre-dispatch, pre-typing latency that grew with retained rows (caps are 5,000 rows per status). Slack already prunes hourly; TTLs and caps are unchanged. First typing start per dispatch now logs one INFO line with sinceMessageMs (Discord message creation → typing call: the user-perceived gap, network + ingress + preflight included) and sinceDispatchMs (dispatch → typing). Their difference isolates the pre-dispatch share — the segment invisible to gateway-internal prompt_build→first_llm timing, which measured p50 21ms while operators observed multi-second indicator lag. Replaces the reverted env-gated [oc-typing-lag] console timers with an always-on recorded fact that needs no rebuild to consult. Validation: node scripts/run-vitest.mjs extensions/discord/src/monitor (988 passed); pnpm tsgo:extensions green; oxlint/oxfmt clean.
Per-agent runtime materialization re-runs the full plugin registry load synchronously on the main thread; a slow one freezes the whole gateway (observed: ~30s liveness stalls on each agent's first message, with all in-flight dispatches' traces flushing together on recovery). The existing aggregate timing is debug-level and unattributed. When a registry load exceeds 1s, warn with per-plugin candidate timings (top 10 >=50ms), discovery timing, cache key, subagent mode, and the caller stack, so the next stall names its owner.
…r dispatch stage traces Instrumentation from tonight's stall hunt showed each agent's FIRST message paying a multi-second synchronous plugin registry load at dispatch time (per-agent-workspace cache keys; observed 4s for 158 plugins, freezing the event loop and every concurrent dispatch). - Prewarm every configured agent workspace's runtime plugin registry in the post-ready prewarm scheduler, one per event-loop turn, so the dispatch path always hits a warm cache key. - Split the opaque attempt-workspace startup-stage span with sub-marks (compaction-runtime, runtime-snapshot, attempt-entry) so remaining cold-run cost names its owner. - Route the discord inbound→typing latency line through the console logger: the pino child logger only reached the file log, which is why the line went unnoticed in journald all week.
…atter The prior fix routed the inbound→typing latency line through `info` from plugin-sdk/runtime-env — which is a ThemeFormatter (string colorizer), not an emitter, so the line was formatted and discarded. Zero samples landed anywhere since the pino path was removed in the same change. Diagnosed by Tank (agent) tracing globals.ts:37. logInfo from plugin-sdk/logging-core is the always-on console emitter sibling discord files already use.
Upstream openclaw#116261 bounded prepared-runtime startup work, deferring model catalog preparation to first use — measured cost on an agent's first message: ~16s inside loadResolvedPublishedModelCatalogOwner (live provider discovery with 5s/provider timeouts plus a manifest-model scan) before the reply pipeline's first traced phase, with no typing indicator. Warm each agent's catalog owner from the post-ready prewarm scheduler, after the runtime plugin registries it depends on: boot stays bounded (off the startup critical path) and first messages hit a warm catalog.
|
Codex review: needs real behavior proof before merge. Reviewed September 1, 2026, 6:48 PM ET / 22:48 UTC. ClawSweeper reviewWhat this changesThe branch adds Gateway/Discord latency diagnostics, changes Discord ingress pruning from per-admission to hourly, and prewarms agent plugin registries and full model catalogs after Gateway readiness. Regression provenancePossible regression — probable (reviewed change; known regression link). No predecessor PR is attributed. Merge readiness⛔ Blocked until stronger real behavior proof is added - 11 items remain Keep this recently updated draft open for correction rather than stale cleanup. Its two post-ready prewarms reintroduce the event-loop and lifecycle hazards that current main deliberately avoids; the remaining diagnostics could be evaluated only after the unsafe work and inaccurate metrics are removed. Priority: P1 Review scores
Verification
How this fits togetherGateway startup publishes bounded, lifecycle-owned agent runtime facts before live turns begin. Discord ingress then admits messages and agent dispatch consumes those facts; the proposed idle prewarm instead starts extra registry and catalog work after readiness. flowchart LR
A[Gateway startup] --> B[Published static runtime facts]
B --> C[Agent turn admission]
D[Discord ingress] --> C
E[Post-ready idle task] --> F[Registry and catalog work]
F --> C
C --> G[Typing feedback]
G --> H[Operator diagnostics]
Before merge
Findings
Agent review detailsSecurityNone. PR surfaceSource +127, Tests +49. Total +176 across 7 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep lifecycle-owned static dispatch facts as the only startup preparation; remove the catalog and registry idle tasks, preserve ingress limits at admission, and evaluate any useful diagnostics as a narrow separately proven change. Do we have a high-confidence way to reproduce the issue? Yes, from source: the introduced idle tasks call full-catalog and synchronous registry loaders after a one-time idle check. The PR does not include a current-head redacted runtime trace that demonstrates the claimed before/after behavior. Is this the best way to solve the issue? No. Current main already publishes static dispatch facts through the lifecycle and intentionally leaves live provider catalogs request-owned; moving those loads into an idle Gateway task is the wrong owner boundary. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against a022a71c92e8. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (15 earlier review cycles; latest 8 shown)
|
The prewarm step imported `ensureRuntimePluginsLoaded` from
`../agents/runtime-plugins.js`. That symbol does not exist — the module's
only export is `loadAgentRuntimePluginRegistryHandle`, whose params type
(`{ config?, workspaceDir?, ... }`) already matches what this call site
passes. `pnpm tsgo:core` fails with TS2339 on the import, so any tree
carrying this commit does not typecheck; it reached `origin/integration`
and broke the build there.
Swapped to the real export. Behavior is the intended one either way:
`loadAgentRuntimePluginRegistryHandle` resolves the same per-workspace
registry cache key dispatch uses, so warming it here still moves the
multi-second cold load off an agent's first message.
Note this branch has a second, pre-existing typecheck failure that this
commit deliberately does not touch: `resolveConfiguredAgentWorkspaceDirs`
is imported from `agent-scope-config.js` but is only defined on
`fix/metadata-snapshot-reuse-and-gates`. The branch therefore cannot
typecheck standalone — it needs that branch merged, or the helper folded
in. Left for whoever owns the split, since fixing it here would duplicate
the definition and conflict on merge.
Validation: with this change, `pnpm tsgo:core` on integration (where the
workspace-dirs helper is present) is clean. oxlint clean on the touched
file.
Co-Authored-By: Claude Opus 5 <[email protected]>
…ting negative First live sample of this metric read `sinceMessageMs=-347`, which says typing fired 347ms before the message existed. Discord stamps the message on its own clock and we read ours; the two are not synchronised, so a raw negative means the real gap was smaller than the local/remote clock drift, not that anything went backwards. Left alone this is worse than cosmetic. `sinceMessageMs` is the field that captures the whole user-perceived gap — network delivery plus ingress plus preflight — so with ~350ms of drift every future sample silently under-reports by that much, and a negative one is unusable outright. Negative values now report `sinceMessageMs=0` with `sinceMessageClamped=true` and the raw delta preserved as `rawSinceMessageMs`, plus an inline note that the gap fell within clock drift. Clamping without keeping the raw value would throw away the drift magnitude, which is the one thing that tells an operator how much to distrust the unclamped samples. Non-negative values are unchanged; `sinceDispatchMs` is computed from a single local clock and was never affected. Validation: oxlint and oxfmt --check clean on the touched file; git diff --check clean. `pnpm tsgo:extensions` cannot pass on this branch standalone for a reason unrelated to this change — `server-startup-handler-prewarm.ts` imports `resolveConfiguredAgentWorkspaceDirs`, which only exists on `fix/metadata-snapshot-reuse-and-gates` — so the typecheck was verified on integration, where that helper is present. Co-Authored-By: Claude Opus 5 <[email protected]>
…-and-tracing Resolutions: - run-loop.ts: main replaced the raw runLoopIterations counter with a retry budget, so the first-attempt instrumentation now keys off runRetryBudget.attemptsDispatched === 0. - attempt-dispatch-preparation.ts: union of our attempt-entry stage mark and main's effectiveModel plumbing. Fixed a branch-invariant violation found during the merge: this branch imported resolveConfiguredAgentWorkspaceDirs from agent-scope-config, but that helper exists only on a sibling branch, so this branch could not typecheck standalone against origin/main and was only ever green inside integration. Replaced with a local helper over listAgentIds + resolveAgentWorkspaceDir, so the branch builds on its own; the sibling introduces the shared helper and whichever lands first wins on merge. Also fixed a mock that never intercepted anything: the prewarm test mocked 'ensureRuntimePluginsLoaded' on ../agents/runtime-plugins.js, which that module does not export - the real symbol is loadAgentRuntimePluginRegistryHandle, which the source has called since 653b9c4. The runtime-plugins prewarm assertions were therefore running against the unmocked module. Corrected, and the workspace-dir stub moved from the aggregate helper to resolveAgentWorkspaceDir so it still intercepts after the inlining above. Validation: - pnpm tsgo:core -> exit 0, 0 errors - pnpm vitest run server-startup-handler-prewarm.test.ts -> 7 passed - oxlint clean; git diff --check clean
|
Closing this draft because current main assigns static preparation to the startup lifecycle, while the branch's idle catalog and synchronous-registry prewarm crosses that ownership boundary and can increase background work without proving a safe freshness contract. The useful diagnostic portion has been rebuilt independently on Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
What Problem This Solves
The branch was created after a production gateway's first inbound message paid roughly 16 seconds of lazy model-catalog and plugin-registry initialization. The stall was user-visible and the responsible stages were not attributed in logs.
Why This Change Was Made
It combines latency instrumentation with post-ready prewarming:
User Impact
The diagnostics make first-turn stalls substantially easier to attribute. However, the prewarm portion no longer matches current-main ownership: current main already publishes the dispatch-equivalent registry, while provider catalogs are intentionally request-owned. The idle prewarm therefore bypasses lifecycle owners and does not meet the current upstream usefulness/safety bar.
Current recommendation: retire this draft rather than merge the prewarm design. If maintainers want the instrumentation independently, extract it into a smaller diagnostic-only change.
Evidence
The motivating Linux gateway recorded inbound-to-typing latency and slow registry work, and its cold
before_agent_replystage fell from roughly 10–16 seconds to about 1.8 seconds after deployment. Focused startup-prewarm coverage passed 7/7 on branch heade42f0d148ce377fee12d6e0eb5e9d91fb678e8b6.The later portfolio review changed the recommendation: tracing current main showed that equivalent registry publication is already owned elsewhere and that the remaining catalog work should not be initiated from an idle startup task. That makes the observed historical speedup insufficient evidence for merging this implementation today.
🤖 Generated with Claude Code
Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).