Repository navigation
fix(ai): turns fail without compaction when Hugging Face TGI rejects an over-long prompt - #158161
Conversation
… mode When the estimated input leaves no room for output, the openai-completions request builder falls back to max_completion_tokens=1 and still sends the request. openclaw#157673 turned that into a context overflow for thinking-enabled reasoning models; non-reasoning models and thinking-off requests still send the one-token request, which cannot hold a useful reply and comes back cut off by length. Throw the same context_length_exceeded error for those requests when the estimate leaves zero or negative output space, so the existing overflow recovery compacts instead. Positive short budgets (1-15 tokens that fit the estimate) and their insufficient_output_budget warning are unchanged for non-reasoning and thinking-off requests, and deliberately short requested budgets are untouched. Refs openclaw#157307
|
🦞👀 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. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Add the missing exhausted explicit-one-token regression and correct the misleading no-output diagnostic.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 1
Open (1)
What changed in this PR
Fixes exhausted OpenAI-compatible proxy completion budgets for non-reasoning and thinking-disabled requests by routing them through overflow recovery.
Changes:
- Rejects zero/negative available output budgets with
context_length_exceeded. - Preserves positive short-budget behavior.
- Updates regression coverage across affected modes.
| File | Summary | Findings |
|---|---|---|
packages/ai/src/transports/openai-completions-params.ts |
Adds exhausted-budget rejection logic. | Moderate (2 votes): add coverage for exhausted explicit maxTokens: 1. Nit (1 vote): clarify the no-output diagnostic. |
packages/ai/src/transports/openai-completions-params.test.ts |
Tests non-reasoning and thinking-off budget behavior. | None. |
packages/ai/src/transports/openai-completions-params.reasoning.test.ts |
Covers Qwen thinking-off behavior near the context limit. | None. |
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
Codex review: needs maintainer review before merge. What this changesRecognize TGI input-length and combined-token validation errors as context overflow so existing compaction recovery can run. Example: TGI rejects a request with
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review This PR fixes a current TGI overflow-recovery gap with a focused patch, sufficient Gateway proof, and no actionable findings. Priority: P2 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe shared AI overflow matcher classifies provider error text for assistant messages and failover; the embedded runner consumes those classifications to compact eligible history and retry. flowchart TD
A[Provider response] --> B[Shared overflow matcher]
B --> C[Assistant and failover classification]
C --> D[Embedded recovery owner]
D --> E[History compaction]
E --> F[Provider retry]
F --> G[User reply]
Technical reviewBest possible solution: Land the narrow TGI matcher extension through the existing compaction recovery owner. Do we have a high-confidence way to reproduce the issue? Current-main source shows the missing TGI patterns and recovery consequence; the supplied baseline Gateway trace demonstrates the failure, but this read-only review ran no target code. Is this the best way to solve the issue? The patch repairs the canonical matcher with exact provider wording, preserves output-only validation behavior, and leaves recovery policy and output budgeting unchanged. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 9cc6124bcf15. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +27, Tests +13, Docs +1. Total +41 across 6 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes: No label 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 HistoryReview history (12 earlier review cycles; latest 8 shown)
Reviewed October 13, 2026, 11:46 PM ET / October 14, 2026, 03:46 UTC (Revision 13). |
…imate margin The openai-completions request builder estimates input as chars/4 with a 1.25 safety margin. Against a real tokenizer (Qwen3) that estimate is 1.4-1.6x the true count for prose, code, tool schemas and CJK text, so a fixed prompt that really fills about 65-73% of the context was refused before provider I/O, with nothing for compaction to recover. When the margined estimate leaves no room and thinking is off (or the model is non-reasoning), budget from the unmargined chars/4 estimate instead and refuse only when that also leaves no room. If the unmargined estimate undercounts, the provider's own context-length rejection enters the same overflow recovery. Thinking-enabled requests keep the margined estimate and the 16-token floor from openclaw#157673. The runtime's required-maintenance test now passes unchanged: its foreground requests go out with roughly 700 and 4,400 output tokens instead of triggering an extra overflow compaction. The refusal fixtures move to estimates of at least 1.25x the context, and an explicit one-token request at an exhausted estimate is still sent.
…mates The unmargined fallback only fired once the margined estimate left no room at all, so a non-thinking request whose margined room was 1-15 tokens was still sent with that cap (down to 1, the original one-token defect), and the cap then jumped back up once the margin was fully exhausted. For requests without thinking, budget from the unmargined estimate as soon as the margined estimate leaves fewer than 16 output tokens, and refuse with context_length_exceeded when the unmargined room is also under 16. Every cap that context pressure reduces is now at least 16 tokens, caps fall steadily within each estimate, and refusal is terminal as the prompt grows. Thinking-enabled requests keep the margined estimate and the 16-token floor from openclaw#157673 unchanged. A caller's own maxTokens that fits the room (1, 2, 16) is still sent as requested; only budgets that context pressure cuts are held to the floor. The refusal now says which estimate it used and how many of the 16 tokens remain, instead of "leaves only 1 output tokens" for an exhausted prompt. The margin drop is logged as keep_max_tokens when a caller's cap is honored without clamping, and the insufficient_output_budget warning is removed because no reduced cap under the floor is sent any more.
…mate Budgets taken from the unmargined estimate were logged only at debug level, so the warn-level signal operators used to spot prompts at the context cap (the insufficient_output_budget lines) disappeared by default. Log those clamp_max_tokens and keep_max_tokens lines at warn level, with the margined estimate alongside, since the provider may still reject the request. Ordinary clamping stays at debug level. Document the requested-cap rule exactly: the room never counts below one token, so a requested cap of 1 is sent in every mode even when the estimate already exceeds the context, and a prompt that really does is rejected by the provider and enters overflow recovery. Any other requested cap within the room is sent as is, and a cap that context pressure cuts below 16 tokens is refused. Pin the fallback threshold (3,145 characters -> 16 tokens, 3,146 -> 212 at a 1,000-token context), the refusal threshold (3,932 -> 16, 3,933 refused), the refusal wording for both estimates, and the one-token request with thinking enabled.
|
Narrowed in The fixed-prompt case was a real regression in Same 56k-character prompt on an isolated Gateway with a tokenizer-accurate loopback server: Undercounted prompts now reach the provider, so recovery depends on its rejection classifying as an overflow. vLLM and SGLang wordings do; a TGI-style 422 would not. This still extends past #157673's recorded decision for non-reasoning and thinking-off requests, so it needs an owner's call. |
No conflicts. Main has moved 1,068 commits past this branch's base 9fdb24b, and the last CI run stopped after one shard failed, so 13 shards never reported.
Budgeting from the unmargined estimate lets an undercounted prompt reach the provider, so recovery depends on its rejection reading as an overflow. Hugging Face TGI rejects with HTTP 422 `Input validation error:` and one of two wordings from router/src/validation.rs: "`inputs` tokens + `max_new_tokens` must be <= N" and "`inputs` must have less than N tokens". classifyFailoverSignal returned `format` for both, which stops the runner's compaction, and isContextOverflow matched neither. Both wordings join the assistant and strict failover overflow tables. classifyFailoverSignal, isContextOverflowError and isContextOverflow now return overflow for both; a `max_new_tokens` limit on its own still does not. The corpus rows, the assistant-message rows and the predicate test fail without the table entries (2, 2 and 1 tests).
Apply the existing useful-output floor to every context-driven clamp, including non-reasoning and thinking-off requests. Keep deliberately short caps when they fit and report exhausted room as context overflow. Builds on the investigations in #161748 and #158161. Refs #161254, #105729, #158159. Co-authored-by: Jacob Tomlinson <[email protected]> Co-authored-by: Alex Mittell <[email protected]> (cherry picked from commit e05ca71)
Upstream openclaw#167878 merged to main as e05ca71 and is not in v2026.9.9 or a beta. Every context-driven clamp on an OpenAI-compatible proxy request now keeps the 16-token useful-output floor, including non-reasoning and thinking-off requests, so a prompt at the context cap is reported as a context overflow and goes through compaction instead of being sent with max_completion_tokens: 1. A deliberately short cap still goes out when it fits; an exhausted cap, explicit or not, is an overflow. The input estimate keeps its 1.25 margin. This replaces the carried openclaw#158161 budget change: the params files go back to v2026.9.9's (bcfc888) and take openclaw#167878 on top, which drops openclaw#158161's unmargined fallback for non-thinking requests, its exhausted explicit one-token exception and its warn-level budget log. Upstream openclaw#158161 is now only the Hugging Face TGI overflow wordings; those stay carried in overflow.ts and the failover tests, unchanged. Applied as e05ca71's source and docs diff. Its new test is rewritten in 9.9's test layout (main had already consolidated it), and the 9.9 tests that pinned the old fallback are removed as on main: the non-reasoning short-budget and insufficient_output_budget warning cases in openai-completions-params.test.ts and the Qwen near-cap asserts in openai-completions-params.reasoning.test.ts.
Upstream openclaw#168326 merged to main as c18324d and is not in v2026.9.9 or a beta. The request builder's own refusal ("Context window exceeded: estimated input N leaves only M output tokens within the C-token context.") is now a context overflow for every classifier, not only the text heuristic, so a prompt that exhausts the output budget shows the /reset, /new or larger-context guidance in live chat, Details, saved history and channel replies. It needs openclaw#167878's refusal wording, carried in the previous commit; openclaw#158161's old wording would not match. Conflicts and 9.9 adaptations: - overflow.ts and overflow.test.ts merged cleanly; the carried openclaw#158161 TGI wordings stay next to the new REQUEST_BUDGET_OVERFLOW_RE. - user-copy.ts: took the widened CONTEXT_OVERFLOW_ERROR_HEAD_RE and pointed 9.9's FAILOVER_REASON_BASE_COPY.context_overflow at the new shared CONTEXT_OVERFLOW_ERROR_MESSAGE (same text); main's unrelated provider prompt-size constants are not carried. - assistant-request-failure-copy.ts: 9.9 keeps its own layout. Its recorded-failure context-overflow copy ("this conversation is too large for the model ... tighter output limit") now returns CONTEXT_OVERFLOW_ERROR_MESSAGE, which is what openclaw#168326 did to main's copy, and server.chat.gateway-server-chat.test.ts and server-methods.test.ts expect the new text. - server-chat.native-provider-error.test.ts does not exist on 9.9 (main added it in openclaw#165488 with a shared test harness 9.9 lacks). It is added with only openclaw#168326's case, on a minimal harness built from 9.9's createAgentEventHandler and test helpers.
…58145 carried after the 9.9 deploy Names the three carried commits, the carried openclaw#158161 budget change that openclaw#167878 replaces, openclaw#158145 moving from 452a23f to 4e5f4e1, and what 9.9's chunked redactor still leaves unmasked under the new openclaw#158145, with the M4 guard, test, control and dist-marker results.
Merge current main into the contributor branch, retain the narrow TGI patterns, and run the TGI corpus rows after the test-suite cleanup. Keep output-only validation errors outside compaction and document the supported wording.
✅ Maintainer security changes approvedA maintainer approved this revision with an explicit security approval comment.
A later push requires a fresh approval comment for an external contributor's PR. |
|
/allow-security-sensitive-change |
|
Merged via squash.
|
…an over-long prompt (openclaw#158161) * fix(ai): reject exhausted proxy completions budgets in every thinking mode When the estimated input leaves no room for output, the openai-completions request builder falls back to max_completion_tokens=1 and still sends the request. openclaw#157673 turned that into a context overflow for thinking-enabled reasoning models; non-reasoning models and thinking-off requests still send the one-token request, which cannot hold a useful reply and comes back cut off by length. Throw the same context_length_exceeded error for those requests when the estimate leaves zero or negative output space, so the existing overflow recovery compacts instead. Positive short budgets (1-15 tokens that fit the estimate) and their insufficient_output_budget warning are unchanged for non-reasoning and thinking-off requests, and deliberately short requested budgets are untouched. Refs openclaw#157307 * fix(ai): budget exhausted non-thinking proxy requests without the estimate margin The openai-completions request builder estimates input as chars/4 with a 1.25 safety margin. Against a real tokenizer (Qwen3) that estimate is 1.4-1.6x the true count for prose, code, tool schemas and CJK text, so a fixed prompt that really fills about 65-73% of the context was refused before provider I/O, with nothing for compaction to recover. When the margined estimate leaves no room and thinking is off (or the model is non-reasoning), budget from the unmargined chars/4 estimate instead and refuse only when that also leaves no room. If the unmargined estimate undercounts, the provider's own context-length rejection enters the same overflow recovery. Thinking-enabled requests keep the margined estimate and the 16-token floor from openclaw#157673. The runtime's required-maintenance test now passes unchanged: its foreground requests go out with roughly 700 and 4,400 output tokens instead of triggering an extra overflow compaction. The refusal fixtures move to estimates of at least 1.25x the context, and an explicit one-token request at an exhausted estimate is still sent. * fix(ai): hold proxy completions caps to the useful floor on both estimates The unmargined fallback only fired once the margined estimate left no room at all, so a non-thinking request whose margined room was 1-15 tokens was still sent with that cap (down to 1, the original one-token defect), and the cap then jumped back up once the margin was fully exhausted. For requests without thinking, budget from the unmargined estimate as soon as the margined estimate leaves fewer than 16 output tokens, and refuse with context_length_exceeded when the unmargined room is also under 16. Every cap that context pressure reduces is now at least 16 tokens, caps fall steadily within each estimate, and refusal is terminal as the prompt grows. Thinking-enabled requests keep the margined estimate and the 16-token floor from openclaw#157673 unchanged. A caller's own maxTokens that fits the room (1, 2, 16) is still sent as requested; only budgets that context pressure cuts are held to the floor. The refusal now says which estimate it used and how many of the 16 tokens remain, instead of "leaves only 1 output tokens" for an exhausted prompt. The margin drop is logged as keep_max_tokens when a caller's cap is honored without clamping, and the insufficient_output_budget warning is removed because no reduced cap under the floor is sent any more. * fix(ai): warn when proxy completions fall back to the unmargined estimate Budgets taken from the unmargined estimate were logged only at debug level, so the warn-level signal operators used to spot prompts at the context cap (the insufficient_output_budget lines) disappeared by default. Log those clamp_max_tokens and keep_max_tokens lines at warn level, with the margined estimate alongside, since the provider may still reject the request. Ordinary clamping stays at debug level. Document the requested-cap rule exactly: the room never counts below one token, so a requested cap of 1 is sent in every mode even when the estimate already exceeds the context, and a prompt that really does is rejected by the provider and enters overflow recovery. Any other requested cap within the room is sent as is, and a cap that context pressure cuts below 16 tokens is refused. Pin the fallback threshold (3,145 characters -> 16 tokens, 3,146 -> 212 at a 1,000-token context), the refusal threshold (3,932 -> 16, 3,933 refused), the refusal wording for both estimates, and the one-token request with thinking enabled. * fix(ai): recover from TGI context rejections through compaction Budgeting from the unmargined estimate lets an undercounted prompt reach the provider, so recovery depends on its rejection reading as an overflow. Hugging Face TGI rejects with HTTP 422 `Input validation error:` and one of two wordings from router/src/validation.rs: "`inputs` tokens + `max_new_tokens` must be <= N" and "`inputs` must have less than N tokens". classifyFailoverSignal returned `format` for both, which stops the runner's compaction, and isContextOverflow matched neither. Both wordings join the assistant and strict failover overflow tables. classifyFailoverSignal, isContextOverflowError and isContextOverflow now return overflow for both; a `max_new_tokens` limit on its own still does not. The corpus rows, the assistant-message rows and the predicate test fail without the table entries (2, 2 and 1 tests).
- HF TGI/TEI's second overflow form ("`inputs` must have less than N tokens")
joins the table, and TGI's router answers validation errors with HTTP 422,
so the 422 handler now checks the shared TGI wordings too. Before, the
first wording only matched on a 400 and neither compressed on TGI's real
status. Sibling 422s (temperature/top_p) stay format_error.
- DashScope / Model Studio "Range of input length should be [1, N]" compresses
instead of failing the turn. Named on `input length`, so the shared
"Range of top_p should be" frame stays a format error.
Port from openclaw/openclaw#158161 and openclaw/openclaw#171712.
…tart-recovery conflicts Takes beta.4 where it carries a fork change natively. Elsewhere it keeps the fork's delta on top of beta.4's code. - Native on beta.4, fork copies dropped: - openclaw#169306 (e353566): session-manager-persistence.ts and session-manager-metadata.worker.ts are byte-identical to beta.4. The fork's session-manager-append-custody.ts pull-forward is deleted; it has no importers left. - openclaw#158161 (177b090): classify.legacy-provider-predicates.test.ts is byte-identical to beta.4, whose corpus carries the same three TGI rows. - runtime-read.ts is beta.4's re-export. The fork's skipInheritance option moves to runtime-read.types.ts, where beta.4 now defines LoadAuthProfileStoreOptions (store.ts and models auth clean pass it). - Fork deltas kept on beta.4's code: - auth-controller.ts: openclaw#93952's withAuthDeadline around beta.4's forceRefresh argument object; the cooldown-probe extraction and its re-export stay (it inlines beta.4's file-local resolveUnavailableAuthReason). - auth-controller.test-support.ts: beta.4's runtime-provider change, which its SIWC tests need, moves into the fork's split-out harness. - failover tests: beta.4's case moves, plus the fork's Anthropic long-context 429 overflow test and its classified-reason 5xx copy test. - assistant-failure.ts: union of imports (recordModelFallbackStop and isPreDispatchToolCallRejectionMessage). - session-store.ts: the fork's per-attempt contextSnapshot ahead of beta.4's buildMainSessionRecoveryAfterAgentRunPatch, so recovery sees its totals. - session-manager-entries.ts: the fork's checkpoint-handle formatter with beta.4's createEntry timestamp. - restart recovery (dispatch, delivery, tests): beta.4's prepareRestartRecoveryDeliveryCurrent and isCurrent structure; the fork's restart-cause wording passes cause to announceRestartRecoveryResumption. - oauth-common-mocks.test-support.ts: beta.4's importOriginal spread, keeping the fork's syncEnvBackedTokenCredentials identity override. - docs/concepts/oauth.md: the fork's dead-grant paragraph in beta.4's wording. - Tests that follow upstream's openclaw#170532 pruning: 3 of the 5 tests in the fork's transcript-file-state.compaction-checkpoint.test.ts are removed, because upstream deleted the same tests; the 2 that remain keep the checkpoint-handle pins. - runtime-context-prompt.ts: the clean merge ran the fork's carrierText through openclaw#166869's joiner-aware append, which puts late context first for a space joiner. The carrier is rendered without a joiner (prompt-prelude.ts), so it gets its own paragraph-order append. The existing joiner test now pins carrierText for both joiners. Not built here (no builds on this host); tsgo and tests run on the M4.

Related: #158159, #167878
What Problem This Solves
Fixes: a turn fails without compacting when Hugging Face TGI rejects an over-long input with
Input validation error.User Impact
TGI input-length and combined input/output-token rejections enter the existing context-overflow recovery path. An output-only
max_new_tokensvalidation failure remains a request error. Output budgets, configuration contracts, and stored data are unchanged.Why This Change Was Made
The canonical AI overflow matcher lacked TGI's two exact validation messages. This preserves @amittell's four-line repair in the assistant and strict failover scopes, merges current main into the contributor branch without rewriting its history, and keeps main's later request-budget fixes and test cleanup.
The classifier corpus now runs a representative subset, so the new TGI rows are explicitly selected. Regression coverage includes the output-only exclusion. The compaction documentation names the supported messages.
Production: +4/-0 lines; tests and test support: +36/-0; docs: +1/-0. The production additions extend two existing scopes; removing unrelated provider clauses just to offset them would weaken supported behavior.
Evidence
Fresh macOS Apple Silicon proof uses an isolated Gateway and task-owned HTTP/SSE proxy in front of Ollama
qwen2.5:7b. The fixture counts serialized message characters / 4 (rounded up), enforces a lower server cap, and emits TGI's exact HTTP-200 SSE error shape withhttp_status_code: 422. Accepted requests go to the real local model. No operator Gateway or shared model was stopped.Baseline main
976cc974fab1912c696d1101bd17a1abf05eb77e: OpenClaw admits the final request (route=fits, estimate 13,061; configured context 131,072). The proxy rejects 12,657 synthetic input units against a 9,000-unit cap. Four identical requests are rejected; no compaction runs; the CLI returns an empty error result (exit 1, 13.51 seconds).On head
50bac1ed6e81b53eac34d5089de9e50e1f3bc886, the same input-cap scenario rejects 12,752 synthetic input units once, invokes overflow compaction, summarizes through real Ollama at 8,384 units, and retries at 5,019 units below the 9,000-unit cap. The CLI deliversLOCAL_RECOVERY_OK, records one compaction, and exits 0 (53.46 seconds; summary inference 6.793 seconds, retried inference 3.378 seconds).The total-token control also succeeds:
12,746 inputs + 1,024 max_new_tokens > 13,000produces the exact TGI total-budget error, then a real Ollama summary (8,377 + 4,096 <= 13,000) and retry (4,998 + 1,024 <= 13,000) deliverLOCAL_RECOVERY_OK. One compaction, exit 0, 29.44 seconds; summary and retry inference took 5.175 and 1.942 seconds.The output-only negative control, on the already-compacted session, returns exactly
Input validation error: `max_new_tokens` must be <= 512. Given: 1024. It remains a request error, retries without shrinking the 5,071-unit prompt, performs no compaction, and exits 1 as expected (27.32 seconds).The proof config disables proactive compaction and memory flushing and uses
keepRecentTokens: 1024to isolate provider-error recovery. Native TGI tokenization, GPU TGI, Linux, and Windows are not covered; this is exact-wire Gateway boundary proof plus live Ollama inference.Regressions fail with main's original matcher: both new assistant cases return false, and both classifier cases return
reason: formatinstead ofcontext_overflow. The output-only controls pass. With the fix:The last suite is import-bound (94.31 seconds inside Vitest); the new AI and classifier files took 2.72 and 5.67 seconds inside Vitest. CI seconds are pending.
pnpm build qaRuntimepassed (4m 51s). Core and package-test type checks, scoped oxlint, formatting, docs MDX sanity, max-lines, line-cap, assertion-safety, database-worker/dialect, timeout-race, mock-export, config-doc, and plugin-inventory checks passed. The gateway-only setup needed the already-declared@openclaw/solid-lintworkspace installed before scoped lint could run; no dependency or lockfile was changed.Independent Codex review: scoped-clean, no actionable findings. The review and size-ratchet rechecks use incorporated main
711a46bcdf649cdf872ae560cc5a4f76064ec1d2; the relevant AI/recovery/classifier owners are unchanged from the baseline proof. Earlier budgeting work is already covered by #167878 and #168326 and is outside this patch.Maintainer action before merge: the enforced Security Review flags
failover-classification.auth-format.cases.tsvia its credential-path glob and requires a fresh/allow-security-sensitive-changeapproval for this head. This file change is the output-only TGI negative fixture; no production credential code changed.