Repository navigation
fix(agents): route shared TPM exhaustion to configured fallbacks - #185496
Conversation
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: blocked before merge. What this changesThis PR shortens shared TPM recovery, routes around saturated models, and preserves configured fallbacks when a session selects its configured primary. Example: An agent uses openai/gpt-5.4 with anthropic/claude-sonnet-4-6 as its configured fallback.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 4 items remain Keep open: this maintainer-authored PR addresses a current fallback failure, but affected consumer tests need repair before it is ready. Priority: P1 Before merge
Findings
Tests
Agent review detailsHow this fits togetherGateway and agent entry points resolve session model policy, the fallback runner orders eligible models, and the shared admission gate paces outgoing provider requests. flowchart TD
A[Session or agent request] --> B[Model selection policy]
B --> C[Fallback candidate runner]
D[Shared model saturation] --> C
C --> E[Embedded retry controller]
E --> F[Provider admission gate]
F --> G[Provider transport]
G --> D
Technical reviewBest possible solution: Retain the existing admission, retry, selection, and persistence owners while making their affected consumers agree on the new fallback contract. Do we have a high-confidence way to reproduce the issue? Current-main source shows creation forcing a model pin, user pins disabling the fallback ladder, and shared admission spanning models; no target code was executed during this read-only review. Is this the best way to solve the issue? The repair addresses both policy and admission blockers through existing owners, but its consumer tests still encode the previous contracts. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d0916212f458. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +343, Tests +536, Docs +18. Total +897 across 28 files. Added test files: 2. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 27, 2026, 1:42 AM ET / 05:42 UTC. |
Align fallback consumers and their fixtures with the selection owner. Equal-primary selections retain configured fallbacks; different models and explicit empty ladders remain strict. Approved per-file allowance: 3731 to 3736 counted lines for agent-command.live-model-switch.test.ts; expectations updated for equal-primary saved selections keeping configured fallbacks; #185496.
38f5974 to
41dd2fd
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e8945ccc22
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Scope shared token-rate-limit admission by account and model, bound replay-safe same-model recovery when a fallback is eligible, and route other sessions around saturated candidates. Normalize same-primary session creation and keep configured fallbacks for existing equal-primary selections while preserving different strict selections and locks.
Align fallback consumers and their fixtures with the selection owner. Equal-primary selections retain configured fallbacks; different models and explicit empty ladders remain strict. Approved per-file allowance: 3731 to 3736 counted lines for agent-command.live-model-switch.test.ts; expectations updated for equal-primary saved selections keeping configured fallbacks; #185496.
df7d0bb to
d371116
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d371116807
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| sessionAuthProfileId: params.userLockedAuthProfileId, | ||
| sessionAuthProfileSource: params.userLockedAuthProfileId ? "user" : undefined, |
There was a problem hiding this comment.
Scope the pinned auth profile to compatible fallback providers
When a user pins a profile for provider A and the fallback chain includes providers B and C, this passes A's profile as a user lock while preparing B's auth. prepareAgentRuntimeAuth rejects the incompatible profile, and the catch below marks B eligible without reading its saturation gate. If A and B are saturated but C is healthy, B is consequently ordered first and the request waits behind its gate instead of using C. The actual candidate loop in model-fallback-runner.ts checks resolveAuthProfileEligibility before applying the pin; apply the same provider compatibility check here so the snapshot observes B's actual starting account.
AGENTS.md reference: AGENTS.md:L70-L70
Useful? React with 👍 / 👎.
|
@clawsweeper re-review The configured-account identity finding is fixed and its thread resolved. The four reviewed patches are unchanged after incorporating #185667. Exact-head CI has only the independently evidenced #185424 worker failures; the PR body records the completed main comparison and authorized native landing exception. |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
…nclaw#185496) * fix(agents): route shared TPM exhaustion to configured fallbacks Scope shared token-rate-limit admission by account and model, bound replay-safe same-model recovery when a fallback is eligible, and route other sessions around saturated candidates. Normalize same-primary session creation and keep configured fallbacks for existing equal-primary selections while preserving different strict selections and locks. * refactor(agents): own fallback policy in model selection Align fallback consumers and their fixtures with the selection owner. Equal-primary selections retain configured fallbacks; different models and explicit empty ladders remain strict. Approved per-file allowance: 3731 to 3736 counted lines for agent-command.live-model-switch.test.ts; expectations updated for equal-primary saved selections keeping configured fallbacks; openclaw#185496. * fix(ci): complete fallback mocks and lint cleanup * fix(agents): honor configured account identity in saturation lookup
What Problem This Solves
Concurrent sessions can spend minutes retrying a saturated primary without reaching their configured fallback. Remembered new-session defaults also become strict user model overrides, disabling that fallback chain before retry policy can help.
Peter's asks:
Team evidence from October 26–27: 292 rate-limit errors across 19 of 27 sessions over roughly three hours, with each run logging its own
transient same-model retry N/15, waits up to 60 seconds, and no configured model fallback. The primary and fallback used the same OpenAI account, with about 20 concurrent agent runs and 150k–690k input-token requests. The organization TPM bucket remained saturated despite retry hints around 48 ms. One turn exhausted 15 retry events over approximately eight minutes and ended incomplete.A second blocker affected all 19 sessions created that day: they stored a strict
usermodel override matching the configured primary, although Peter had never selected an override. The rememberednew-session.v1:<agent>preference included the displayed model; the new-session flow sent it throughsessions.create, whose creation-only forced pin turned it into a strict selection. Gateway logs confirmed configured fallbacks were disabled by that override.User Impact
Four fixes make the configured fallback reachable:
sessions.createrequests matching the effective configured primary instead of forcing an override. Existing saved equal-primary user selections keep the configured fallback chain without a database rewrite or Doctor migration.Selecting the configured primary retains its configured fallbacks. Different explicit model selections, model-selection locks, and explicit empty fallback lists remain strict. Clear a saved override with
sessions.patch model:null; writing the displayed default back as a model is not the cleanup operation.Why This Change Was Made
The gate already owns shared saturation. Candidate ordering now consumes its read-only account/model snapshot rather than adding another cooldown store. Ordering lives in
model-fallback-rate-limit.ts; the fallback runner only calls it and grows by three lines, remaining below its 700-line cap.Creation's forced-pin history was checked against #169030. Different requested models still preserve explicit selection; same-primary creation now uses the existing default normalization. Existing SDK/session-agent exports are retained after moving unchanged session-agent resolution to its configuration owner to avoid a static import cycle.
Accepted limits: coordination is process-local. Native transports, deferred credentials, and account choices requiring cooldown admission retain ordinary admission when their starting identity cannot be determined read-only. Saturation uses the existing one-minute recovery window, and existing 10-minute idle/30-minute-cap fallback stickiness remains. A saved or remembered model differing from a subsequently changed primary remains a different, strict selection. No UI change, new config, dependency, persisted shape, schema, or migration is introduced.
Evidence
Published head:
df7d0bb7ebd6a0f262dcd390997f99abc126dd63. The PR is OPEN, ready and MERGEABLE. Exact-head CI run 40467478171 completed FAILURE. Requiredopenclaw/ci-gate: FAILURE. All six lint jobs, baseline ratchets, and all three PostgreSQL conformance jobs passed. Its only five failed test shards are the coordinator-confirmed CLI and worker failures described below; no unrelated repairs were added. Earlier runs remain prior-head evidence. Stopped for coordinator review; no merge was attempted.The coordinator-approved file-specific size allowance is committed:
agent-command.live-model-switch.test.ts, 3,731→3,736 counted lines, after duplicate fixture wiring cleanup, through the normal per-file lint-limit mechanism. Reason: “expectations updated for equal-primary saved selections keeping configured fallbacks; #185496”. No other ceiling was raised and no baseline entry was added. The current line-cap guard passes for 46 changed source files.The architecture repair moves fallback availability into the existing model-selection config owner and its type into the leaf fallback contract. All consumers/mocks were cut over. The exact Madge guard passes with zero cycles. One rebase conflict retained both main's added prepared-runtime sharing test and the selection-owner import.
Branch-mode Codex P1 review covered the implementation and selection-owner cutover at 41dd2fd, scoped-clean with confidence 0.84. CI then found two duplicate imports, an unused size suppression, incomplete real-module pass-through in two mocks, and an extra asynchronous suspension-row assertion. The five-file follow-up fixes these; its fresh P1 review is scoped-clean with confidence 0.97, including final source verification. It is now committed and pushed. No fallback production logic changed in that follow-up.
The coordinator approved the deletion-only baseline cleanup made necessary by the repaired mocks. The normal prune command removed exactly two obsolete entries: 6,615→6,613, with no additions. Formatting and line-cap checks pass. Strict-selection tests retain physical selected-model-only requests, terminal failure, exactly one persisted run-error message, and no success text. The extra suspension-row assertion failed once in CI and passed on identical local inputs; it concerns an asynchronous projection outside the direct-agent terminal contract. The command/steering/reply-utils replay passed: 109 command cases and 40 reply cases, two configured shards in 578.33 s. The normal max-lines prune also removed the single obsolete suppression entry (409→408), as required after removing its unused suppression; no baseline entries were added.
The final repair accepts the automated account-identity finding: when bundled catalog metadata exists, normalization needs an explicit provider config to retain configured organization headers and endpoints. Saturation reads now use the same existing config resolver as the real model resolver. The regression failed on e894 (requested primary instead of backup), then all 53 focused fallback cases passed with the two-line production fix. Core and affected agent test types pass; Madge reports zero cycles; line-cap and formatting checks pass. A fresh complete-candidate Codex P1 review is scoped-clean (confidence 0.85), including final source verification. The last commit contains this repair, its single regression, and the stale baseline deletion.
All 16 real Gateway product cases passed locally (790.46 s including imports). An earlier broad replay was stopped before shared-fixture edits; the separate three-file replay above subsequently completed. The requested additional real embedded-runner replay passed in 23,542ms; total wrapper 721.89s, including a 194,967 ms worker build and 496.29 s Vitest duration dominated by imports. It ran alone at host load 52.62, below the earlier peak near 80. The existing 120,000 ms test limit was unchanged. Earlier results remain recorded: timeout at 120,000 ms (reported body 141,627 ms), followed by a 37,869 ms diagnostic pass (wrapper 524.66 s). Passing replay does not prove a fix for that timeout.
The coordinator confirms the CLI and worker failures are not caused by this PR. They are the only five failed test shards on the final head:
checks-node-changed-compact-small-6(CLI),checks-node-changed-compact-large-11(worker computer launcher),checks-node-changed-compact-large-25-1(worker detached context),checks-node-changed-compact-large-8-1(worker context engine), andchecks-node-changed-compact-large-26(worker terminal results/watchdog). CLI #185388 is being fixed forward separately; worker fixtures come from #185424. Source evidence supports both attributions: Main #185424 added preturn workspace quiesce/reconcile/resume; four unchanged worker suites reject/omit that protocol (18 detached-context,27 computer-launcher,2 context-engine,4 terminal-result failures). The last suite also contains a source-demonstrated fixture deadlock consistent with its 300,000 ms no-output watchdog termination; the log does not identify the hung test by stack. Main #185388 changed completion reply-expectation precedence;17 unchanged CLI cases expect different behavior. Explicit child-result precedence needs its policy owner's review rather than blanket fixture relaxation. Relevant production/tests are byte-identical at base 43fbf45 and this head. Exact-base run 40459732984 was cancelled with no jobs, so this is source attribution, not a completed base test verdict. Those files were not edited here. All failed logs were fetched once; no blind CI rerun was requested.Gate keying, the short retry budget, public
sessions.create, and real-runner routing were red with the original owning modules and green with the repair. The original routing owner sent three primary requests for session B instead of going straight to fallback; the original creation owner persisted an equal-default strict override. The scripted provider runs through the real stream gate with isolated SQLite state, synthetic credentials, and rejected network calls. A makes three primary requests then answers on fallback; B sends only fallback; after fake-clock expiry C uses primary; strict[] waits through the gate.The earlier 14-file touched/consumer batch passed 224 distinct cases plus one existing skip;40 E2E cases also passed under the second configured runtime. After account correction 53 focused cases passed; after ordering correction 52 fallback cases passed. Core/four affected test typechecks, formatting, docs MDX, assertion safety and database-worker checks passed. The local lint wrapper twice hit its unchanged 300,000 ms Plugin SDK declaration prerequisite before lint ran; the coordinator selected PR CI lint as the supported proof. All six lint jobs passed on the final head, with no timeout or guard bypass.
Commands and scope
OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1 node scripts/run-vitest.mjs \ src/llm/stream.complete-host.test.ts \ src/agents/embedded-agent-runner/run/failover-retry-controller.test.ts \ src/agents/agent-scope.test.ts \ src/agents/agent-tools.prefix-stability.test.ts \ src/agents/model-fallback.shared-rate-limit.integration.test.ts \ src/agents/model-fallback.shared-rate-limit.test.ts \ src/gateway/server.sessions.create.resolved-model.test.ts \ src/agents/embedded-agent-runner.resolvesessionagentids.test.ts \ src/agents/model-runtime-policy.test.ts \ src/cron/isolated-agent/run-fallback-policy.test.ts \ src/auto-reply/reply/agent-runner-run-params.thinking.test.ts \ src/gateway/server-methods/chat-send-message-injection.test.ts \ src/agents/model-fallback.run-embedded.e2e.test.ts \ src/agents/model-fallback.reply-entry.e2e.test.ts --maxWorkers=1 OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1 node scripts/run-vitest.mjs \ src/agents/model-fallback.test.ts \ src/agents/model-fallback.shared-rate-limit.test.ts \ src/agents/model-fallback.shared-rate-limit.integration.test.ts --maxWorkers=1 pnpm tsgo:core node scripts/run-tsgo-core-test-shards.mjs --ci-graphs-json '["core-test-agents-root","core-test-agents-other","core-test-gateway-server","core-test-other"]' pnpm check:line-cap-ratchet --base 9dd9539b04768fe07f190ed6e78eb2e7b77f7db2 pnpm check:max-lines-ratchet --base 9dd9539b04768fe07f190ed6e78eb2e7b77f7db2 pnpm check:assertion-safety --base 9dd9539b04768fe07f190ed6e78eb2e7b77f7db2 pnpm check:test-mock-exports --base 9dd9539b04768fe07f190ed6e78eb2e7b77f7db2 pnpm check:database-worker-ratchet --base 9dd9539b04768fe07f190ed6e78eb2e7b77f7db2 pnpm check:import-cycles node scripts/check-docs-mdx.mjs docs/concepts/model-failover.md docs/concepts/retry.md git diff --checkThe 14-file batch preceded the final account/ordering refinements; focused reruns cover those changes. lint configuration: +7/-0 (net +7); docs: +30/-12 (net +18); production: +584/-249 (net +335); tests/support including harnesses and mocks: +707/-94 (net +613); obsolete baseline entries: +0/-3. Total: 51 files, +1,328/-358 (net +970). The smallest coherent change includes the gate, chain admission, retry budget, and producer/policy repair: leaving any one of these paths unchanged can still prevent configured fallback.
No live Gateway, Team/stable state, real provider API, deployment, release, new configuration or dependency was used for proof. No worker or completion-policy repair is included here. The coordinator reviewed and accepted the production diff and authorized landing.
Landing update: CLI fix-forward #185667 landed as
b3b0f1bb8105cf784f87f47a8f31a9564888f2e3. This branch was rebased onto main454f79575efd51acaebcfa2e100674f299d96fbb; all four commits are patch-identical bygit range-diff, andgit diff --checkpasses. Current head:d371116807e9c310cd789b8d2c130c10b6ebab20. Exact-head CI, attempt 1, is terminal: 60 passed, 25 skipped; four worker shards and their aggregate gate failed. All six lint jobs, security-fast, baseline ratchets, and all three PostgreSQL conformance jobs passed. The CLI failures are gone. The earlier five-shard results above belong to the previous head.The completed main CI run 40463504008, main commit
9b7db694b593cd2b498d704611414a8659fe7ffbafter #185424, has the same detached-context, computer-launcher, and context-engine failures. Its terminal-result log also contains the same four failed assertions followed by the durable-Move timeout. The four affected test files, launch fixtures, launcher/execution owners, and preturn reconciliation owners are byte-identical between that main baseline and the refreshed PR head. Any inherited-failure landing will retain the actual failed run and source evidence; it will not describe failed CI as green.The coordinator authorized native squash landing with these independently evidenced pre-existing #185424 worker failures. Current failed jobs are
checks-node-changed-compact-large-11(27 computer cases),checks-node-changed-compact-large-24(18 detached-context cases),checks-node-changed-compact-large-8-1(two context-engine cases), andchecks-node-changed-compact-large-9(four terminal-result assertions, followed by the unchanged 300,000 ms watchdog); aggregateopenclaw/ci-gateis failed. Actual CI checkout1854829d87feeaff2d63404fd399cf08882fd839has ordered parents main06c9568679c378a8e8a4a24468d16300a6c3f378and this exact PR head; its tree matches their merge. Native evidence retains the logs, the completed failing main run, exact case comparisons, source-object equality, passing scoped proof, and the original investigated local timeout. The watchdog log does not identify its hung test by stack; the same four preceding assertions fail on main, where the durable-Move case also times out. No worker-fixture repair, timeout increase, or successful-CI claim is included here.