Skip to content

fix: avoid repeated model setup before fallback attempts - #201216

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-fallback-rate-limit-model-normalize-20260919
Nov 18, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-fallback-rate-limit-model-normalize-20260919

Conversation

@steipete

@steipete steipete commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A five-candidate fallback chain normalizes five configured models and selects provider handles twenty times before each turn, even when the primary succeeds. Current admitted turns already reuse their plugin generation, so activation/config preparation is largely absent; the remaining repeated model and hook work is unnecessary.

User Impact

Fallback health checks reuse model facts from the admitted snapshot. Model selection, transport, credential selection, and rate-limit decisions keep their existing behavior. There are no configuration changes or migration steps.

Why This Change Was Made

Rate-limit identity needs the resolved provider, model, endpoint, and credential/organization headers; harness/auth selection also needs the resolved API. The existing model snapshot now prepares its configured primary/fallback routes in the retained plugin generation. Reads require the same config identity. Replacement snapshots prepare replacement routes; retained snapshots keep their own facts. Live auth and health remain live. Unknown, standalone, and projected-config candidates retain the cold resolver.

Configured model normalization shares one provider handle across its model and transport hooks using the catalog normalizer's existing synchronous context. Custom/static hooks retain their policy. Agents without configured fallbacks skip projection, and initial primary selection uses static normalization before the candidate resolver applies its policy. No global activation/config cache was added; earlier activation-policy work remains the owner.

Runtime source grows by 119 lines. The growth supplies the missing snapshot-owned route projection and shared normalization context; raw catalog rows do not contain the final transport/header facts. Proof/workload/fixtures add 308 lines.

Evidence

Final measured head: 9f22a34e22107ddce37323927093ae8c0b3a7561. Baseline: 80607c31486ed53baa082340949784572785f9d7.

The committed workload uses 48 synthetic plugins, three providers and five fallback candidates. Both variants enter the prepared-model scope and plugin-runtime generation scope used by reply execution. Pin Node 24.22.1; five serial A/A/B blocks alternate A/A/B and B/A/A order. Each process runs 100 warmup and 1,000 measured turns separated by setImmediate. Timing, sampled allocation, precise counts, and CPU profiles are separate passes. No session DB or workspace traversal is exercised, so unrelated disk fixtures are omitted. No production data or live model call is used.

Predeclared acceptance: identical selection and rate-limit behavior, zero model normalization on prepared reads, CPU/allocation gains beyond control variation, and no unexplained 20% candidate regression. Snapshot preparation is reported separately as the intended once-per-snapshot work transfer.

Metric (median of five process results) A1 A2 Candidate
Main-thread CPU / turn 452.5 µs 458.3 µs 145.9 µs
Total process CPU / turn 671.1 µs 685.2 µs 230.3 µs
Owner median latency 402.0 µs 411.3 µs 127.3 µs
Owner p95 latency 620.4 µs 627.5 µs 195.4 µs
Sampled allocation / turn 625,398 B 623,527 B 222,240 B
Snapshot publication wall time 0.519 ms 0.523 ms 10.677 ms
Snapshot publication process CPU 0.542 ms 0.548 ms 17.407 ms

Main-thread CPU falls about 68%, process CPU 66%, and sampled allocation 64%. The extra publication work amortizes after approximately 39 warm turns using total process CPU; this is an amortization estimate, not a measured cold-first-turn latency claim. This optimization is for reused snapshots. No whole-Gateway speedup is claimed.

A/A CPU difference has median 2.62%; allocation difference has median 0.38% and maximum 1.41%. One timing A2 outlier is retained: 1,001.7 µs CPU, making the maximum A/A CPU difference 121.3%. All candidate CPU samples (141.9–277.7 µs) remain below every baseline sample (416.9–1,001.7 µs); allocation ranges also do not overlap. One-minute host load ranged 8.0–30.9. No samples were dropped.

Precise coverage over 100 turns: configured-model normalization 500 → 0, provider-runtime lookup 2,000 → 0, auto-enable 0 → 0. Plugin-entry normalization occurs once on the base and zero times on the candidate, not once per turn. Regression spies also verify zero normalizePluginsConfig calls on prepared reads. Separate CPU profiles show 66.0 ms inclusive in configured-model normalization and 19.6 ms in provider lookup on the base, versus zero samples in either on the candidate; these are profiled-pass numbers, not warm timing results.

Two regressions fail before the fix on the intended counts: 15 model normalizations over three five-candidate turns versus zero, and four provider selections per configured normalization versus one. Tests also cover resolved-model parity, saturated-route selection, endpoint/config replacement, retained old snapshots, and a mismatched config/snapshot control. Forty-five focused tests plus catalog and sticky-rate-limit coverage passed. After the review repairs, the 24-test command suite and corrected snapshot regression passed; all six affected Stop cases pass after incorporating the main repair below. OPENCLAW_CHECK_CHANGED_SKIP_DEADCODE=1 pnpm check:changed exits 0, reusing the earlier successful unused-export scans. Fresh independent Codex review reports no actionable P0–P2 findings.

Review/CI corrections are retained explicitly: the first benchmark omitted the plugin-runtime scope, so all its timing/allocation/activation figures were withdrawn and replaced by the complete campaign above. CI also exposed a PR-caused static custom-provider selection regression; it was reproduced and fixed without weakening the existing test. A separate main test regression was attributed to #201157 by exact-main-parent reproduction and adjacent-commit testing; #201222 repaired it. This branch incorporates #201222, with patch-identical lane commits verified by git range-diff. No inherited-failure exception is requested.

Reproduce: node --expose-gc --import ./scripts/tsx.mjs scripts/perf/model-fallback-activation-inputs.ts --flow prepared-runner --iterations 1000 --warmup 100, with separate --allocation, --counts --iterations 100 --warmup 0, and --profile <file> --iterations 100 --warmup 0 passes.

@clawsweeper

clawsweeper Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts agents Agent runtime and tooling size: L labels Nov 18, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review the prepared fallback-rate-limit model projection and shared provider-normalization handle context at this head. Pay particular attention to config reload/retained snapshot behavior, custom runtime hooks, transport and auth/header parity, and the cold path for unprepared or mismatched candidates. Local regressions and Codex review pass; the predeclared A/A/B performance campaign is running while this remains a draft.

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 18, 2026
@steipete
steipete marked this pull request as ready for review November 18, 2026 13:25
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T13:53:42.597145Z 9f22a34 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added the clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. label Nov 18, 2026
@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR prepares fallback route facts with model snapshots and shares provider selection across synchronous normalization hooks.

Example: A reused snapshot runs 100 turns with synthetic-first/primary and four configured fallback candidates.

  • Before: The supplied corrected benchmark records 500 configured-model normalizations and 2,000 provider lookups.
  • After: Prepared reads record zero of either operation while retaining primary selection and live rate-limit checks.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch and corrected comparative measurements support the optimization; proof remains an in-process synthetic workload, and exact-head CI is still completing.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal performance change supplies a corrected production-owner benchmark and regression results; inspected screenshots concern the separate Stop repair and provide no evidence for this optimization.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Turns with configured fallbacks spend CPU and allocate memory preparing unchanged model routes even when the primary succeeds.
Reason: The maintainer-authored direction targets measured repeated work and explicitly accepts the publication-cost tradeoff for reused snapshots.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it removes repeated fallback setup still present on main, addresses both earlier findings, and introduces no actionable correctness or security defect found in this review.

Priority: P2
Reviewed head: 9f22a34e22107ddce37323927093ae8c0b3a7561

Before merge

None.

Findings

None.

Agent review details

How this fits together

The model runtime prepares route facts from config and plugin registrations; fallback admission combines those facts with current auth and health to order eligible candidates.

flowchart TD
  A[Config and plugin generation] --> B[Prepared model snapshot]
  B --> C[Fallback route facts]
  D[Requested candidate chain] --> E[Rate limit preparation]
  C --> E
  F[Live auth and health] --> E
  E --> G[Ordered model attempts]
Loading

Technical review

Best possible solution:

Keep final route facts on their existing snapshot owner, reuse synchronous provider handles, and retain live auth, health, and cold resolution.

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

Current-main source repeats normalization for every candidate before attempting the primary, and the supplied corrected benchmark quantifies that work; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change follows existing snapshot and normalization owners, preserves custom/static hook policy, and shares the original cold algorithm between preparation and unmatched reads.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 801073ff843a.

Provenance checked

  • Fallback rate-limit route resolution keeps the original intent (5686263: Shared saturation ordering needs resolved endpoint, model, and account facts so eligible fallbacks remain reachable.)
  • Configured-model assembly keeps the original intent (3213e3e: refactor(agents): unify configured model assembly #178309 consolidated configured and discovered assembly under one normalization operation while preserving route and request precedence.)
  • Provider-handle reuse keeps the original intent (730ce41: Reuse provider selection within a synchronous pass while retaining model-specific misses, transport ordering, and origin restrictions.)
  • Existing fallback performance workload keeps the original intent (f475f27: Measure repeated activation work independently of inference; the added prepared flow distinguishes that earlier optimization from remaining model-resolution work.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5686263 adds src/agents/model-fallback-rate-limit.ts:117 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 568626311f8f; files: src/agents/model-fallback-rate-limit.ts)
  • Vincent Koc: Raw commit 730ce41 adds src/plugins/provider-model-normalization.ts:21 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 730ce41827c4; files: src/plugins/provider-model-normalization.ts)

PR surface

Source +119, Tests +265, Other +43. Total +427 across 10 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 6 135 16 +119
Tests 3 265 0 +265
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 67 24 +43
Total 10 467 40 +427

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus validation growth Production +119 net lines; tests and fixtures +265; benchmark +43. The growth carries final route facts in the existing snapshot, shares normalization context, and covers generation isolation and work reduction without a new global cache.

Labels

Label changes:

  • add P2: This is a bounded performance improvement to fallback preparation with measured warm-work reduction and no demonstrated urgent user outage.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a bounded performance improvement to fallback preparation with measured warm-work reduction and no demonstrated urgent user outage.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-18T13:33:16.613Z sha 08c6635 :: needs changes before merge. :: [P2] Preserve static custom-model selection during snapshot preparation | [P2] Enter the plugin-runtime scope in both benchmark variants

Reviewed November 18, 2026, 9:07 AM ET / 14:07 UTC (Revision 2).

Reuse configured fallback models within the admitted config snapshot and share provider handles across configured normalization hooks. Preserve cold resolution for standalone or mismatched snapshots and reload route facts with their owning snapshot.
Skip projection for agents without configured fallbacks. Match the production plugin-runtime scope in fallback benchmarks and regressions so both variants use the same retained registry.
@steipete
steipete force-pushed the steipete/perf-micro-fallback-rate-limit-model-normalize-20260919 branch from d734179 to 9f22a34 Compare November 18, 2026 13:50
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed all three items from the review of 08c6635b4ec8d9a9a2f3347041e7d82f5b094dcc on final head 9f22a34e22107ddce37323927093ae8c0b3a7561:

  1. Static custom-model selection: src/agents/prepared-model-runtime.full-catalog.ts:371–376 skips no-fallback projection and sets allowPluginNormalization: false for initial primary selection. The candidate resolver retains ownership of runtime normalization. The existing failing custom-provider test reproduced locally before the repair, then its complete 24-test command suite passed unchanged.
  2. Matching runtime scopes: scripts/perf/model-fallback-activation-inputs.ts:167–171 now enters withPluginRuntimeGenerationScope(preparedSnapshot, ...) inside the prepared-model scope for both A and B. The regression mirrors both scopes at src/agents/model-fallback.prepared-rate-limit.test.ts:26–41. The corrected base still normalizes 15 models across three turns; the candidate normalizes zero. All earlier performance figures are withdrawn.
  3. Complete performance campaign: the PR body now contains the completed corrected five-block A/A/B timing and allocation campaign, exact source heads, work counts, profiles, host-load and outlier disclosure, and snapshot preparation cost. Main-thread CPU medians are 452.5/458.3 → 145.9 µs per turn; allocation is 625,398/623,527 → 222,240 B. Current admitted-path activation is already zero on both variants. The one-time preparation CPU increase amortizes at roughly 39 warm turns; no cold-first-turn or whole-Gateway speedup is claimed.

The separate inherited Stop-test regression was reproduced on the exact CI main parent and traced to #201157. Main's #201222 repair is incorporated; all six selected Stop cases now pass. The lane commits are patch-identical after that rebase. Changed checks and fresh Codex autoreview are clean; exact-head hosted CI is running.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete steipete changed the title improve: avoid repeated model setup before fallback attempts fix: avoid repeated model setup before fallback attempts Nov 18, 2026
@steipete
steipete merged commit 2b58c8e into main Nov 18, 2026
143 checks passed
@steipete
steipete deleted the steipete/perf-micro-fallback-rate-limit-model-normalize-20260919 branch November 18, 2026 14:12
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 19, 2026
…1216)

* perf(agents): prepare fallback rate-limit routes with model snapshots

Reuse configured fallback models within the admitted config snapshot and share provider handles across configured normalization hooks. Preserve cold resolution for standalone or mismatched snapshots and reload route facts with their owning snapshot.

* fix(agents): preserve static model selection during fallback preparation

Skip projection for agents without configured fallbacks. Match the production plugin-runtime scope in fallback benchmarks and regressions so both variants use the same retained registry.
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
* perf(agents): prepare fallback rate-limit routes with model snapshots

Reuse configured fallback models within the admitted config snapshot and share provider handles across configured normalization hooks. Preserve cold resolution for standalone or mismatched snapshots and reload route facts with their owning snapshot.

* fix(agents): preserve static model selection during fallback preparation

Skip projection for agents without configured fallbacks. Match the production plugin-runtime scope in fallback benchmarks and regressions so both variants use the same retained registry.

(cherry picked from commit 2b58c8e)

Companion audit: #201632 is selected to preserve registry and metadata ownership for the fallback hot path. #200605, #203901, #203095 and #202618 make independent TUI, custody, module separation and model listing changes; none is required by this port.

Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. scripts Repository scripts size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant