Skip to content

fix: prevent Gateway stalls with multiple workspaces - #130706

Closed
steipete wants to merge 43 commits into
mainfrom
codex/gateway-metadata-ownership
Closed

steipete wants to merge 43 commits into
mainfrom
codex/gateway-metadata-ownership

Conversation

@steipete

@steipete steipete commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

The useful correctness and cleanup work from this PR has landed in 83 focused PRs, with the complete replacement map and per-cut evidence in #142100. This body replaces the original broad implementation proposal. #130706 remains closed unmerged as replaced by that series, with its branch preserved; #142100 remains closed unmerged as the completed decomposition/reference map.

The focused repairs preserve selected model identities and keep their metadata, authentication, pricing, limits and runtime ownership consistent. They also correct configuration publication, channel controls, media, compaction and fallback reporting while removing duplicate paths. Actual landed production accounting is 5,453 lines added / 5,508 removed: net −55, measured once per merge against its first parent. Including the separate UI repair #143889 gives net −49. Tests, QA scenarios and tooling are counted separately; no forecast or unmerged work contributes.

All 744 original paths across 19 neighborhoods have recorded dispositions. The general collection framework and extra storage/listener/retention plumbing, separate projector, unsupported import/mechanical changes and blanket constrained-ACP refusal were not adopted. Broader captured-source, sparse-donor/route-reader and compaction proposals also remain unadopted for the ownership/provenance defects documented in #142100. Existing canonical owners were reused.

The previous three cuts—#144438, #144354 and #144474—have verified native merges, required CI and qualified runtime evidence. Source tests, compiled CLI/API checks, real Gateway lifecycle, local loopback peers and authenticated external scenarios remain separate. Historical and production-identical proof keeps its original revision; #144474's final test-only adapter carries the earlier compiled proof. #140488's changed hook behavior passed, but its full live driver remains failed on cleanup-confidence warnings. The map preserves the five early execution/provider unknowns and all failed-attempt qualifications.

The September 13 continuation landed #147830 and #147849, reducing production by another nine lines. These repair captured image model/resize selection and exact configured-row transport facts for registered harnesses. Each passed its own focused checks, independent review, normal build, scoped compiled proof and exact-head CI, followed by native merge verification. The image proof uses real registered providers and SSE loopback; the harness proof uses public CLI/SDK selection through a real synthetic plugin. Hosted inference and the separate non-idempotent alias handoff remain unclaimed.

The September 12 continuation landed #146113, #146183, #146134 and #146261: usage-price cache refresh, cold TTS catalog selection, declared reasoning tiers, and static Kimi aliases. These four reduce production by another 31 lines. Each has verified native merge, exact-head CI and qualified runtime proof. Hosted OpenAI checks exposed and then verified the API-specific maximum-effort contract; TTS/Kimi uses compiled loopback proof with OS egress denial, not hosted Kimi inference. The reasoning patch carried unchanged onto current main after an unrelated Gateway shard-capacity failure; its build/hosted evidence retains the original c31 revision. All prior failed-attempt and proof qualifications remain in #142100.

Authenticated Telegram model-picker callback proof was waived by the maintainer on August 30, 2026 and was not run. No message round trip/mock substitute or desktop credential fallback was used. That waiver is limited to the Telegram obligation and does not waive upstream-provider validation or erase the #142473 recorder proof, which ran on combined build 6809 with identical recorder files, not a standalone recorder build.

Retained-source isolation, broader compaction provenance, sparse donor semantics and ACP per-turn overrides remain separate limits; lost historical model IDs cannot be reconstructed. #130324 remains open and unproved. This series does not establish the cause of the original multi-workspace CPU/stall report. Contributor credit is preserved in the linked replacement PRs and their commits.

@steipete
steipete requested a review from a team as a code owner August 27, 2026 05:03
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review blocked

Automated review did not run, so no review verdict was produced.

Reason: The input-safety check rejected material in this revision. No detected value, path, or scanner output is reproduced here.

ClawSweeper will not retry this unchanged revision.

Next step: If this is a genuine credential, remove and rotate it. If it is an intentional test fixture, a maintainer must review and qualify it.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Aug 27, 2026
@clawsweeper clawsweeper Bot added 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 10:09 PM ET / September 5, 2026, 02:09 UTC.

ClawSweeper review

What this changes

The branch gives plugin metadata an explicit lifecycle owner, carries workspace and model context through authentication and pricing, bounds session-summary reads, and improves Telegram model-picker receipts.

Merge readiness

⛔ Blocked before merge - 6 items remain

Keep open as the agreed reference branch, not a landing unit. Several extracted repairs have shipped in v2026.9.1, but remaining model-selection and metadata-lifecycle work is not fully accounted for, so neither whole-PR implementation nor supersession is established.

Priority: P1
Reviewed head: b6c358440aa2b94351d8c22466dc360d41c56ef8
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Measured runtime improvements provide useful evidence, but residual ownership growth and the introduced ACP compatibility restriction limit confidence in the combined patch.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The supplied MEMBER association exempts this PR from the ordinary contributor-proof gate; head-specific built-Gateway evidence supports the hot-path repair, while the original history comparator remains failed and Telegram proof was explicitly waived.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied MEMBER association exempts this PR from the ordinary contributor-proof gate; head-specific built-Gateway evidence supports the hot-path repair, while the original history comparator remains failed and Telegram proof was explicitly waived.
Evidence reviewed 15 items Pinned introduction boundary: The checkout matches original head b6c3584. Host-verified raw parents are df14f15 and 0594a10. Introduction judgments use the pinned merge-base-to-head delta; no verified test merge supports claims that merging would delete current-main work. Final worktree status is clean.
Maintainer-directed extraction: Supplied comment 5471678425 explicitly freezes this head as a reference rather than a landing unit and keeps it open until remaining changes are accounted for. GitHub context verifies merged extractions #133570, #133579, and #133604; #133633 remains an open, partial replacement for model normalization and compaction ownership.
Metadata ownership and lifecycle: The new owner prepares workspace collections, validates publication identity, and retains accepted snapshots. Gateway startup consumes the selected snapshot, reload publication commits accepted metadata, and runtime generation scopes carry the retained view. Tests cover superseded preparation, alternate state directories, and retired owners not clearing successors. Current main does not contain this collection module, so the entire requested ownership change cannot be treated as implemented merely because narrower caching repairs landed.
Findings None None.
Security None None.

How this fits together

The Gateway uses configuration and workspace plugin metadata to prepare agent runs, select models, resolve credentials, and price usage. Its health and status paths also read session databases, so repeated discovery or excessive session hydration can stall unrelated requests.

flowchart TD
  A[Configuration and workspaces] --> B[Prepared plugin metadata]
  B --> C{Operation context}
  C --> D[Retained agent generation]
  D --> E[Model selection, auth, and pricing]
  E --> F[Channel replies and receipts]
  G[Session databases] --> H[Bounded health and status reads]
  C --> H
Loading

Decision needed

Question Recommendation
Should the remaining performance replacements include rejection of finite-allowlist ACP overrides, or should that contract change receive a separate compatibility review? Review the ACP restriction separately: Keep the reference branch frozen and isolate constrained ACP behavior from the remaining performance landing units.

Why: The introduced guard intentionally stops an existing execution path, and the request to split the performance repair does not itself establish acceptance of that restriction.

Before merge

  • Resolve merge risk (P1) - Finite-allowlist background ACP runs that previously reached execution will now throw before inference; documentation and tests establish intent, but the supplied disposition does not explicitly accept that compatibility loss.
  • Resolve merge risk (P1) - The original net +2,138 production lines do not yet have a complete retain/drop mapping against the smaller landed replacements, leaving residual ownership and context-propagation growth unresolved.
  • Complete next step (P2) - Do not land the frozen head; account for remaining changes through the existing replacement PRs or explicit removal decisions, and resolve the ACP compatibility boundary in its owning cut.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Review config compatibility - Confirm compatibility and upgrade impact for the changed config or default surface before merge.
  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Production versus test growth Production net +2,138; tests/support net +15,252; tooling net +115 The original lifecycle boundary explains some growth, but the agreed smaller replacements require residual accounting rather than wholesale reuse.
Existing execution policy tightened 1 ACP path made fail-closed for finite model allowlists An operator-visible restriction is introduced without a new configuration setting.

Stored data model

Persistent data-model change detected: migration/backfill/repair: extensions/llm-task/doctor-contract-api.ts, serialized state: src/sessions/stored-model-overrides.ts, unknown-data-model-change: src/sessions/stored-model-overrides.ts, unknown-truncated-pull-files. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #130324
Summary: This is one candidate repair in a multi-cause stall investigation; shipped extractions and an open model-ownership replacement cover parts, not the complete report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge-risk options

Maintainer options:

  1. Isolate the ACP compatibility change (recommended)
    Leave the frozen head unmerged and route the finite-allowlist ACP restriction through its own explicit contract review.
  2. Accept the documented restriction
    An owner can approve rejecting constrained ACP runs while retaining the existing model-authorization guarantee.

Technical review

Best possible solution:

Complete the smaller owner-based replacements by reusing shipped metadata, summary, and pricing paths, with the ACP authorization contract isolated for explicit compatibility disposition.

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

No high-confidence current-main reproduction is established: supplied before/after runs target earlier revisions, and v2026.9.1 already contains several underlying repairs.

Is this the best way to solve the issue?

No for wholesale landing: the agreed extraction approach reuses already-shipped fixes and lets the remaining model and lifecycle contracts be validated independently.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P1: The underlying report includes real multi-workspace Gateway stalls and channel-ingress failures; partial shipped repairs do not establish complete resolution.
  • merge-risk: 🚨 compatibility: The introduced initial-model guard rejects existing constrained background ACP execution instead of allowing it to proceed.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied MEMBER association exempts this PR from the ordinary contributor-proof gate; head-specific built-Gateway evidence supports the hot-path repair, while the original history comparator remains failed and Telegram proof was explicitly waived.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. Model-picker terminal receipts are Telegram-visible, but the supplied maintainer disposition explicitly waives live callback proof; it was not run or passed.

Evidence

What I checked:

  • Pinned introduction boundary: The checkout matches original head b6c3584. Host-verified raw parents are df14f15 and 0594a10. Introduction judgments use the pinned merge-base-to-head delta; no verified test merge supports claims that merging would delete current-main work. Final worktree status is clean. (b6c358440aa2)
  • Maintainer-directed extraction: Supplied comment 5471678425 explicitly freezes this head as a reference rather than a landing unit and keeps it open until remaining changes are accounted for. GitHub context verifies merged extractions test: consolidate model and plugin metadata fixtures #133570, perf: separate static provider catalogs from live discovery #133579, and refactor(config): avoid evaluating type-only configuration modules #133604; fix: prevent stale fallback models after plugin reloads #133633 remains an open, partial replacement for model normalization and compaction ownership. (b6c358440aa2)
  • Metadata ownership and lifecycle: The new owner prepares workspace collections, validates publication identity, and retains accepted snapshots. Gateway startup consumes the selected snapshot, reload publication commits accepted metadata, and runtime generation scopes carry the retained view. Tests cover superseded preparation, alternate state directories, and retired owners not clearing successors. Current main does not contain this collection module, so the entire requested ownership change cannot be treated as implemented merely because narrower caching repairs landed. (src/plugins/plugin-metadata-collection.ts:299, b6c358440aa2)
  • Authentication context handoff: External profile resolution passes captured configuration, workspace, and plugin metadata into the provider-profile resolver rather than relying solely on ambient context. This addresses the reporter's distinction between successful synthetic agent turns and previously failing channel ingress. (src/agents/auth-profiles/external-auth.ts:111, b6c358440aa2)
  • Current-main bounded session reader: Current main already has the synchronous read-only summary owner: it scans lightweight session rows and hydrates requested recent entries rather than cloning the complete history. The branch and main versions differ by only one added and one removed line; the shared physical-store reader is also present. Readonly and status tests cover counts, recent windows, pending rows, and shared stores. (src/config/sessions/session-accessor.sqlite-summary.ts:29, f9b00a558261)
  • Current-main static pricing: Current main builds pricing keys with the static provider normalizer and prepared manifest policy, without activating provider runtime for each lookup. Its narrower implementation establishes substantial overlap, not equivalence with every captured-generation change in this branch. (src/model-catalog/pricing.ts:64, f9b00a558261)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Finish the retained/dropped mapping for remaining lifecycle and model changes, reusing landed owners rather than copying the original production and test growth.
  • Resolve the constrained ACP contract in its owning replacement while preserving model-authorization enforcement.

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 (16 earlier review cycles; latest 8 shown)
  • reviewed 2026-08-27T16:54:52.767Z sha 2a3c717 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T05:17:37.112Z sha 6718126 :: found issues before merge. :: [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-28T06:32:37.880Z sha e435af6 :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T08:03:55.110Z sha 1c24d54 :: found issues before merge. :: [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-28T13:54:57.119Z sha c0ba2f3 :: found issues before merge. :: [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-28T14:44:00.445Z sha d6c0f40 :: found issues before merge. :: [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-29T03:02:26.832Z sha 73c6adc :: found issues before merge. :: [P2] Remove the release-owned changelog entry
  • reviewed 2026-08-29T04:23:36.644Z sha 73c6adc :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 27, 2026
@steipete
steipete force-pushed the codex/gateway-metadata-ownership branch from eebae21 to 5119615 Compare August 27, 2026 06:29
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 27, 2026
@elikampf

Copy link
Copy Markdown

Confirming this fix works, with a second finding underneath it that turned out to be the larger half.

Thank you for the work on this. It solved a burn I'd been chasing for days, and the diagnosis it enabled found the rest.

Setup

13 agent entries, 13 distinct workspaceDirs, 15 agent session stores (largest single store 1.3 GB), 460 plugin manifests, node v24.19.0, arm64 Linux, gateway from source under systemd.

Before this branch

Gateway pinned at 100% of a core indefinitely. perf with --perf-basic-prof put 60.2% of samples under resolvePluginMetadataSnapshot → loadPluginMetadataSnapshot → loadPluginRegistrySnapshotWithMetadata, re-reading all 460 manifests 3-6x/sec.

After this branch

The rediscovery loop is gone. Idle gateway now sits at 1.0% CPU, RSS 1.1 GB.

The second layer

With the branch deployed, the gateway was still at ~85%. The cause was the "System busyness" debug overlay — the diagnostics panel itself.

ui/src/pages/debug/debug-overlay.ts:16:

const DEBUG_OVERLAY_POLL_INTERVAL_MS = 2000;

Measured over 10 minutes with the overlay open: 257 status calls, averaging 1,653 ms. At a 2,000 ms poll interval that's an 82.65% duty cycle, against 79-89% measured CPU. Closing the overlay dropped the gateway to 1.0% and RSS from 2.5 GB to 1.1 GB, immediately, with zero config changes.

status isn't a cached metric — server-methods/health.ts:186 rebuilds a full summary per call, walking every agent's session store and deep-cloning session entries before keeping only the ten most recent per agent. That cost scales with accumulated history, so it stays invisible on a small install and dominates on a large one.

These two are one chain rather than two independent bugs. status/summary.ts aggregates plugin state, so each overlay poll resolved plugin metadata — which, before this branch, meant a 460-manifest rescan. The overlay was driving the rediscovery loop 30 times a minute. This branch made each resolution cheap; the remaining cost is the summary rebuild itself.

The observability panel was generating most of the load it was reporting, which makes it hard to catch: the burn only appears while you're looking at it.

Possibly worth a separate issue, but two things would help:

  • Skip a poll tick when the previous status hasn't returned (currently no backoff at a 2s interval against a 1.65s call).
  • Cache or incrementally maintain the status summary rather than rebuilding whole-estate per call.

Sibling to #122865, which reports the same shape (unthrottled dashboard polling saturating the gateway) for sessions.list on the sessions page.

One remaining issue on this branch

sessions.list and sessions.describe still fail with Plugin metadata lookup escaped its prepared config or workspace, thrown at src/plugins/plugin-metadata-snapshot.ts:396 in the if (owner?.getActive()) branch when owner.readSnapshot(params) returns undefined. Still present at head 84f0909. It was ~75/min with the dashboard open. Reproduces on restart, so it looks deterministic rather than a race — happy to test patches against this config.

@steipete

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed measurements. I am holding this PR open while checking the session projection failure and the remaining full-store work in status. The current debug overlay already has an in-flight request guard, so the backend summary path needs attention rather than simply stretching the polling interval.

I can reproduce successful list/describe calls with fresh sessions in four distinct workspaces, including custom plugin load paths; I am now testing persisted model overrides and the configless normalization path. If available, a redacted stack trace for the first metadata-guard exception and the affected session's model/provider override fields would help pin down the exact path. Please omit credentials, message content, and private paths; no full session store is needed.

The metadata win and your reported 1% idle CPU are useful evidence, but I will not treat them as proof that the dashboard path is fixed. The final branch will receive another built-Gateway replay before merge.

@steipete
steipete force-pushed the codex/gateway-metadata-ownership branch from 84f0909 to ce36be2 Compare August 27, 2026 10:09
This was referenced Sep 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: discord Channel integration: discord channel: mattermost Channel integration: mattermost channel: slack Channel integration: slack channel: telegram Channel integration: telegram cli CLI command changes commands Command implementations docs Improvements or additions to documentation extensions: groq extensions: llm-task Extension: llm-task gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants