[GH-ISSUE #4838] [Engine] Claude Code treats the context-overflow 400 on /v1/messages as a generic API error: three identical retries, no compaction #2219

Closed
opened 2026-11-04 01:57:36 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @gdevenyi on GitHub (Oct 31, 2026).
Original GitHub issue: https://github.com/Niko1221/Strata/issues/4838

Area

[Engine] (speed, kernels, models, the server and API)

Desktop app, Terminal or source?

Source (START-HERE.bat, setup.sh or a build)

A source checkout with the mock engine. No model and no GPU were used.

What happened

Earlier discussion: #1675, with #1615 and #1623. This report is about a different client.

When a prompt no longer fits, Claude Code 2.1.316 treats Strata's overflow 400 on /v1/messages as a generic API error. It sends the same request three times, does not compact, and the session stays stuck: the next short message fails the same way.

Strata answers (serve/server.py:5290):

request exceeds the context window: prompt (27442 tokens) leaves no room to answer in the context (25000); requests are never truncated

Expected: Claude Code compacts the conversation and carries on, as it does for this error from Anthropic's API.

A different client from the earlier threads. #1615, #1623 and #1675 were about Pi and about llama.cpp's phrase. #1623 added request exceeds the context window, and the #1615 reporter confirmed that Pi matches it. #1675 proposed llama.cpp's phrase as a second phrase, and was closed with "Two phrases for one error would be noise", because Pi already matched. On a 400, Claude Code does not match that phrase: in the 2.1.316 bundle a 400 is classified by prompt is too long or input is too long for requested model. (Unconfirmed static analysis, from reading the bundle: context window is matched only on an HTTP 413, which Anthropic's errors page defines as a byte limit on the request.) The #1615 reply said: "If a harness you use matches a different phrase, tell us which and we will check it against the message." This is that report. CONTRIBUTING.md says new evidence goes to the original discussion, and those threads are closed; the closing note on #1615 says "A new issue that links this one works too", so I am filing it here. The decision is yours. I have not opened a PR, and CONTRIBUTING.md says a declined proposal is not resubmitted.

Results. Same mock server each time, with a 25,000-token context. Only the text of the 400 differs.

Message text Turn that overflows The next short turn
Strata's api_error, 3 POSTs, all identical api_error, 3 POSTs
prompt is too long: N tokens > C maximum (control) completed, 3 POSTs: the 400, a compaction request, the smaller retry completed, 1 POST
The control's text, then Strata's text after ; completed, 3 POSTs completed, 1 POST

What the control proves. With the same status (400), the same error type and the same server, the words alone decide whether Claude Code recovers.

What it does not prove.

  • The real engine or a real tokenizer. ByteTokenizer counts one token per byte, and the model's replies are scripted, including the summary.
  • How often a real session reaches this 400. strata launch sets CLAUDE_CODE_MAX_CONTEXT_TOKENS (strata_cli/launch/harness.py:115), so Claude Code should normally compact by itself first. This 400 is the backstop for a prompt that jumps past the limit in one turn. Setting that variable and CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096 by hand gave the same results as the table. I did not run through strata launch itself.
  • Interactive sessions or an overflow caused by a tool result. All runs were claude -p with --tools "", and the overflow came from a user prompt.
  • That the third message is safe in every code path. The bundle also has an exact-form regex, /^prompt is too long: \d+ tokens > \d+ maximum$/, which that message does not satisfy. I did not trace what it gates; recovery happened in the run anyway.
  • Anything about other clients. I did not run Pi or any other client against the third message. It still contains exceeds the context window, the text the #1615 reporter says Pi matches.

A one-turn session shows only half of it. With a 4,000-token context and a single prompt, Strata's text gives api_error and 3 POSTs. The control gives prompt_too_long and 1 POST, with no compaction. So the wording changes the classification there, but nothing recovers. Claude Code's docs say a single exchange cannot be compacted.

The wording, from primary docs:

  • Anthropic's context windows page: "If the input alone already exceeds the model's context window, the API returns a 400 invalid_request_error ("prompt is too long") on every model."
  • Claude Code's error reference lists Prompt is too long, and has a precedent for a provider with other words: "Amazon Bedrock reports this condition as Input is too long for requested model., which Claude Code handles the same way. Before v2.1.217, Claude Code didn't recognize the Bedrock wording, so auto-compact never triggered on it".
  • Not found in the docs: the form with numbers, N tokens > C maximum. I took it from the Claude Code 2.1.316 bundle, so this is unconfirmed static analysis (/prompt is too long[^0-9]*(\d+)\s*tokens?\s*>\s*(\d+)/). The error reference says only that the message changes "When the API reports token counts in its error". The doc phrase is the part that matters for matching; the numbers are client code, not a documented format.

The second 400 (serve/server.py:5297), a smaller case. It is reached only with --no-fit-max-tokens / "fit_max_tokens": false; by default Strata shortens max_tokens instead. With a 20,000-token context and one prompt, Strata's text gave api_error and 3 identical POSTs with max_tokens 128000. With input length and max_tokensexceed context limit: P + M > C, decrease input length ormax_tokens and try again, Claude Code retried once with max_tokens 12073 and completed. That wording comes from the bundle's matcher (the part up to P + M > C; the tail is my own), not from a doc page. Anthropic's page says newer models accept such a request, so this case may not be worth a change.

The choices as I see them, for you to decide:

  1. Use Anthropic's wording on /v1/messages only, and keep the current text on the other routes. Service.prepare raises the error for all of them today, so this needs a catch in the Messages route.
  2. One message holding both phrases (the third row above). This is the "two phrases" you declined in #1675, but here the second phrase serves a different client, and without it this client does not recover.
  3. Leave it and document it, if you consider the backstop too rare to matter.

Do you want a fix PR? If yes, say which of 1 or 2 and I will send it. If you pick 3, or would rather not change this, I will not open one.

Smallest steps or command that reproduce it

Needs Claude Code on the PATH and a Python with the repo's dependencies. It talks only to the local mock, with a dummy key and a temporary config folder.

Save these two files in the repo root, then run sh overflow_run.sh strata, sh overflow_run.sh anthropic and sh overflow_run.sh both.

overflow_mock.py:

# usage, from the repo root: PYTHONPATH=. python overflow_mock.py strata|anthropic|both CONTEXT
import re, sys, time
from pathlib import Path
from serve.frontend import ChatTemplate
from serve.server import ByteTokenizer, MockEngine, Service, serve

mode, context = sys.argv[1], int(sys.argv[2])
prepare = Service.prepare

def wrapped(self, *args, **kwargs):
    print("REQUEST", flush=True)
    try:
        return prepare(self, *args, **kwargs)
    except ValueError as e:
        m = re.search(r"prompt \((\d+) tokens\) leaves no room.*context \((\d+)\)", str(e))
        if m and mode == "anthropic":   # only the text of the no-room 400 changes
            raise ValueError(f"prompt is too long: {m[1]} tokens > {m[2]} maximum")
        if m and mode == "both":
            raise ValueError(f"prompt is too long: {m[1]} tokens > {m[2]} maximum; {e}")
        raise

Service.prepare = wrapped
tok = ByteTokenizer()
engine = MockEngine(tok, "</think>\n\n<summary>short summary</summary>", max_context=context)
svc = Service(engine, tok, ChatTemplate(Path("serve/chat_template.jinja")))
print("PORT", serve(svc, port=0).server_address[1], flush=True)
time.sleep(600)

overflow_run.sh:

#!/bin/sh
# usage, from the repo root: sh overflow_run.sh strata|anthropic|both
LOG=$(mktemp); PYTHONPATH=. PYTHONDONTWRITEBYTECODE=1 python overflow_mock.py "$1" 25000 > "$LOG" 2>&1 &
SRV=$!; sleep 3
export ANTHROPIC_BASE_URL=http://127.0.0.1:$(sed -n 's/^PORT //p' "$LOG") ANTHROPIC_API_KEY=x
export CLAUDE_CONFIG_DIR=$(mktemp -d) CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 DISABLE_AUTOUPDATER=1
cd "$(mktemp -d)"; SID=$(python -c 'import uuid; print(uuid.uuid4())')
turn() {  # $1 = characters, $2 = --session-id or --resume
  P=$(python -c "print(('lorem ipsum dolor sit amet ' * 1000)[:$1])"); B=$(grep -c '^REQUEST' "$LOG")
  claude -p "$P" "$2" "$SID" --model claude-sonnet-5-5 --tools "" --output-format json < /dev/null \
    | python -c "import json,sys; j=json.load(sys.stdin); print(j['terminal_reason'], '|', str(j['result'])[:70], end=' | ')"
  echo "POSTs: $(( $(grep -c '^REQUEST' "$LOG") - B ))"
}
turn 1500 --session-id; turn 1500 --resume; turn 1500 --resume
turn 16000 --resume     # the prompt no longer fits
turn 200 --resume       # a short next turn
kill "$SRV"

I ran these inside unshare -rn with only the loopback interface up, so that nothing could reach the real API, and with the mock file kept outside the repo and its path passed in. The output is under Logs.

Reproduction status

Reproduced locally

With the mock engine only (MockEngine in serve/server.py). Not reproduced on a real engine or GPU. What I say about the Claude Code bundle's code is unconfirmed static analysis; the table above is what I saw it do.

Strata version

Git commit c62d5e3a (0.2.9, main). Claude Code 2.1.316.

Graphics card, memory and system

None used (mock engine). Linux 7.2.9, x86-64.

Model, size and settings

MockEngine with ByteTokenizer, context 25000 (max_context), default fit_max_tokens. Claude Code run with --model claude-sonnet-5-5 --tools "", a name Strata ignores.

Logs

$ sh overflow_run.sh strata
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 1
api_error | API Error: 400 request exceeds the context window: prompt (27442 token | POSTs: 3
api_error | API Error: 400 request exceeds the context window: prompt (27643 token | POSTs: 3

$ sh overflow_run.sh anthropic
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 3
completed | <summary>short summary</summary> | POSTs: 1

$ sh overflow_run.sh both
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 1
completed | <summary>short summary</summary> | POSTs: 3
completed | <summary>short summary</summary> | POSTs: 1

The three POSTs of the control's overflow turn, from a server-side request log in an equivalent run:

messages=9  400 prompt is too long: 27443 tokens > 25000 maximum
messages=7  200 prompt 17741 tokens
messages=6  200 prompt 24053 tokens

Written with an AI agent (Claude Code), which also ran the steps above.

🤖 Generated with Claude Code

https://claude.ai/code/session_01W53iURzvDQMjnYemag8uvv

Originally created by @gdevenyi on GitHub (Oct 31, 2026). Original GitHub issue: https://github.com/Niko1221/Strata/issues/4838 ### Area [Engine] (speed, kernels, models, the server and API) ### Desktop app, Terminal or source? Source (START-HERE.bat, setup.sh or a build) A source checkout with the mock engine. No model and no GPU were used. ### What happened Earlier discussion: #1675, with #1615 and #1623. This report is about a different client. When a prompt no longer fits, Claude Code 2.1.316 treats Strata's overflow 400 on `/v1/messages` as a generic API error. It sends the same request three times, does not compact, and the session stays stuck: the next short message fails the same way. Strata answers (`serve/server.py:5290`): ``` request exceeds the context window: prompt (27442 tokens) leaves no room to answer in the context (25000); requests are never truncated ``` Expected: Claude Code compacts the conversation and carries on, as it does for this error from Anthropic's API. **A different client from the earlier threads.** #1615, #1623 and #1675 were about Pi and about llama.cpp's phrase. #1623 added `request exceeds the context window`, and the #1615 reporter confirmed that Pi matches it. #1675 proposed llama.cpp's phrase as a second phrase, and was closed with "Two phrases for one error would be noise", because Pi already matched. On a 400, Claude Code does not match that phrase: in the 2.1.316 bundle a 400 is classified by `prompt is too long` or `input is too long for requested model`. (Unconfirmed static analysis, from reading the bundle: `context window` is matched only on an HTTP 413, which Anthropic's errors page defines as a byte limit on the request.) The #1615 reply said: "If a harness you use matches a different phrase, tell us which and we will check it against the message." This is that report. CONTRIBUTING.md says new evidence goes to the original discussion, and those threads are closed; the closing note on #1615 says "A new issue that links this one works too", so I am filing it here. The decision is yours. I have not opened a PR, and CONTRIBUTING.md says a declined proposal is not resubmitted. **Results.** Same mock server each time, with a 25,000-token context. Only the text of the 400 differs. | Message text | Turn that overflows | The next short turn | | --- | --- | --- | | Strata's | `api_error`, 3 POSTs, all identical | `api_error`, 3 POSTs | | `prompt is too long: N tokens > C maximum` (control) | `completed`, 3 POSTs: the 400, a compaction request, the smaller retry | `completed`, 1 POST | | The control's text, then Strata's text after `; ` | `completed`, 3 POSTs | `completed`, 1 POST | **What the control proves.** With the same status (400), the same error type and the same server, the words alone decide whether Claude Code recovers. **What it does not prove.** - The real engine or a real tokenizer. `ByteTokenizer` counts one token per byte, and the model's replies are scripted, including the summary. - How often a real session reaches this 400. `strata launch` sets `CLAUDE_CODE_MAX_CONTEXT_TOKENS` (`strata_cli/launch/harness.py:115`), so Claude Code should normally compact by itself first. This 400 is the backstop for a prompt that jumps past the limit in one turn. Setting that variable and `CLAUDE_CODE_MAX_OUTPUT_TOKENS=4096` by hand gave the same results as the table. I did not run through `strata launch` itself. - Interactive sessions or an overflow caused by a tool result. All runs were `claude -p` with `--tools ""`, and the overflow came from a user prompt. - That the third message is safe in every code path. The bundle also has an exact-form regex, `/^prompt is too long: \d+ tokens > \d+ maximum$/`, which that message does not satisfy. I did not trace what it gates; recovery happened in the run anyway. - Anything about other clients. I did not run Pi or any other client against the third message. It still contains `exceeds the context window`, the text the #1615 reporter says Pi matches. **A one-turn session shows only half of it.** With a 4,000-token context and a single prompt, Strata's text gives `api_error` and 3 POSTs. The control gives `prompt_too_long` and 1 POST, with no compaction. So the wording changes the classification there, but nothing recovers. Claude Code's docs say a single exchange cannot be compacted. **The wording, from primary docs:** - Anthropic's [context windows page](https://platform.claude.com/docs/en/build-with-claude/context-windows#context-window-overflow-behavior): "If the input alone already exceeds the model's context window, the API returns a 400 `invalid_request_error` ("prompt is too long") on every model." - Claude Code's [error reference](https://code.claude.com/docs/en/errors#prompt-is-too-long) lists `Prompt is too long`, and has a precedent for a provider with other words: "Amazon Bedrock reports this condition as `Input is too long for requested model.`, which Claude Code handles the same way. Before v2.1.217, Claude Code didn't recognize the Bedrock wording, so auto-compact never triggered on it". - Not found in the docs: the form with numbers, `N tokens > C maximum`. I took it from the Claude Code 2.1.316 bundle, so this is unconfirmed static analysis (`/prompt is too long[^0-9]*(\d+)\s*tokens?\s*>\s*(\d+)/`). The error reference says only that the message changes "When the API reports token counts in its error". The doc phrase is the part that matters for matching; the numbers are client code, not a documented format. **The second 400 (`serve/server.py:5297`), a smaller case.** It is reached only with `--no-fit-max-tokens` / `"fit_max_tokens": false`; by default Strata shortens `max_tokens` instead. With a 20,000-token context and one prompt, Strata's text gave `api_error` and 3 identical POSTs with `max_tokens` 128000. With `input length and `max_tokens` exceed context limit: P + M > C, decrease input length or `max_tokens` and try again`, Claude Code retried once with `max_tokens` 12073 and completed. That wording comes from the bundle's matcher (the part up to `P + M > C`; the tail is my own), not from a doc page. Anthropic's page says newer models accept such a request, so this case may not be worth a change. **The choices as I see them, for you to decide:** 1. Use Anthropic's wording on `/v1/messages` only, and keep the current text on the other routes. `Service.prepare` raises the error for all of them today, so this needs a catch in the Messages route. 2. One message holding both phrases (the third row above). This is the "two phrases" you declined in #1675, but here the second phrase serves a different client, and without it this client does not recover. 3. Leave it and document it, if you consider the backstop too rare to matter. **Do you want a fix PR?** If yes, say which of 1 or 2 and I will send it. If you pick 3, or would rather not change this, I will not open one. ### Smallest steps or command that reproduce it Needs Claude Code on the PATH and a Python with the repo's dependencies. It talks only to the local mock, with a dummy key and a temporary config folder. Save these two files in the repo root, then run `sh overflow_run.sh strata`, `sh overflow_run.sh anthropic` and `sh overflow_run.sh both`. `overflow_mock.py`: ```python # usage, from the repo root: PYTHONPATH=. python overflow_mock.py strata|anthropic|both CONTEXT import re, sys, time from pathlib import Path from serve.frontend import ChatTemplate from serve.server import ByteTokenizer, MockEngine, Service, serve mode, context = sys.argv[1], int(sys.argv[2]) prepare = Service.prepare def wrapped(self, *args, **kwargs): print("REQUEST", flush=True) try: return prepare(self, *args, **kwargs) except ValueError as e: m = re.search(r"prompt \((\d+) tokens\) leaves no room.*context \((\d+)\)", str(e)) if m and mode == "anthropic": # only the text of the no-room 400 changes raise ValueError(f"prompt is too long: {m[1]} tokens > {m[2]} maximum") if m and mode == "both": raise ValueError(f"prompt is too long: {m[1]} tokens > {m[2]} maximum; {e}") raise Service.prepare = wrapped tok = ByteTokenizer() engine = MockEngine(tok, "</think>\n\n<summary>short summary</summary>", max_context=context) svc = Service(engine, tok, ChatTemplate(Path("serve/chat_template.jinja"))) print("PORT", serve(svc, port=0).server_address[1], flush=True) time.sleep(600) ``` `overflow_run.sh`: ```sh #!/bin/sh # usage, from the repo root: sh overflow_run.sh strata|anthropic|both LOG=$(mktemp); PYTHONPATH=. PYTHONDONTWRITEBYTECODE=1 python overflow_mock.py "$1" 25000 > "$LOG" 2>&1 & SRV=$!; sleep 3 export ANTHROPIC_BASE_URL=http://127.0.0.1:$(sed -n 's/^PORT //p' "$LOG") ANTHROPIC_API_KEY=x export CLAUDE_CONFIG_DIR=$(mktemp -d) CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 DISABLE_AUTOUPDATER=1 cd "$(mktemp -d)"; SID=$(python -c 'import uuid; print(uuid.uuid4())') turn() { # $1 = characters, $2 = --session-id or --resume P=$(python -c "print(('lorem ipsum dolor sit amet ' * 1000)[:$1])"); B=$(grep -c '^REQUEST' "$LOG") claude -p "$P" "$2" "$SID" --model claude-sonnet-5-5 --tools "" --output-format json < /dev/null \ | python -c "import json,sys; j=json.load(sys.stdin); print(j['terminal_reason'], '|', str(j['result'])[:70], end=' | ')" echo "POSTs: $(( $(grep -c '^REQUEST' "$LOG") - B ))" } turn 1500 --session-id; turn 1500 --resume; turn 1500 --resume turn 16000 --resume # the prompt no longer fits turn 200 --resume # a short next turn kill "$SRV" ``` I ran these inside `unshare -rn` with only the loopback interface up, so that nothing could reach the real API, and with the mock file kept outside the repo and its path passed in. The output is under Logs. ### Reproduction status Reproduced locally With the mock engine only (`MockEngine` in `serve/server.py`). Not reproduced on a real engine or GPU. What I say about the Claude Code bundle's code is unconfirmed static analysis; the table above is what I saw it do. ### Strata version Git commit c62d5e3a (0.2.9, main). Claude Code 2.1.316. ### Graphics card, memory and system None used (mock engine). Linux 7.2.9, x86-64. ### Model, size and settings `MockEngine` with `ByteTokenizer`, context 25000 (`max_context`), default `fit_max_tokens`. Claude Code run with `--model claude-sonnet-5-5 --tools ""`, a name Strata ignores. ### Logs ``` $ sh overflow_run.sh strata completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 1 api_error | API Error: 400 request exceeds the context window: prompt (27442 token | POSTs: 3 api_error | API Error: 400 request exceeds the context window: prompt (27643 token | POSTs: 3 $ sh overflow_run.sh anthropic completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 3 completed | <summary>short summary</summary> | POSTs: 1 $ sh overflow_run.sh both completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 1 completed | <summary>short summary</summary> | POSTs: 3 completed | <summary>short summary</summary> | POSTs: 1 ``` The three POSTs of the control's overflow turn, from a server-side request log in an equivalent run: ``` messages=9 400 prompt is too long: 27443 tokens > 25000 maximum messages=7 200 prompt 17741 tokens messages=6 200 prompt 24053 tokens ``` *Written with an AI agent (Claude Code), which also ran the steps above.* 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01W53iURzvDQMjnYemag8uvv
Author
Owner

@gdevenyi commented on GitHub (Nov 3, 2026):

Fixed on main by 24739780: on /v1/messages an overflow now starts with Anthropic's own wording and keeps Strata's sentence after it. Thank you. I have not rerun the reproduction steps against it.

<!-- gh-comment-id:6595577115 --> @gdevenyi commented on GitHub (Nov 3, 2026): Fixed on `main` by 24739780: on `/v1/messages` an overflow now starts with Anthropic's own wording and keeps Strata's sentence after it. Thank you. I have not rerun the reproduction steps against it.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#2219
No description provided.