Skip to content

fix(llm): stop calling a shared KV-cache collision "conversation too long" - #5322

Merged
kovtcharov-amd merged 33 commits into
amd:mainfrom
kovtcharov:fix/llm-kv-cache-collision
Oct 19, 2026
Merged

kovtcharov-amd merged 33 commits into
amd:mainfrom
kovtcharov:fix/llm-kv-cache-collision

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5321, which is merged in. Review only the commits that aren't in #5321.

Depends on #5336 for the complete fix. The Agent UI auto-title still posts outside the model lease on main, so it can still collide with a turn. #5336 moves titles onto the side slot under the lease. Until #5336 lands, this PR retries such a collision and stops misreporting it, but the auto-title can still cause one.

Users were told "This conversation got too long… Start a fresh task" when their conversation wasn't long at all. With --kv-unified, two requests on one model share a single KV pool. If they outgrow it together, llama.cpp fails both with "Context size has been exceeded." GAIA treated that as an overflow: it didn't retry, the agent trimmed history, and the user saw the fresh-task advice. Now that error is recognised as a collision. The client retries it under its normal bounded policy, and if it still fails, the user is told the likely cause and to send the message again. A real overflow ("the request exceeds the available context size") is unchanged. Text completions, which RAG uses, now take the same per-model lease as chat, so they no longer run alongside a turn.

Reproduced by tests/unit/test_lemonade_kv_cache_shared.py; fails on main, passes here. On main, 11 of its 12 tests fail on behaviour (the 12th checks that a real overflow is still an overflow). On main the collision classifies as LemonadeContextOverflowError with "Start a fresh task", and a chat that hits it fails after one request. Here it succeeds on the second request.

Test plan

  • pytest tests/unit/test_lemonade_kv_cache_shared.py tests/unit/test_lemonade_chat_slots.py
  • Classification, retry, chat-helper and agent-retry suites: 619 pass.
  • python util/lint.py --black --isort --flake8 --pylint is clean.
🔍 Technical details
  • KV_CACHE_SHARED_PHRASES are moved out of CONTEXT_OVERFLOW_PHRASES. is_kv_cache_shared_error() is new, and classify_http_failure returns "KV cache shared with another request" for these errors.
  • LemonadeKVCacheSharedError (retryable) is checked before the overflow branch in both _classify_lemonade_response and classify_lemonade_exception.
  • test_an_exhausted_kv_pool_is_a_context_overflow encoded the old misdiagnosis. It is inverted here.
  • llama.cpp emits this text only when a decode can't find a free KV cell, and it sends it to every active slot. A single request that fills its own slot stops with finish_reason=length, and one that doesn't fit at all gets "exceeds the available context size".
  • The Agent UI auto-title, which posted outside the lease, moves onto the side slot under the lease in fix(ui): never take a model from under another chat or app #5336.
  • A collision after output has started is surfaced rather than replayed, and is still marked transient (test_a_collision_after_output_is_not_replayed).
  • Categories to watch: error_recovery, context_retention, memory, rag_quality.

A Lemonade that accepts connections but is busy loading another app's model
froze GAIA: status probes used the 900 s generation timeout under the
manager's class-wide lock, so every agent construction in the process
waited up to 15 minutes, and every chat call re-read /health and /models
with that timeout while holding the model lease. Time spent queued behind
someone else's load also counted against the 120 s retry budget, so a
request that failed after waiting out a 30B cold load got no retry at all.

- Status probes use short (connect, read) timeouts; a server that accepts
  and stays silent raises LemonadeUnresponsiveError and reads as busy, not
  down. ensure_ready, initialize() and auto_start report it and never start
  or take over a busy server.
- A request that finds the server busy waits for it, logged and on stderr,
  bounded by GAIA_LLM_LOAD_WAIT (600 s), then fails naming that setting.
- A /health probe that shows the model resident is trusted for 10 s; any
  load, unload or failed request drops it. The residency check skips /models.
- The retrier asks the server what it is loading after a transient failure:
  time behind a reported load is kept out of the retry deadline and bounded
  by GAIA_LLM_LOAD_WAIT instead, with a retry notice. Cloud requests never
  wait on a local load.
…long"

With --kv-unified, two requests on one model share a single KV pool. When
they outgrow it together, llama.cpp fails both with "Context size has been
exceeded." GAIA read that as a context overflow and told the user to "Start
a fresh task", though neither conversation was too long and the same request
fits once the other one ends.

- "Context size has been exceeded" and "failed to find free space in the KV
  cache" are a KV-cache collision, not an overflow. The client retries them
  under its normal bounded policy, and the user sees
  LemonadeKVCacheSharedError's message rather than the fresh-task advice.
- "The request exceeds the available context size" stays a real overflow.
- Text completions (used by RAG) take the same per-model lease as chat, so
  they no longer run beside a turn on the shared pool.
@github-actions github-actions Bot added llm LLM backend changes tests Test changes performance Performance-critical changes labels Oct 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve

Users were being told their conversation was too long and to start a fresh task when the real cause was two requests briefly sharing the model's memory. This PR treats that error as a temporary collision: GAIA retries it, and if it still fails, tells the user to send the message again. Real context overflows behave as before. Text completions, which RAG uses, now wait their turn like chat does, so they can't cause the collision in the first place. I found no blocking issues. I reviewed only the last commit, as the description asks.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change is in the LLM client's error classification and request serialization, and a real KV-pool collision needs two concurrent requests against a live --kv-unified llama.cpp backend, which this runner doesn't have. The verdict rests on static review plus the PR's own unit reproduction. I couldn't run that reproduction here because pytest isn't installed on this runner. The PR names the eval categories to watch on the next RC (error_recovery, context_retention, memory, rag_quality).

🔍 Technical details

Issues found

None blocking.

  • 🟢 A collision in the middle of a stream is still not replayed, which is correct, but untested. _stream_surviving_gaia_lemonade_stop refuses to retry once a chunk has been yielded. A KV collision that arrives mid-stream as an openai.APIError is now classified retryable by classify_exception, but the agent loop sees it outside the client retry and handles it through _transient_model_failure (agents/base/agent.py:7387), which no longer treats it as an overflow. A small test asserting that a mid-stream "Context size has been exceeded" event isn't replayed client-side would pin that boundary. This is optional.

Things I checked that hold up

  • No self-deadlock from the new completions lease. _local_request_lock is an RLock, and model_lease folds a nested same-model lease into a no-op (daemon/broker_client.py:~428). A completion issued inside an outer chat lease on the same thread won't block on itself.
  • Classification order is consistent at every entry point. The KV phrases are checked before the overflow phrases in _classify_lemonade_response, classify_lemonade_exception and classify_http_failure. A body that carries llama.cpp's exceed_context_size type alongside the collision message still lands on the collision branch.
  • The streaming-completions wrapper matches chat streaming. It holds the lease for the whole generator and calls _forget_resident on any exit, including GeneratorExit.
  • The inverted test encodes the new contract. test_an_exhausted_kv_pool_is_not_a_context_overflow replaces the test that asserted the old misdiagnosis, rather than sitting alongside it.

Strengths

  • The new comment on KV_CACHE_SHARED_PHRASES says exactly why these phrases aren't overflows (a full single slot stops with finish_reason=length), so it stays correct as the code moves.
  • LemonadeKVCacheSharedError.user_message gives the user a concrete next step ("send your message again"), and the retry stays inside the existing bounded policy. There's no new hidden retry loop.
  • test_lemonade_kv_cache_shared.py reproduces the bug end to end: it fails on main and passes here.

GAIA_LLM_RETRY_ATTEMPTS=1 promised no retries, but a request that failed
while Lemonade reported a model load was still waited for and retried. The
load wait now applies only while attempts remain. GAIA_LLM_LOAD_WAIT=0 gives
up at once, and the fail-fast recipe sets it.

- Docs: GAIA_LLM_LOAD_WAIT in the retry table, the deadline row no longer
  claims to cover a load wait, and a short section on a busy shared server.
- The read-timeout message no longer guesses that another app is loading.
- The busy-server tests use short probes (about 20 s less suite time).
Follow-ups from an independent review of the busy-server handling.

- The per-process residency cache is gone. Another app can evict the model
  and Lemonade can reload it at its own 32K default inside any trust window,
  and nothing short of a probe sees that (amd#1030). Every request now costs one
  short /health probe and no /models read.
- Only an LLM load excuses a request from the retry deadline. Another app
  loading a speech or embedding model, or downloading one, no longer makes a
  request wait.
- Stop ends both waits within half a second, including the busy-server wait
  before the first attempt (StreamCancelledError).
- The busy-server wait reports through the retry notice, not print().
- Only an unanswered status GET is labelled "busy". A /load or other POST
  that times out keeps the plain request error.
- The load-wait tests import cleanly on main, so they fail on behaviour.
The collision message no longer claims "your conversation is not too long";
that was never verified against a live overflow, so it now says the likely
cause and what to do if it keeps happening. Removes the two residency-cache
calls left in the text-completion paths after merging the cache removal.
@github-actions github-actions Bot added the documentation Documentation changes label Oct 18, 2026
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Follow-ups, including a few from an independent review:

  • Mid-stream collision: added the test you suggested. A collision after output is surfaced rather than replayed, and it's still marked transient so the agent can retry the step.
  • Softer message: the user text no longer says "your conversation is not too long", because that was never checked against a live overflow. It now gives the likely cause and says what to do if it keeps happening.
  • Auto-title outside the lease: fix(ui): never take a model from under another chat or app #5336 (Agent UI backend) moves titles onto the side slot under the same lease. That file belongs to that PR, so I haven't edited it here.
  • Merged fix(llm): wait for a busy shared Lemonade instead of hanging or failing #5321's latest commits (attempt cap, no residency cache), so the defects this branch inherited from fix(llm): wait for a busy shared Lemonade instead of hanging or failing #5321 are fixed here too.
  • Tests fail on behaviour on main: the new names are read inside each test, so on main the tests fail on behaviour rather than at import (11 of 12 fail; the 12th checks that a real overflow is still an overflow).

The red Linux unit check is the same wall-clock flake as on #5321, test_sse_handler.py::test_huge_envelope_token_by_token_is_not_quadratic. It's tracked in #5325.

Each probe during a wait used the full 5 s read timeout, and a silent server
spends all of it, so Stop could go unseen for 5–8 s against the half second
the docstring promised. A probe made while waiting now uses a 1 s connect
and read, and Stop is checked again right after it, so the bound is about
1.5 s. The docstring and the configuration docs say so. Tested against a
real socket that accepts and never answers.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

The red Dependency Review, label and Test GAIA CLI on Windows (Full Integration) checks aren't caused by this change:

  • Dependency Review: "Dependency review is not supported on this repository". The repo's dependency graph is turned off.
  • label and the Windows CLI integration job: "API rate limit exceeded for installation". actions/labeler and setup-ffmpeg hit the GitHub API limit.

The 1 s probe used during a wait treated any server slower than a second as
"not answering", so a Lemonade answering /health in 2 s kept a request
waiting until GAIA_LLM_LOAD_WAIT ran out, and the load-state probe turned
transient slowness into a load wait. Probes during a wait now get the full
PROBE_TIMEOUT and run on a worker thread, so Stop is seen every half second
while one is blocked. That holds for the busy wait, the get_status after it,
and the retrier's load probe.

The Stop tests now press Stop after the first sleep, while a probe is
blocked on a real silent socket, so a probe without the Stop check fails
them.
@kovtcharov

Copy link
Copy Markdown
Contributor Author

Merged #5321's round-3 fix (slow-but-alive server, Stop during a stalled probe). This PR has no changes of its own this round.

kovtcharov and others added 6 commits October 18, 2026 10:34
A Lemonade that accepts connections but is busy loading another app's model
froze GAIA: status probes used the 900 s generation timeout under the
manager's class-wide lock, so every agent construction in the process
waited up to 15 minutes, and every chat call re-read /health and /models
with that timeout while holding the model lease. Time spent queued behind
someone else's load also counted against the 120 s retry budget, so a
request that failed after waiting out a 30B cold load got no retry at all.

- Status probes use short (connect, read) timeouts; a server that accepts
  and stays silent raises LemonadeUnresponsiveError and reads as busy, not
  down. ensure_ready, initialize() and auto_start report it and never start
  or take over a busy server.
- A request that finds the server busy waits for it, logged and on stderr,
  bounded by GAIA_LLM_LOAD_WAIT (600 s), then fails naming that setting.
- A /health probe that shows the model resident is trusted for 10 s; any
  load, unload or failed request drops it. The residency check skips /models.
- The retrier asks the server what it is loading after a transient failure:
  time behind a reported load is kept out of the retry deadline and bounded
  by GAIA_LLM_LOAD_WAIT instead, with a retry notice. Cloud requests never
  wait on a local load.
GAIA_LLM_RETRY_ATTEMPTS=1 promised no retries, but a request that failed
while Lemonade reported a model load was still waited for and retried. The
load wait now applies only while attempts remain. GAIA_LLM_LOAD_WAIT=0 gives
up at once, and the fail-fast recipe sets it.

- Docs: GAIA_LLM_LOAD_WAIT in the retry table, the deadline row no longer
  claims to cover a load wait, and a short section on a busy shared server.
- The read-timeout message no longer guesses that another app is loading.
- The busy-server tests use short probes (about 20 s less suite time).
Follow-ups from an independent review of the busy-server handling.

- The per-process residency cache is gone. Another app can evict the model
  and Lemonade can reload it at its own 32K default inside any trust window,
  and nothing short of a probe sees that (amd#1030). Every request now costs one
  short /health probe and no /models read.
- Only an LLM load excuses a request from the retry deadline. Another app
  loading a speech or embedding model, or downloading one, no longer makes a
  request wait.
- Stop ends both waits within half a second, including the busy-server wait
  before the first attempt (StreamCancelledError).
- The busy-server wait reports through the retry notice, not print().
- Only an unanswered status GET is labelled "busy". A /load or other POST
  that times out keeps the plain request error.
- The load-wait tests import cleanly on main, so they fail on behaviour.
kovtcharov and others added 7 commits October 18, 2026 23:21
Each probe during a wait used the full 5 s read timeout, and a silent server
spends all of it, so Stop could go unseen for 5–8 s against the half second
the docstring promised. A probe made while waiting now uses a 1 s connect
and read, and Stop is checked again right after it, so the bound is about
1.5 s. The docstring and the configuration docs say so. Tested against a
real socket that accepts and never answers.
The 1 s probe used during a wait treated any server slower than a second as
"not answering", so a Lemonade answering /health in 2 s kept a request
waiting until GAIA_LLM_LOAD_WAIT ran out, and the load-state probe turned
transient slowness into a load wait. Probes during a wait now get the full
PROBE_TIMEOUT and run on a worker thread, so Stop is seen every half second
while one is blocked. That holds for the busy wait, the get_status after it,
and the retrier's load probe.

The Stop tests now press Stop after the first sleep, while a probe is
blocked on a real silent socket, so a probe without the Stop check fails
them.
# Conflicts:
#	src/gaia/llm/lemonade_client.py
A cloud model never waits on a local load, but its agent construction
still treated a silent server as down and failed after the 5 s probe.
It now reports the server busy and continues, as the local-model path
does; a server with nothing listening still fails.
…f3-5322

# Conflicts:
#	src/gaia/llm/lemonade_client.py
#	tests/unit/test_lemonade_shared_server.py
The install check swallowed the busy signal and, for any host other than
localhost, reported the server as not reachable before initialize() could
say it was busy. It now counts a busy server as available; a remote
server with nothing listening still is not.
# Conflicts:
#	src/gaia/llm/lemonade_client.py
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 19, 2026
…ng (amd#5321)

When another app was loading a model on the shared Lemonade, GAIA froze
or failed. A server that accepted connections but stayed silent mid-load
blocked every agent construction in the process for up to 15 minutes,
because status checks used the 900 s generation timeout under a
class-wide lock. Every chat call also re-read `/health` and `/models`
with that timeout while holding the model lease. And a request that
failed after waiting out someone else's 30B cold load got no retry at
all, because the time it spent queued had already used up the 120 s
retry budget.

Now a busy server reads as **busy**, not down:
- Agent construction comes back within seconds, and GAIA never starts or
takes over a busy server.
- A request waits for a busy server and says so through the retry
notice. It honours Stop within half a second and gives up after
`GAIA_LLM_LOAD_WAIT` (600 s) with an error that names that setting.
- Time spent behind another app's LLM load no longer counts against the
retry budget. Attempts still do: `GAIA_LLM_RETRY_ATTEMPTS=1` still means
no retries.

Reproduced by `tests/unit/test_lemonade_shared_server.py` and
`tests/unit/test_retry_load_wait.py`; they fail on main and pass here.
On main:
- Two agents built against a stalled server are both still blocked after
30 s.
- `get_status()` hangs past 90 s.
- A request queued 150 s behind a load fails after one attempt.
- `test_retry_load_wait.py`: all 23 fail.

## Test plan
- [x] `pytest tests/unit/test_lemonade_shared_server.py
tests/unit/test_retry_load_wait.py` passes, using loopback fakes only.
- [x] The 165 unit files that touch the LLM client, retry or manager,
run with amd#5322 on top: 5,094 pass. The 17 failures are the 16 that fail
on clean main plus `test_verification_scope`, a flake listed in amd#5325.
- [x] `python util/lint.py --black --isort --flake8 --pylint` is clean.
- [ ] Live check on hardware: load a large model from one session and
send a chat from another.

<details>
<summary>🔍 Technical details</summary>

- Probe timeouts are `PROBE_TIMEOUT` (3.05, 5), `SYSTEM_INFO_TIMEOUT`
(3.05, 15) and `CATALOG_TIMEOUT` (3.05, 30).
- A status GET that times out raises `LemonadeUnresponsiveError`, which
keeps the `Request failed:` prefix existing callers match on.
`LemonadeStatus.busy` carries the same state. A POST that times out
stays a plain `LemonadeClientError`.
- `ensure_ready`, `initialize()`,
`create_lemonade_client(auto_start=True)` and `launch_server` all treat
busy as "up". Before this, a failed probe could reach `_stop_listeners`
and kill a server in the middle of another app's load.
- Every request makes one `get_status(include_catalog=False)` probe.
There is no residency cache: another app can evict the model, and
Lemonade can reload it at its 32K default, inside any trust window
(amd#1030).
- `ModelCallRetrier` takes a `server_loading` probe. Only `type ==
"llm"` entries with status `loading`, `evicting`, `pending` or `queued`
count as a load; downloads don't. The probe is attached only for local
models, it is not consulted once attempts run out, the wait is measured
on the wall clock, and Stop is checked every 0.5 s.
- `_model_retrier` and `_call_with_retry` take a `model` argument. amd#5282
edits the same signatures, so a mechanical merge conflict is expected.
- Error classification is LLM-affecting, so watch `error_recovery`,
`context_retention`, `rag_quality` and `memory` on the next RC. No eval
was run here: one was already running on the shared machine.
- The `/health` status names come from the Lemonade 2026.40 binary; they
weren't observed during a live load.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit f1b3b52 Oct 19, 2026
48 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the fix/llm-kv-cache-collision branch October 19, 2026 14:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes llm LLM backend changes performance Performance-critical changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants