Skip to content

fix(ai): turns fail without compaction when Hugging Face TGI rejects an over-long prompt - #158161

Merged
steipete merged 9 commits into
openclaw:mainfrom
amittell:fix/completions-exhausted-budget-all-modes
Oct 14, 2026
Merged

steipete merged 9 commits into
openclaw:mainfrom
amittell:fix/completions-exhausted-budget-all-modes

Conversation

@amittell

@amittell amittell commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

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_tokens validation 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 with http_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 delivers LOCAL_RECOVERY_OK, records one compaction, and exits 0 (53.46 seconds; summary inference 6.793 seconds, retried inference 3.378 seconds).

TGI SSE: Input validation error: `inputs` must have less than 9000 tokens. Given: 12752
context overflow detected (attempt 1/3); attempting auto-compaction for tgi/qwen2.5:7b
auto-compaction succeeded for tgi/qwen2.5:7b; retrying prompt
proxy: retry input=5019 < server_cap=9000 -> real Ollama
CLI: LOCAL_RECOVERY_OK; lastTurnCompactions=1; stopReason=stop; exit=0

The total-token control also succeeds: 12,746 inputs + 1,024 max_new_tokens > 13,000 produces 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) deliver LOCAL_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: 1024 to 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: format instead of context_overflow. The output-only controls pass. With the fix:

Focused suite Result Wall time
AI overflow 11/11 15.84 s
Failover classification 57/57 10.70 s
OpenAI-compatible request budgets 33/33 9.98 s
Existing context-overflow policies 5/5 114.66 s

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 qaRuntime passed (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-lint workspace 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.ts via its credential-path glob and requires a fresh /allow-security-sensitive-change approval for this head. This file change is the output-only TGI negative fixture; no production credential code changed.

… 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
Copilot AI lite review requested due to automatic review settings September 25, 2026 14:32
@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Medium severity

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.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 25, 2026
@clawsweeper

clawsweeper Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Recognize TGI input-length and combined-token validation errors as context overflow so existing compaction recovery can run.

Example: TGI rejects a request with inputs must have less than 9000 tokens. Given: 12752.

  • Before: The recorded baseline repeats the rejected request without compaction and ends the turn unsuccessfully.
  • After: The recorded head compacts once, retries below the server cap, and delivers LOCAL_RECOVERY_OK.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused canonical-owner repair with shipped-entry-point recovery proof, useful regression controls, successful exact-head gates, and no open findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The recorded exact-head CLI/Gateway run exercises the production transport and recovery owners on macOS through a TGI-shaped SSE rejection proxy with real Ollama inference: both context errors recover successfully, while output-only validation does not compact.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A TGI input-length rejection can end a turn without compacting recoverable conversation history.
Reason: A narrow, demonstrated provider failure is repaired through the established owner, with maintainer participation on the current head.

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
Reviewed head: 50bac1ed6e81b53eac34d5089de9e50e1f3bc886

Before merge

None.

Findings

None.

Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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

  • Shared assistant and strict failover overflow scopes keeps the original intent (90ddeb4: Centralize overflow wording in the AI package while retaining distinct caller scopes and preventing classification drift.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change: The pinned introduction diff adds only TGI patterns, assistant and structured-classification regression cases, corpus selection, and compaction documentation. (packages/ai/src/utils/overflow.ts:25, 50bac1ed6e81)
  • Current main still needs the repair: Fetched main lacks both TGI patterns; recovery rejects an assistant error already classified as a non-overflow reason before attempting compaction. (src/agents/embedded-agent-runner/run/overflow-context-recovery.ts:96, 9cc6124bcf15)
  • Shipped-entry-point proof: The full PR body records isolated macOS Gateway runs through an HTTP/SSE fault proxy and real Ollama inference: input-length and combined-budget errors compact and deliver a reply; the output-only negative control does not compact. Native GPU TGI is outside the recorded coverage. (50bac1ed6e81)
  • Exact-head approval and gates: The discussion records steipete's security approval for this head, and live commit statuses report success for the CI gate, dependency review, and security-sensitive review; the body’s earlier approval request is resolved. (50bac1ed6e81)
  • Canonical ownership and history: Feature history across the package extraction and older src/llm paths identifies the shared scoped matcher as the existing owner; commit 90ddeb4 centralized the scopes to prevent classifier drift. (packages/ai/src/utils/overflow.ts:43, 90ddeb4b4065)
  • Provider wire-contract verification: The PR explicitly relies on TGI's validation protocol; its published source defines the two matched context errors separately from the output-only MaxNewTokens error. (router/src/validation.rs:997, b4adbf2f6e2e)

PR surface

Source +27, Tests +13, Docs +1. Total +41 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 27 0 +27
Tests 2 13 0 +13
Docs 1 1 0 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 41 0 +41

Review metrics

Metric Value Why it matters
Production versus test growth Production +4/-0; tests and fixtures +36/-0 Extends existing matcher scopes and regression tables without adding another classifier or test-only production seam.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A provider-specific classification gap breaks recovery for oversized TGI requests, with limited blast radius.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (12 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-28T20:51:28.353Z sha 57d604f :: blocked before merge. :: none
  • reviewed 2026-10-09T13:13:49.616Z sha 57d604f :: blocked before merge. :: none
  • reviewed 2026-10-09T18:58:14.502Z sha 086c2d5 :: blocked before merge. :: none
  • reviewed 2026-10-09T22:29:21.170Z sha 086c2d5 :: blocked before merge. :: none
  • reviewed 2026-10-10T04:38:49.555Z sha 69e2961 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-10T12:36:18.817Z sha 69e2961 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-14T03:15:39.990Z sha 50bac1e :: needs maintainer review before merge. :: none
  • reviewed 2026-10-14T03:25:38.532Z sha 50bac1e :: needs maintainer review before merge. :: none

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.
@amittell

Copy link
Copy Markdown
Contributor Author

Narrowed in e3e9d0974de. Without thinking, once the margined estimate leaves fewer than 16 output tokens, the builder budgets from the estimate without the 1.25 margin and refuses only if that also leaves fewer than 16. Thinking-enabled requests keep #157673's rule.

The fixed-prompt case was a real regression in b1560e72cd0. Against the Qwen3 tokenizer the margined estimate runs 1.4-1.6x the real count for prose, code and tool schemas, so prompts that filled 65-73% of the context were refused. Main sends max_completion_tokens: 1 for the same prompts, so neither was usable.

Same 56k-character prompt on an isolated Gateway with a tokenizer-accurate loopback server: ST at cap 1 on main, no provider call on b1560e72cd0, a full reply at cap 4096 on the head. The body also has both failure paths on the head with production compaction settings: a prompt past the unmargined estimate refused locally, and a base64-heavy prompt the estimate undercounted, rejected by the provider with vLLM's current wording. Both compacted and the retry replied.

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.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 26, 2026
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).
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Sep 27, 2026
@clawsweeper clawsweeper Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 27, 2026
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
RomneyDa pushed a commit that referenced this pull request Oct 10, 2026
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)
amittell added a commit to amittell/openclaw that referenced this pull request Oct 10, 2026
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.
amittell added a commit to amittell/openclaw that referenced this pull request Oct 10, 2026
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.
amittell added a commit to amittell/openclaw that referenced this pull request Oct 10, 2026
…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.
@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

✅ Maintainer security changes approved

A maintainer approved this revision with an explicit security approval comment.

A later push requires a fresh approval comment for an external contributor's PR.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XS and removed size: M labels Oct 14, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 14, 2026
@steipete

Copy link
Copy Markdown
Contributor

/allow-security-sensitive-change

@steipete steipete self-assigned this Oct 14, 2026
@steipete
steipete merged commit 177b090 into openclaw:main Oct 14, 2026
155 of 158 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…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).
teknium1 added a commit to NousResearch/hermes-agent that referenced this pull request Oct 19, 2026
- 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.
amittell added a commit to amittell/openclaw that referenced this pull request Oct 28, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. security-sensitive-changed size: XS 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.

3 participants