Skip to content

fix(gateway): prevent chat metadata from blocking concurrent RPCs - #119369

Merged
fuller-stack-dev merged 13 commits into
openclaw:mainfrom
fuller-stack-dev:codex/chat-metadata-canonical-snapshot
Aug 5, 2026
Merged

fuller-stack-dev merged 13 commits into
openclaw:mainfrom
fuller-stack-dev:codex/chat-metadata-canonical-snapshot

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

Related: #118846

What Problem This Solves

Fixes an issue where users opening chat with a large model/skill configuration could see chat.metadata take tens of seconds, duplicate that work across concurrent requests, and delay unrelated Gateway RPCs during the same interval.

Why This Change Was Made

Review findings and root-cause judgment

The independent review compared four credible causes: request-time model discovery, command/skill scanning, duplicate concurrent amplification, and broader process-wide event-loop starvation. Current canonical main still constructs model and command metadata on the RPC path; deterministic instrumentation proved equivalent concurrent requests duplicate that work, while user-shaped Gateway runs showed worktrees.branches delayed in the same request window.

The best-fit fix is therefore the lifecycle owner, not another request cache: one prepared chat metadata generation derived from the published config/catalog/auth/plugin/skills facts, with projections shared by equivalent callers. The prepared model runtime already owns catalog and auth publication; auth mutations invalidate and republish that owner. Skill and plugin lifecycle signals invalidate the same metadata generation. models.list remains the explicit discovery/freshness API.

A final review found a separate lifecycle deadlock in the first implementation: a worker scheduled for epoch 1 could absorb a second invalidation, commit epoch 2, then leave the replacement gate unresolved because completion still checked epoch 1. The final patch makes gate settlement belong to the generation actually committed and prevents stale/non-owning workers from settling it.

This does not claim to solve every process-wide event-loop starvation source in #118846. It removes the proven request-time metadata work at its canonical owner. It adds no config, protocol, storage, or compatibility fallback, and does not modify Control UI model-control behavior.

Evidence map

  • Entry points: chat.metadata and chat startup metadata.
  • Canonical owner: prepared model/auth lifecycle plus skill/plugin/config generation.
  • Hot-path callee: snapshot projection only; no provider discovery, persisted auth rediscovery, plugin activation, or filesystem skill scan.
  • Sibling boundary: models.list retains explicit fresh discovery behavior.
  • Failure boundary: generation replacement rejects waiters on failure and recovers on a later publication.

AI-assisted implementation and review.

User Impact

Chat startup and metadata reads use a prepared snapshot, equivalent concurrent callers share one projection, warm reads are effectively constant-time, and unrelated Gateway RPCs are not held behind request-time metadata discovery/scanning.

Evidence

Final head: c32625d732b006cba081a48f53049e4088c98c76
Canonical base: 75ef5aebecb8e808eaa8a0503fb4b466703c5306

Root-cause regression and local/static proof

  • Deterministic P1 red proof on prior PR head 003cc7e06e48: Blacksmith Testbox lease tbx_01kz83cz960zfq2sbayqwabcmp, run https://github.com/openclaw/openclaw/actions/runs/30975684559, command pnpm test src/gateway/server-methods/chat-metadata-runtime.test.ts -- -t 'resolves the replacement gate after a coalesced second invalidation'. Both coalesced refreshes completed, but the following read remained blocked past 100 ms. The same proof passed after the repair.
  • Focused lifecycle proof: lease tbx_01kz83n6q0j1rbnjj1a4966jsa, run https://github.com/openclaw/openclaw/actions/runs/30975893921. chat-metadata-runtime.test.ts (9), prepared-model-runtime.lifecycle.test.ts (40), and server-lifetime-sidecars.test.ts (1): 50 tests passed.
  • Final targeted regression plus pnpm check:changed: exit 0. Core and core-test tsgo, both changed-file lint passes, formatting, dead exports, plugin/dependency boundaries, database guards, and runtime import cycles all passed.
  • Focused coverage includes equivalent concurrent single-flight, snapshot-only reads, config/catalog-auth/skills/plugin invalidation, double invalidation, replacement waiting, failure/recovery, unchanged-generation reuse, command degradation, and projection failure eviction/retry.
  • Exact-head branch autoreview: clean, no accepted/actionable findings, confidence 0.98; TruffleHog clean.

Final Crabbox/Testbox user-shaped Gateway proof

Provider: blacksmith-testbox through the Crabbox wrapper
Lease: tbx_01kz84b3kw4cq2pw111hswhcfg (violet-krill)
Run: https://github.com/openclaw/openclaw/actions/runs/30976475675
Environment: Linux x86_64, Node 24.19.0, pnpm 11.15.1, 41 configured models, 1,000 workspace skill manifests
Scenario script SHA-256: 268539eb0f094808b89c27137c80a95fbdbfa68fd2f4a0ea54e3c57d9bf66320
Exact remote command: CHAT_METADATA_BOOTSTRAPPED=1 bash /tmp/chat-metadata-crabbox-scenario.sh 75ef5aebecb8e808eaa8a0503fb4b466703c5306 c32625d732b006cba081a48f53049e4088c98c76 "$PWD"

The same run started a real Gateway for base and head, issued two concurrent chat.metadata calls together with worktrees.branches and health, then issued a warm metadata call, invalid input, and a recovered valid call.

Observation Canonical base Final head
Gateway startup 106,139 ms 66,108 ms
chat.metadata.a 266.811 ms 73.501 ms
chat.metadata.b 268.254 ms 74.644 ms
worktrees.branches 301.872 ms 134.659 ms
health 48.587 ms 65.034 ms
warm chat.metadata 83.195 ms 3.051 ms
invalid input INVALID_REQUEST, 1.955 ms INVALID_REQUEST, 1.905 ms
recovered metadata 79.227 ms 3.300 ms

Both cases returned 41 models and 267 commands. Concurrent payloads were identical. Model fingerprint was 4453a94a585073ce2315e6440a5304759f8f27845c371ca9a8ddfad5e5a0ffa8; command fingerprint was 73bf1d7e0a88e50d12961c5244fd062266a097d5308c13acdd07a173d71a1acd. File tracing was available but recorded zero request-window lines for both cases, so no implementation inference is drawn from it.

Source-blind behavior validation passed all seven clauses: equivalent concurrent snapshots, 41-model result, unrelated-RPC liveness, warm reuse, invalid-input rejection, recovery, and base/head catalog equivalence.

Direct AWS supporting proof

Earlier direct AWS proof used lease cbx_d593332898f7 (crimson-krill), AWS c7a.8xlarge, Linux x86_64, Node 24.18.1, pnpm 11.15.1, public networking, and no Tailscale:

Three later fresh direct-AWS leases could not reach provider SSH and executed no scenario code; final corrected-head proof therefore used the trusted Blacksmith Testbox backend above rather than presenting an infrastructure failure as product evidence.

@fuller-stack-dev
fuller-stack-dev requested a review from a team as a code owner August 4, 2026 23:14
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Aug 4, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Aug 4, 2026
@clawsweeper

clawsweeper Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 5, 2026, 1:08 AM ET / 05:08 UTC.

ClawSweeper review

What this changes

The PR moves Gateway chat metadata from request-time model, auth, plugin, and skill discovery into a lifecycle-prepared snapshot shared by concurrent chat requests.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⛔ Blocked by patch quality or review findings - 10 items remain

Keep open: the lifecycle-owned snapshot is the right direction, but this head introduces three P1 regressions in startup availability, persisted-profile visibility, and invalidation coherence.

Priority: P1
Reviewed head: c32625d732b006cba081a48f53049e4088c98c76

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The supplied runtime evidence is strong, but three source-proven P1 regressions leave this head not ready to merge.
Proof confidence 🦞 diamond lobster (5/6) Not applicable: The author is a repository MEMBER, so the external-contributor proof gate does not apply; the supplied exact-head Testbox Gateway run is still strong supporting evidence.
Patch quality 🧂 unranked krab (1/6) 3 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The author is a repository MEMBER, so the external-contributor proof gate does not apply; the supplied exact-head Testbox Gateway run is still strong supporting evidence.
Evidence reviewed 7 items Current request-time behavior: Current main builds models and commands directly for chat metadata, so the startup-allowed RPC has a response path before the new lifecycle generation exists.
Startup contract regression: The method descriptor explicitly marks chat.metadata as startup-available, while the new normal lifecycle does not refresh until post-attach sidecars and the reader throws when no generation exists.
Prepared auth is absent on cold startup: The new generation substitutes an empty auth store when no runtime store was previously published; the projector then treats it as authoritative and deliberately skips persisted-store loading.
Findings 3 actionable findings [P1] Preserve chat metadata availability before sidecars
[P1] Carry persisted profiles into the prepared generation
[P1] Retry a projection invalidated while it is awaiting
Security None None.

How this fits together

Gateway chat metadata feeds chat startup and metadata RPC responses with available models and commands. The new lifecycle prepares that response from model/auth publication plus skill and plugin state, then serves cached projections to clients.

flowchart LR
  A[Gateway client] --> B[Chat metadata request]
  B --> C[Prepared metadata lifecycle]
  D[Model and auth publication] --> C
  E[Skill and plugin changes] --> C
  C --> F[Shared metadata generation]
  F --> G[Chat startup and metadata response]
Loading

Before merge

  • Preserve chat metadata availability before sidecars (P1) - chat.metadata is explicitly startup-available, but normal startup does not prepare this runtime until post-attach sidecars. Between HTTP bind and that refresh, this new throw replaces main's on-demand response path; publish it before dispatch or return the established retryable startup shape without restoring request-time discovery.
  • Carry persisted profiles into the prepared generation (P1) - On a cold Gateway, no runtime auth snapshot is published by prepared-model construction, so this fallback makes the store empty. The downstream projector treats that empty store as authoritative and skips persisted auth loading, causing existing profile-backed models to appear unavailable.
  • Retry a projection invalidated while it is awaiting (P1) - A session-specific profile projection is lazy. If config, auth, skill, or plugin invalidation runs while this await is pending, current is cleared and a replacement gate is opened, yet the old projection is still returned. Recheck generation identity or epoch after the await and retry through the replacement gate.
  • Resolve merge risk (P1) - Existing persisted auth profiles can make configured models appear unavailable after a cold Gateway start.
  • Resolve merge risk (P1) - A client may call the explicitly startup-available chat.metadata RPC after HTTP bind but before metadata sidecars refresh it, receiving an error instead of the established startup behavior.
  • Resolve merge risk (P1) - A session-specific metadata read can complete with stale model/auth data after a config, auth, skill, or plugin invalidation.
  • Complete next step (P2) - This protected maintainer PR has concrete P1 repairs, but its Gateway/auth lifecycle boundary needs owner review before the branch is updated.
  • Improve patch quality - Preserve startup-allowed chat.metadata behavior before post-attach sidecars run.
  • Improve patch quality - Publish the effective persisted auth store at the lifecycle boundary and cover a cold-start profile-backed model.
  • Improve patch quality - Add a deferred session-profile invalidation test and retry instead of returning its obsolete generation.

Findings

  • [P1] Preserve chat metadata availability before sidecars — src/gateway/server-methods/chat-metadata-runtime.ts:437-441
  • [P1] Carry persisted profiles into the prepared generation — src/gateway/server-methods/chat-metadata-runtime.ts:131-135
  • [P1] Retry a projection invalidated while it is awaiting — src/gateway/server-methods/chat-metadata-runtime.ts:474
Agent review details

Security

None.

PR surface

Source +573, Tests +460. Total +1033 across 26 files.

View PR surface stats
Area Files Added Removed Net
Source 19 858 285 +573
Tests 7 538 78 +460
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 1396 363 +1033

Review metrics

Metric Value Why it matters
Production versus test LOC production +855/-285; tests +541/-78 The net production growth is justified only if it delivers one correct lifecycle owner; the three P1 regressions must be repaired before that added surface is acceptable.

Stored data model

Persistent data-model change detected: serialized state: src/agents/auth-profiles/runtime-snapshots.test.ts, serialized state: src/agents/auth-profiles/runtime-snapshots.ts, serialized state: src/gateway/server-methods/models-list-auth-resolver.ts, unknown-data-model-change: src/gateway/server-chat-metadata-lifecycle.ts, unknown-data-model-change: src/gateway/server-methods/chat-metadata-runtime.test.ts, unknown-data-model-change: src/gateway/server-methods/chat-metadata-runtime.ts, and 14 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Repair lifecycle publication before merge (recommended)
    Preserve startup availability, carry a cold-start effective auth snapshot, and retry projections invalidated while awaiting before re-running exact-head Gateway proof.

Technical review

Best possible solution:

Keep a single lifecycle-owned metadata generation, but publish its effective auth facts before use, preserve the startup RPC contract without restoring request-time discovery, and retry any projection superseded during its await.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes three focused paths: call chat.metadata after HTTP bind before post-attach sidecars, start with a persisted auth profile but no runtime snapshot, or invalidate during a deferred session-profile projection.

Is this the best way to solve the issue?

No. The lifecycle owner is appropriate, but this head must preserve the startup contract, publish authoritative auth facts, and recheck the generation after an awaited lazy projection.

Full review comments:

  • [P1] Preserve chat metadata availability before sidecars — src/gateway/server-methods/chat-metadata-runtime.ts:437-441
    chat.metadata is explicitly startup-available, but normal startup does not prepare this runtime until post-attach sidecars. Between HTTP bind and that refresh, this new throw replaces main's on-demand response path; publish it before dispatch or return the established retryable startup shape without restoring request-time discovery.
    Confidence: 0.98
  • [P1] Carry persisted profiles into the prepared generation — src/gateway/server-methods/chat-metadata-runtime.ts:131-135
    On a cold Gateway, no runtime auth snapshot is published by prepared-model construction, so this fallback makes the store empty. The downstream projector treats that empty store as authoritative and skips persisted auth loading, causing existing profile-backed models to appear unavailable.
    Confidence: 0.97
  • [P1] Retry a projection invalidated while it is awaiting — src/gateway/server-methods/chat-metadata-runtime.ts:474
    A session-specific profile projection is lazy. If config, auth, skill, or plugin invalidation runs while this await is pending, current is cleared and a replacement gate is opened, yet the old projection is still returned. Recheck generation identity or epoch after the await and retry through the replacement gate.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 75ef5aebecb8.

Labels

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • remove proof: sufficient: Current real behavior proof status is not_applicable, not sufficient.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P1: The branch can break normal Gateway chat metadata for startup clients and existing stored auth profiles.
  • merge-risk: 🚨 compatibility: It replaces established request-time chat metadata behavior with lifecycle readiness and can change results during startup or reload.
  • merge-risk: 🚨 auth-provider: The cold-start prepared-auth fallback can hide existing persisted provider profiles from model availability.
  • merge-risk: 🚨 availability: An explicitly startup-available Gateway RPC can fail before post-attach metadata preparation completes.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦞 diamond lobster and patch quality is 🧂 unranked krab.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: The author is a repository MEMBER, so the external-contributor proof gate does not apply; the supplied exact-head Testbox Gateway run is still strong supporting evidence.

Evidence

What I checked:

Likely related people:

  • Vincent Koc: Current-main blame attributes the replaced chat-metadata request path to this commit; deeper local history is incomplete. (role: recent area contributor; confidence: low; commits: 8f2850d83e90; files: src/gateway/server-methods/chat-history-handler.ts)
  • openclaw/openclaw-secops: CODEOWNERS assigns agent auth-profile and Gateway auth paths to this team, including the prepared-auth behavior changed here. (role: auth surface owner; confidence: high; files: src/agents/auth-profiles/runtime-snapshots.ts, src/gateway/server-methods/models-list-auth-resolver.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-04T23:20:35.491Z sha 0af005e :: found issues before merge. :: [P1] Keep metadata reads coherent during invalidation | [P1] Publish only after the replacement gate is readable | [P1] Invalidate metadata at the direct hot-reload stale edge | [P2] Retain the metadata listener sidecar for shutdown
  • reviewed 2026-08-05T04:04:16.928Z sha d57e5a0 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-05T04:30:45.272Z sha 003cc7e :: found issues before merge. :: [P1] Resolve the active replacement after a coalesced invalidation

@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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 5, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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 Aug 5, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Aug 5, 2026
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Exact-head update for d605e032fea4da14befbcbb48a87dafa40d205a4:

  • Reproduced and fixed the lazy projection invalidation race. A deferred session projection returned the obsolete first generation after replacement had published; the read now rechecks generation identity after both success and failure and retries through the replacement gate.
  • Reproduced and fixed an unmatched publication event found by final autoreview. Direct invalidation without a replacement emitted only invalidated; it now immediately emits terminal failed, while replacement-owned transitions still finish with their later published/failed event.
  • Independently falsified the other two prior review claims: chat.metadata is in STARTUP_UNAVAILABLE_GATEWAY_METHODS until sidecars finish, and canonical persisted auth SQLite stores force full secrets preparation and runtime auth publication before model/metadata sidecars.

Proof:

@fuller-stack-dev

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@fuller-stack-dev
fuller-stack-dev merged commit 77f7560 into openclaw:main Aug 5, 2026
119 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via squash.

@fuller-stack-dev
fuller-stack-dev deleted the codex/chat-metadata-canonical-snapshot branch August 5, 2026 06:10
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 5, 2026
…enclaw#119369)

* fix(gateway): serve chat metadata from prepared snapshots

* fix(gateway): make chat metadata replacement atomic

* fix(gateway): keep metadata contract cycle-free

* fix(gateway): settle coalesced metadata replacement

* fix(gateway): retry invalidated metadata projections

* fix(gateway): terminate unowned metadata invalidation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant