Skip to content

Clamp stream max tokens to remaining context window - #85008

Closed
Major126 wants to merge 3 commits into
openclaw:mainfrom
Major126:codex/max-tokens-context-clamp
Closed

Major126 wants to merge 3 commits into
openclaw:mainfrom
Major126:codex/max-tokens-context-clamp

Conversation

@Major126

Copy link
Copy Markdown

Fixes #83086.

Summary

  • clamp configured/requested stream maxTokens to the remaining context window instead of forwarding values that exceed the available budget
  • clamp callModel.maxTokens too so providers that fall back to model defaults cannot bypass the same limit
  • add focused unit coverage for both option-level and model-level clamping

Verification

  • OPENCLAW_VITEST_INCLUDE_FILE=src/agents/pi-embedded-runner/extra-params.sampling.test.ts node scripts/run-vitest.mjs run --config test/vitest/vitest.unit-fast.config.ts --passWithNoTests=false
  • corepack pnpm exec oxfmt --check src/agents/pi-embedded-runner/extra-params.ts src/agents/pi-embedded-runner/extra-params.sampling.test.ts src/agents/pi-embedded-runner/stream-max-tokens-context-window.ts
  • git diff --check

Notes

  • pnpm tsgo:core:test was not run because the repo's sparse-checkout guard requires a much broader checkout (packages, ui/src, etc.)

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 21, 2026
@clawsweeper

clawsweeper Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

Workflow note: Future ClawSweeper reviews update this same comment in place.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

Summary
The PR adds an embedded-runner stream wrapper that estimates used input tokens and clamps configured, runtime, and model max token values against the remaining context window, with focused unit coverage.

Reproducibility: yes. Source inspection shows current main can forward a full OpenAI-compatible model/config output cap without subtracting input tokens, and the linked issue provides a concrete StepFun failure pattern.

PR rating
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦐 gold shrimp
Summary: The patch is directionally useful but not merge-ready because proof is missing and one supported max-token source remains uncovered.

Rank-up moves:

  • Clamp or remove model.params max-token aliases when applying the remaining-context budget.
  • Add focused regression coverage for a long-prompt model.params.max_completion_tokens path.
  • Post redacted real runtime proof from StepFun or an equivalent OpenAI-compatible provider path.
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Real behavior proof
Needs real behavior proof before merge: The PR has unit/format verification only; it needs redacted real runtime proof such as terminal output, logs, or a screenshot/artifact from StepFun or an equivalent provider showing the oversized token error is gone. Redact API keys, IPs, phone numbers, endpoints, and other private details; updating the PR body should trigger a fresh review, or a maintainer can ask @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • The PR still needs after-fix real behavior proof from StepFun or an equivalent OpenAI-compatible provider path; unit tests and format checks do not prove the runtime failure is gone.
  • The new heuristic clamp applies broadly to embedded runner streams and may shorten output caps for long prompts, so maintainers need confidence that it handles all existing max-token sources rather than only a subset.

Maintainer options:

  1. Repair all token-cap sources before merge (recommended)
    Update the clamp so model.params max-token aliases cannot override the remaining-context budget, then add proof from the affected runtime path.
  2. Land as a partial mitigation
    Maintainers could intentionally accept the partial improvement, but the linked bug should remain open until the request-builder/model.params bypass is covered.
  3. Pause until proof exists
    Because this is a draft external PR without real behavior proof, maintainers can pause review until the contributor posts redacted runtime evidence.

Next step before merge
The PR needs contributor-provided real behavior proof and a focused code repair for the remaining max-token source before normal merge review can continue.

Security
Cleared: The diff adds local TypeScript request-budgeting logic and tests; it does not change dependencies, CI, secrets, permissions, package metadata, or code-download paths.

Review findings

  • [P2] Clamp model params token aliases too — src/agents/pi-embedded-runner/stream-max-tokens-context-window.ts:125-127
Review details

Best possible solution:

Clamp the final outbound max-token budget across every source the request builder can choose, including model.params aliases, while preserving smaller explicit runtime caps and adding regression coverage for the option, model, and model.params paths.

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

Yes. Source inspection shows current main can forward a full OpenAI-compatible model/config output cap without subtracting input tokens, and the linked issue provides a concrete StepFun failure pattern.

Is this the best way to solve the issue?

No, not yet. The stream-wrapper approach is plausible, but the proposed fix does not cover model.params max-token aliases that the current request builder prefers over model.maxTokens.

Label changes:

  • add P1: The linked regression can make long-context model calls fail repeatedly once prompt input grows, blocking agent output for affected users.
  • add merge-risk: 🚨 compatibility: The PR globally changes generated max token limits using an estimate and needs proof that existing provider/config max-token paths are not broken or bypassing the clamp.
  • add rating: 🧂 unranked krab: Current PR rating is 🧂 unranked krab because proof is 🧂 unranked krab, patch quality is 🦐 gold shrimp, and The patch is directionally useful but not merge-ready because proof is missing and one supported max-token source remains uncovered.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR has unit/format verification only; it needs redacted real runtime proof such as terminal output, logs, or a screenshot/artifact from StepFun or an equivalent provider showing the oversized token error is gone. Redact API keys, IPs, phone numbers, endpoints, and other private details; updating the PR body should trigger a fresh review, or a maintainer can ask @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Label justifications:

  • P1: The linked regression can make long-context model calls fail repeatedly once prompt input grows, blocking agent output for affected users.
  • merge-risk: 🚨 compatibility: The PR globally changes generated max token limits using an estimate and needs proof that existing provider/config max-token paths are not broken or bypassing the clamp.
  • rating: 🧂 unranked krab: Current PR rating is 🧂 unranked krab because proof is 🧂 unranked krab, patch quality is 🦐 gold shrimp, and The patch is directionally useful but not merge-ready because proof is missing and one supported max-token source remains uncovered.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR has unit/format verification only; it needs redacted real runtime proof such as terminal output, logs, or a screenshot/artifact from StepFun or an equivalent provider showing the oversized token error is gone. Redact API keys, IPs, phone numbers, endpoints, and other private details; updating the PR body should trigger a fresh review, or a maintainer can ask @clawsweeper re-review. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Full review comments:

  • [P2] Clamp model params token aliases too — src/agents/pi-embedded-runner/stream-max-tokens-context-window.ts:125-127
    The new model-level clamp only rewrites maxTokens, but buildOpenAICompletionsParams still prefers model.params.max_completion_tokens/max_tokens over model.maxTokens. A runtime model with params like the existing Kimi coverage can still send the un-clamped params value on a long prompt, so the oversized-token failure can survive this patch; clamp or clear those aliases when constructing the next model.
    Confidence: 0.86

Overall correctness: patch is incorrect
Overall confidence: 0.82

Acceptance criteria:

  • OPENCLAW_VITEST_INCLUDE_FILE=src/agents/pi-embedded-runner/extra-params.sampling.test.ts node scripts/run-vitest.mjs run --config test/vitest/vitest.unit-fast.config.ts --passWithNoTests=false
  • node scripts/run-vitest.mjs src/agents/openai-transport-stream.test.ts
  • git diff --check

What I checked:

  • PR clamp scope: The new helper resolves model-level max tokens only from callModel.maxTokens and configuredModel.maxTokens, not from the model.params max-token aliases that current OpenAI-compatible request building can prefer. (src/agents/pi-embedded-runner/stream-max-tokens-context-window.ts:120, 532e191d6f96)
  • Current request precedence: Current main resolves OpenAI-compatible max tokens as runtime options.maxTokens, then model.params aliases, then model.maxTokens, so leaving model.params.max_completion_tokens intact can still emit an unclamped value. (src/agents/openai-transport-stream.ts:2901, 277a4b695264)
  • Existing test proves model.params precedence: Current tests assert that model.params.max_completion_tokens is sent before model.maxTokens, confirming the bypass path is a supported behavior that this PR needs to account for. (src/agents/openai-transport-stream.test.ts:4506, 0604d25101c7)
  • Linked issue source context: The linked bug report and follow-up ClawSweeper review identify the same root problem: current OpenAI-compatible calls can forward a full output cap without subtracting already-used input tokens.
  • Real behavior proof check: The PR body lists a focused Vitest command, oxfmt, and git diff --check, but no redacted live provider output, runtime log, terminal screenshot, recording, or linked artifact showing the affected provider path after the fix. (532e191d6f96)

Likely related people:

  • steipete: Available local blame and log history for the OpenAI-compatible max-token resolver, extra-param forwarding, and StepFun manifest rows all point to commit 0604d25 by Peter Steinberger in this checkout. (role: current source/history owner; confidence: medium; commits: 0604d25101c7; files: src/agents/openai-transport-stream.ts, src/agents/pi-embedded-runner/extra-params.ts, extensions/stepfun/openclaw.plugin.json)
  • albert-zen: The changelog credits this handle for the OpenAI-compatible per-model max_completion_tokens/max_tokens behavior that is central to the remaining bypass path, though local commit history is collapsed. (role: historical adjacent contributor; confidence: low; files: CHANGELOG.md, src/agents/openai-transport-stream.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against 277a4b695264.

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels May 21, 2026
@clawsweeper

clawsweeper Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

steipete pushed a commit to rendrag-git/openclaw that referenced this pull request May 24, 2026
…like openai-completions endpoints

Strict OpenAI-compatible servers (vLLM, LocalAI, llama.cpp, LM Studio, DashScope, GLM, Kimi) reject Chat Completions requests where max_completion_tokens >= max_model_len with HTTP 400. OpenClaw can emit such values when the catalog has model.maxTokens >= model.contextWindow (e.g. wildcard-discovered vLLM models defaulting to large maxTokens).

Clamp to contextWindow - 1 in buildOpenAICompletionsParams when usesExplicitProxyLikeEndpoint is true. Native OpenAI/Azure/OpenRouter paths are byte-identical.

Supersedes openclaw#85008 at the canonical payload builder seam (covers gateway, embedded runner, and public plugin-SDK consumers in a single 12-line change with no heuristic estimator).
@steipete

Copy link
Copy Markdown
Contributor

Closing as superseded by #85889, which landed on main as 1d1a7c26d8867fdfa98c97d8b510ad0ce1951858.

#85889 keeps the fix at the shared OpenAI Chat Completions payload builder and clamps against the estimated final outbound request after compatibility transforms, including the remaining-context case this PR was targeting.

Thanks for working on this; future PRs are easier for maintainers to carry forward when "Allow edits by maintainers" is enabled.

@steipete steipete closed this May 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: max_tokens not subtracting used input tokens, causing API "too large" errors

2 participants