Repository navigation
fix: harden context window — self-heal on upstream overflow + reserve output headroom - #172
Merged
Merged
Conversation
…rink
When the configured context window is wrong — most commonly the 200k
fallback for an unknown model on a private relay (the MITM case) — the
nudge/truncate bands sit far above the real window and the upstream 400s on
every turn. The proxy previously passed that 400 through verbatim with no
recovery, so a non-compliant model left the session permanently stuck
400-ing (the context blows up and the session stalls).
forward()'s non-2xx path now buffers the (small) error body and inspects it
for a context-overflow (inspectContextOverflow in src/util.ts — a pure,
tested helper: only 400/413 with a recognized context-too-long marker counts,
and it deliberately does NOT match Bedrock's "too many tokens" throttle
phrase, a 429 the client should back off on). On detection it:
- learns the real window from the error body (OpenAI "maximum context
length is N", Anthropic "X tokens > Y maximum", ...) and persists it to
session.metadata.learnedContextLimit (a STABLE field — effectiveContextLimit
is re-resolved every turn and would be overwritten);
- handle() then self-heals: if the learned window is smaller than what was
resolved this turn, it re-centers reqConfig.modelContextLimit on it (spread
into a new object — never mutates the shared global config), so the
nudge/truncate bands drop below the real limit;
- arms an emergency shrink by raising lastInputTokens to the window (a lower
bound — it overflowed, so the context is at least that big), so the next
turn's usage is >=100% and the kernel's emergency nudge + tool-result
truncate fire;
- still passes the error through verbatim (no client-visible change).
Tests: tests/context-overflow.test.ts (11 unit cases) +
tests/e2e-overflow-selfheal.test.ts (overflow -> learn+arm+passthrough ->
recover, real usage report overwrites the armed value).
The kernel's nudge/truncate bands are a fraction of modelContextLimit, but none of the layers reserved room for the model's OUTPUT. On a small window (e.g. 100k) with a large max_tokens, context + output can exceed the window and overflow before the nudge fires — the most common 'context blew up' cause on a 100k window. Reserve the request's exact max_tokens (the output budget for THIS turn) from the window when handing it to the kernel, so the bands sit below (window - maxOutput). Pure reserveOutputHeadroom() + per-request wiring in handle(); unit-tested (4 cases). Complements the self-heal (reactive recovery) with a preventive reservation — together they prevent + recover from the context+output overflow.
…p error-body read Review fixes: - Per-model learnedContextLimits: the learned window is keyed by the model that overflowed. Previously a session-level scalar capped the WHOLE session — after /model-switching to a bigger model mid- conversation, the stale smaller window forced premature compression for the rest of the session. handle() now looks up the current request's model; the legacy scalar remains as a read fallback (persisted sessions) and is still written when the model is unknown. - inspectContextOverflow: recognize the newer Responses-API phrasing 'exceeds the model's maximum context size of N' (patterns only covered 'context length') — self-heal now fires for /responses too. - readStreamToBuffer: cap retained bytes at 1 MiB (stream still drained) so a huge 400 body from a misbehaving upstream can't spike memory. Tests: new unit case for the size phrasing; e2e now asserts per-model keying (no legacy scalar) and adds a third request on a different model asserting no cross-model crosstalk.
…otocol-aware headroom Review fixes for the overflow self-heal: 1. markDirty on the error path: forward()'s non-2xx branch learns the window (metadata.learnedContextLimits) and arms the emergency (stats.lastInputTokens) but returns before forward()'s trailing markDirty — both mutations lived only in memory and were lost on restart, so the next overflow had to be re-learned. Schedule the save in the branch that mutates. Pinned by a scheduleSave spy in the e2e (on-disk assertions can't prove it: the prepare phase's debounced save serializes the live session after the mutation anyway). 2. Strip upstream content-length/transfer-encoding unconditionally on the error path: when readStreamToBuffer breaks the body (errBody null) the response ends with no body, and a content-length claiming bytes that never arrive leaves the client on a broken response. 3. Protocol-aware output headroom: Anthropic's Messages API enforces the input limit independently of max_tokens (separate output budget), so reserving maxOutput from the window shifted every nudge/truncate band down by maxOutput on every Anthropic session with no safety gain. OpenAI-family APIs count output against the window — reserve there (and for unknown protocols, conservatively). New shouldReserveOutputHeadroom() + unit tests.
ranxianglei
force-pushed
the
2026-08-18_overflow-window-selfheal
branch
from
August 19, 2026 15:23
f95108f to
7aa4cca
Compare
Merged
This was referenced Aug 30, 2026
Closed
This was referenced Sep 19, 2026
cskwork
pushed a commit
to cskwork/billion-context
that referenced
this pull request
Oct 21, 2026
…anglei#374) + refresh lockfile 0.0.47 is the first stable containing acp-kernel PR ranxianglei#172 (merge a559247): - renameWithRetry: exponential backoff on EPERM/EBUSY/EACCES (6 attempts, 50ms base, 1600ms cap) - final write failure spills to <name>.fb.json instead of unlink+drop (one slot per id, discovered by loadAll, reconciled by savedAt) - recordFailure: error log rate-limited to first + power-of-two counts (~log2(N) lines per long lock instead of one per write) Verified against the published 0.0.47 tarball (dist/persist) and the rebuilt billion-context dist (spill code inlined). No runtime deps added. Pre-flight: typecheck clean, 858/858 tests pass, build OK.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
For a small context window (e.g. 100k), two concrete mechanisms let the
context blow up (爆掉) and then stall (a permanent 400-loop, not an
infinite hang):
Window misdetection + no recovery. For an unknown model on a private
relay (the MITM case) the resolved window falls back to 200k, so the
nudge/truncate bands sit at 150k/190k — but the upstream 400s at 100k.
Every mechanism fires ~2× too late, silently. When the overflow 400 came
back it was passed through verbatim with no detection, no recovery, no
state reset —
lastInputTokensstayed frozen at the pre-overflow value,so a non-compliant model + nothing truncatable = stuck 400-ing every turn.
No output headroom reserved. The kernel's nudge/truncate bands are a
fraction of the window, but none of the layers reserved room for the
model's output. On a 100k window with a large
max_tokens,context + output > windowoverflows before the nudge fires — the mostcommon "context blew up" cause.
Fix (two complementary layers)
Reactive (self-heal):
inspectContextOverflow(status, body)— pure detector for context-overflow400/413 (provider phrasings); deliberately does not match Bedrock's
"too many tokens" throttle (a 429).
parseOverflowWindowlearns the realwindow when present (
> N maximum/maximum context length is N/ commagrouped).
forward()persists the real window tosession.metadata.learnedContextLimitand arms an emergency shrink(
lastInputTokens = max(current, window)→ next turn's usage ≥100% → kernelemergency nudge + tool-result truncate fire). The 400 is still passed through
verbatim (no client behavior change).
handle()re-centers the kernel on the learned window (spreadinto a new object — the shared global config is never mutated), so the bands
sit below the real limit instead of above it.
Preventive (output headroom):
reserveOutputHeadroom(window, maxOutput)— pure. Per-request,handle()reserves the request's exact
max_tokens(the output budget for thisturn) from the window before handing it to the kernel, so the bands sit
below
window − maxOutput. Only reserves when it leaves a usable window(
maxOutput < window); a degeneratemax_tokens >= windowis left to theself-heal.
Together: prevent the context+output overflow (headroom) and recover
from any overflow that still happens (self-heal) — no more stall.
Verification
npm run typecheckclean.inspectContextOverflow/parseOverflowWindowunit + 4reserveOutputHeadroomunit + 1 overflowe2e).
window in the body) then a 200 → asserts the 400 passes through verbatim,
the real window is learned into
metadata.learnedContextLimit, the emergencyshrink is armed (
lastInputTokens >= window), and the next requestrecovers (self-healed window; the real usage report then overwrites the
armed value).
max_tokensthe kernel sees
usage = 50000/60000(the reserved 60k window), not50000/100000.Notes
learnedContextLimitis a stable field —effectiveContextLimitisre-resolved every turn (plugin mode) and would be overwritten.
package.jsonversion bump (repo convention: separate release PR).