Skip to content

fix: harden context window — self-heal on upstream overflow + reserve output headroom - #172

Merged
ranxianglei merged 4 commits into
masterfrom
2026-08-18_overflow-window-selfheal
Aug 20, 2026
Merged

ranxianglei merged 4 commits into
masterfrom
2026-08-18_overflow-window-selfheal

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Aug 18, 2026 •

Copy link
Copy Markdown
Owner

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):

  1. 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
    — lastInputTokens stayed frozen at the pre-overflow value,
    so a non-compliant model + nothing truncatable = stuck 400-ing every turn.

  2. 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 > window overflows before the nudge fires — the most
    common "context blew up" cause.

Fix (two complementary layers)

Reactive (self-heal):

  • inspectContextOverflow(status, body) — pure detector for context-overflow
    400/413 (provider phrasings); deliberately does not match Bedrock's
    "too many tokens" throttle (a 429). parseOverflowWindow learns the real
    window when present (> N maximum / maximum context length is N / comma
    grouped).
  • On an overflow 400, forward() persists the real window to
    session.metadata.learnedContextLimit and arms an emergency shrink
    (lastInputTokens = max(current, window) → next turn's usage ≥100% → kernel
    emergency nudge + tool-result truncate fire). The 400 is still passed through
    verbatim (no client behavior change).
  • Next turn, handle() re-centers the kernel on the learned window (spread
    into 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 this
    turn) 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 degenerate max_tokens >= window is left to the
    self-heal.

Together: prevent the context+output overflow (headroom) and recover
from any overflow that still happens (self-heal) — no more stall.

Verification

  • npm run typecheck clean.
  • Full suite 469/469 pass (453 baseline + 11 inspectContextOverflow/
    parseOverflowWindow unit + 4 reserveOutputHeadroom unit + 1 overflow
    e2e).
  • Overflow e2e: mock upstream returns a context-overflow 400 (with the real
    window in the body) then a 200 → asserts the 400 passes through verbatim,
    the real window is learned into metadata.learnedContextLimit, the emergency
    shrink is armed (lastInputTokens >= window), and the next request
    recovers
    (self-healed window; the real usage report then overwrites the
    armed value).
  • Output-headroom verified end-to-end: with a 100k window + 40k max_tokens
    the kernel sees usage = 50000/60000 (the reserved 60k window), not
    50000/100000.

Notes

  • learnedContextLimit is a stable field — effectiveContextLimit is
    re-resolved every turn (plugin mode) and would be overwritten.
  • No package.json version bump (repo convention: separate release PR).

@ranxianglei ranxianglei changed the title fix: self-heal context window on upstream overflow + arm emergency shrink fix: harden context window — self-heal on upstream overflow + reserve output headroom Aug 18, 2026
Sisyphus and others added 4 commits August 19, 2026 23:18
…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
ranxianglei force-pushed the 2026-08-18_overflow-window-selfheal branch from f95108f to 7aa4cca Compare August 19, 2026 15:23
@ranxianglei
ranxianglei merged commit f7e35cf into master Aug 20, 2026
9 of 10 checks passed
@ranxianglei ranxianglei mentioned this pull request Aug 21, 2026
@ranxianglei
ranxianglei deleted the 2026-08-18_overflow-window-selfheal branch October 15, 2026 05:31
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant