Skip to content

fix(llm): size a context overflow against the machine's own device profile - #4095

Merged
itomek merged 8 commits into
mainfrom
issue-2884
Sep 22, 2026
Merged

itomek merged 8 commits into
mainfrom
issue-2884

Conversation

@itomek

@itomek itomek commented Sep 22, 2026 •

Copy link
Copy Markdown
Collaborator

On a Ryzen AI (NPU) machine, running out of context was reported as if the model had been loaded wrong. The chat UI announced "Model reloaded — retrying...", replayed the same oversized turn, and only then gave up; on the plain gaia chat "<message>" command line the user got a bare ❌ Error: Max length reached! with no cause and no next step. Nothing was wrong with the load — GAIA was measuring the overflow against the GPU context window (64K) on a machine whose real ceiling is 32K. Now the comparison uses whatever window the machine's own device profile expects, so an NPU overflow says what happened and what to do about it, on both surfaces.

Closes #2884.

🔍 Technical details

Three defects, all the same root cause — a threshold that assumed one device:

  1. Both context-overflow classifiers (_classify_lemonade_response, _classify_chat_exception) compared the reported n_ctx against a hardcoded 65536. On NPU a correct load is NPU_CTX_SIZE (32768), so 0 < n_ctx < 65536 was unconditionally true and every real overflow was marked retryable. The fix derives the threshold from the active device profile via a new active_profile_ctx_size() in llm/lemonade_client.py — not by hardcoding 32768 in place, which would break GPU.
  2. Agent._extract_lemonade_user_message imported the classifier from gaia.ui._chat_helpers inside a try/except Exception: return None. gaia.ui needs fastapi, so on any install without the [ui] extras the import failed silently and every Lemonade error fell back to generic "try again in a moment" copy. That is how the raw backend string reached the CLI.
  3. GaiaCliClient.send_message — the handler gaia prompt routes to — printed
    str(exc) verbatim. The typed sentence is now the headline and the backend
    string is kept underneath as a Details: line, so a connection failure still
    names the model, the URL and the server log.

Both classifiers call active_profile_ctx_size() through a _loaded_below_profile guard: they run inside except handlers, so an unreadable config is logged and the overflow left non-retryable rather than raising a GaiaConfigError that replaces the error the user actually hit.

The classifier moved to llm/providers/lemonade.py as classify_lemonade_exception, next to the error classes it returns; gaia.ui._chat_helpers._classify_chat_exception is now a re-export so existing callers and tests are unchanged.

Searched for other instances: git grep -n 65536 across the tree. Every other hit in src/ is an I/O chunk size, a UI picker option, a docstring example, the constant's own definition, or factory/harvest reporting ratios — none is a ctx expectation. agent.py's literal ladder (context size (4096|8192|16384) is a fast path only; all three values are below both profiles, so it is correct on both, and _is_loaded_ctx_too_small() — already device-aware from the first half of this issue — covers everything else.

Test plan

  • pytest tests/unit/test_ctx_overflow_device_profile_2884.py — 25 new tests, all green. They set default_device to npu/gpu/cpu through the real config file (no mocked accessor) and assert the retryable decision flips with the profile, not with a constant.
  • pytest tests/unit/test_lemonade_error_classification.py tests/unit/agents/ tests/unit/chat/ui/ tests/unit/test_cli_config.py tests/unit/test_cli_device_resolution.py tests/unit/test_lemonade_client_ctx_override.py tests/unit/test_base_agent_lemonade_api_key.py tests/unit/test_lemonade_ctx_ceiling.py — 1105 passed, 50 skipped / 1043 passed / 136 passed across the runs.
  • python util/lint.py --all — exit 0; black --check src/gaia tests 1065 unchanged, flake8 0, isort clean.
  • Not verified on real NPU hardware from this session — no Ryzen AI box was available. The NPU behaviour is exercised by pinning default_device=npu in the config, which is the same input the production code reads. A reviewer on NPU can confirm with a >32K turn: the error should name the context window and suggest a fresh task, with no "Model reloaded — retrying..." line.
Before / after on the plain CLI (from the new regression test)

Before — tests/unit/test_ctx_overflow_device_profile_2884.py captured stdout while the fix was absent:

❌ Error: request (67000 tokens) exceeds the available context size (32768 tokens)

After:

❌ Error: This conversation got too long for the model's context window. Start a fresh task to keep going.

On NPU, every real context overflow was labelled "the model was loaded at
the wrong context size", so the chat layer announced "Model reloaded —
retrying...", replayed the identical oversized turn, and only then surfaced
an error. Nothing was wrong with the load: both classifiers compared the
reported n_ctx against a hardcoded 65536, the GPU/CPU window, while a
correctly loaded NPU model sits at NPU_CTX_SIZE (32768) — so the comparison
was unconditionally true there.

The threshold now derives from the active device profile via a new
active_profile_ctx_size(), rather than swapping one hardcoded constant for
another. A corrupt config raises instead of guessing a device.

Part of #2884.
`gaia chat "<message>"` printed the backend's own string verbatim, so a
context overflow on NPU arrived as a bare "❌ Error: Max length reached!" —
no cause, no next step. The classifier that turns that into an actionable
message lived in gaia.ui, which needs fastapi, so the CLI could not reach it.

Moved it next to the error classes it returns (classify_lemonade_exception in
llm/providers/lemonade.py); gaia.ui keeps its existing name as a re-export.

Part of #2884.
The agent loop reached the error classifier through gaia.ui and swallowed the
ImportError, so on any install without the ui extras every Lemonade failure
fell back to "try again in a moment" instead of the real remediation — which
is how a context overflow reached the CLI as a bare backend string.

Points both call sites at the classifier's new in-core home and drops the
blanket except that hid the miss.

Part of #2884.
@itomek itomek added the ready_for_ci Run CI workflows on draft PR without requesting review label Sep 22, 2026
@github-actions github-actions Bot added llm LLM backend changes cli CLI changes tests Test changes performance Performance-critical changes agents labels Sep 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

Sizing the overflow threshold against the machine's own device profile is the right fix, and the NPU/GPU behaviour is well covered by the new tests. Two things should be sorted before merge.

A broken config file now crashes error handling instead of reporting the error. The new context-size lookup reads GAIA's config and raises loudly when that file is corrupt or unreadable — correct on its own, but the lookup runs inside the handlers that are already dealing with a failure (the CLI, the agent loop, the chat routes). The result is a raw traceback that replaces the error the user was actually hitting. The evidence run reproduced exactly this. Decide the unresolvable-profile case inside the classifier: log it and treat the overflow as not-retryable, so the user still gets the real message.

The plain-CLI half of the fix landed on a method nothing calls. gaia chat never reaches the chat helper that was changed — it goes through the agent, which is fixed by the other half of this PR. The CLI command that does reach the changed class is gaia prompt, and its error path was left printing the raw backend string. Apply the same one-line treatment there, or the "plain CLI" claim in the description only half holds.

One smaller thing: for a connection failure the new typed message is less useful than the string it replaced — the old text named the model, the server URL, the log file and gaia init; the new one just says to try again. Worth keeping the original detail alongside the typed sentence.

Real-world evidence

The evidence bundle exercised the real stack against a stand-in Lemonade backend returning a genuine exceed_context_size envelope, and it supports the core claim — the retry decision flips with the persisted device profile, and the CLI handler prints the remediation instead of the backend string:

-- default_device = npu --                            active_profile_ctx_size() -> 32768
  n_ctx=32768  exception->LemonadeContextOverflowError retryable=False | payload-> ... retryable=False
-- default_device = gpu --                            active_profile_ctx_size() -> 65536
  n_ctx=32768  exception->LemonadeContextOverflowError retryable=True  | payload-> ... retryable=True
   AFTER (this PR, HEAD):
❌ Error: This conversation got too long for the model's context window. Start a fresh task to keep going.
   BEFORE (base 158e2a71):
❌ Error: OpenAI BadRequestError: Error code: 400 - {'error': {'type': 'exceed_context_size', ... 'n_ctx': 32768}}

POST /api/chat/send returned 200 with a well-formed SSE answer on both profiles and no spurious "Model reloaded — retrying…" status. The same run is where the corrupt-config traceback above came from, so that finding is observed, not theoretical. The Agent UI screenshot is marked pending strix-halo lane (no inference on this runner) — fine for merge-time CI; the pixels are still owed.

🔍 Technical details

🟡 A GaiaConfigError escapes from inside every except handler (src/gaia/llm/providers/lemonade.py:361, :266)

active_profile_ctx_size() raises when ~/.gaia/config.json exists but is corrupt or unreadable. Both call sites sit in the overflow branch of a classifier that is only ever invoked while handling another exception:

  • src/gaia/cli.py:455 — inside except Exception as e:, so the ❌ Error: print never runs (verbatim traceback in evidence-bundle.md §Observed, test-runs/pr2884/12_corrupt_cli.txt).
  • src/gaia/agents/base/agent.py:4818 / :4836 — called from the agent loop's error branches (agent.py:6087, :6252); raising there loses the typed message and unwinds past the loop's recovery.
  • src/gaia/ui/_chat_helpers.py:1597, :1613, :1653, :2170, :2204, :2229 — same shape on the streaming and non-streaming chat routes.

Keeping active_profile_ctx_size() loud for its normal callers is right; the classifier just must not be the place it fires. Conservative branch (retryable=False) is also the correct one — it avoids claiming a reload that wouldn't have helped:

def _retryable_below_profile(n_ctx: int) -> bool:
    """Was the model loaded below the active profile's window?

    Classifiers run inside ``except`` blocks — a config failure raised here
    would replace the error the user actually hit, so it is logged and the
    overflow stays non-retryable.
    """
    from gaia.config import GaiaConfigError

    try:
        return 0 < n_ctx < active_profile_ctx_size()
    except GaiaConfigError as exc:
        logger.error("Cannot size the expected context window: %s", exc)
        return False

Then if _retryable_below_profile(n_ctx_reported): at :266 and if m and _retryable_below_profile(int(m.group(1))): at :361. A test for "corrupt config + overflow still yields the typed message" belongs next to test_active_profile_ctx_size_raises_actionably_on_corrupt_config.

🟡 gaia prompt still prints the raw backend string (src/gaia/cli.py:382)

GaiaCliClient.chat has no in-tree caller — async_main routes action == "chat" to ChatAgent (src/gaia/cli.py:552, :571), which gets the typed message via the agent.py fix. The GaiaCliClient path users do reach is prompt → send_message, whose handler is unchanged. evidence-bundle.md §2 confirms it still emitted the raw string in the run.

        except Exception as e:
            from gaia.llm.providers.lemonade import classify_lemonade_exception

            classified = classify_lemonade_exception(e)
            error_message = f"❌ Error: {classified.user_message if classified else str(e)}"
            self.log.error(error_message)
            print(error_message)
            yield error_message

🟢 The typed network message drops the diagnostics it replaced (src/gaia/cli.py:456)

Per evidence-bundle.md §2, connection-refused went from a string naming the model, base URL, ~/.cache/lemonade/server.log and gaia init to "try sending the message again". CLAUDE.md asks an actionable error to name where to look next; keeping the original as a detail line costs nothing:

            detail = f"\n   Details: {e}" if classified else ""
            print(f"❌ Error: {classified.user_message if classified else str(e)}{detail}")

Strengths

  • The threshold is derived from the profile rather than swapped for the other hardcoded constant, and active_profile_ctx_size() reuses the same GaiaConfig.load().default_device convention _is_loaded_ctx_too_small() already follows (agent.py:4766) — one story for "what ctx does this machine expect".
  • Moving the classifier next to the error classes it returns removes a real try/except ImportError: return None that silently degraded every Lemonade error on installs without the [ui] extras, and test_classifier_is_reachable_without_importing_the_ui_package pins it in a subprocess so the test module's own gaia.ui import can't mask a regression.
  • The new tests write the real config file rather than mocking the accessor, and assert the decision flips with the profile in both directions — that is what would have caught the original bug.

The corrupt-config test passed alone and failed in the full suite:
test_cli_config.py reloads gaia.config, rebinding GaiaConfigError to a new
class object, so the module-level import pytest.raises was matching against
had gone stale.
@itomek

itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Full-suite note: pytest tests/unit (13202 passed) ends with 29 failures on this machine. None come from this change — 24 of them fail identically when their files are run on their own in 6s (missing optional deps / no installed wheels / no network), and the 2 in test_chat_fix_contracts.py reproduce with this PR's test file removed from the run.

One failure was mine and is fixed in 4364b30: the corrupt-config test passed alone and failed in the full suite because test_cli_config.py reloads gaia.config, rebinding GaiaConfigError to a new class object that the module-level import no longer matched. It now resolves the class at call time.

@github-actions

Copy link
Copy Markdown
Contributor

The two 🟡 issues from the first review are still open in this push.

🟡 gaia prompt still prints the raw backend string. The fix landed on GaiaCliClient.chat, but the routing code at cli.py:554 confirms that action == "prompt" reaches client.prompt() → send_message, not GaiaCliClient.chat. send_message's except block at cli.py:382 still does str(e) verbatim. The new test (test_cli_chat_surfaces_the_typed_message_not_the_backend_string) exercises the unfired code path — GaiaCliClient.chat is never called by any action in the routing table.

🟡 A corrupt ~/.gaia/config.json still replaces the real error with a GaiaConfigError traceback. Both overflow callers — _classify_lemonade_response:265 and classify_lemonade_exception:361 — call active_profile_ctx_size() bare, with no GaiaConfigError guard. Both functions are called from inside except blocks (the cli handler at cli.py:456, the agent loop, the chat routes). The first review's suggestion — catch GaiaConfigError, log it, and fall back to retryable=False — wasn't applied. The new test at line 522 correctly asserts the function raises on corrupt config, but doesn't test that the callers survive it.

🔍 Technical details

send_message fix (src/gaia/cli.py:382):

        except Exception as e:
            from gaia.llm.providers.lemonade import classify_lemonade_exception
            classified = classify_lemonade_exception(e)
            error_message = f"❌ Error: {classified.user_message if classified else str(e)}"
            self.log.error(error_message)
            print(error_message)
            yield error_message

active_profile_ctx_size guard (src/gaia/llm/providers/lemonade.py:265 and :361):

from gaia.config import GaiaConfigError
try:
    threshold = active_profile_ctx_size()
except GaiaConfigError as exc:
    logger.error("Cannot size the expected context window: %s", exc)
    threshold = None

if threshold is not None and 0 < n_ctx_reported < threshold:
    err_instance.retryable = True

The existing test test_active_profile_ctx_size_raises_actionably_on_corrupt_config should be complemented by a test that exercises the classifier with a corrupt config and asserts the typed LemonadeContextOverflowError (not a GaiaConfigError) is returned.

Two review findings, both real.

The plain-CLI half of the fix landed on `GaiaCliClient.chat`, which has no
in-tree caller — `action == "chat"` routes to ChatAgent, and the
GaiaCliClient path users reach is `prompt` -> `send_message`, whose handler
still printed the raw backend string. Moved the typed-message treatment
there.

Both overflow classifiers called `active_profile_ctx_size()` bare. They run
inside `except` handlers, so a corrupt `~/.gaia/config.json` raised a
GaiaConfigError that replaced the error the user actually hit. The new
`_loaded_below_profile` guard logs it and leaves the overflow
non-retryable — it cannot promise a reload it cannot size.

Also keeps the backend detail as a `Details:` line under the typed
sentence, so a connection failure still names the server and the log file
it used to.
@itomek

itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Both 🟡 findings are fixed in c5f9547, and the 🟢 one too.

  • gaia prompt was the CLI path that actually reaches GaiaCliClient — confirmed, the earlier fix sat on a method with no in-tree caller. The typed message now lands on send_message.
  • A corrupt config no longer escapes from inside the handler. The overflow stays non-retryable rather than promising a reload it can't size, and the user still gets the real error.
  • The backend string is kept as a Details: line under the typed sentence, so a connection failure still names the model, the URL and the server log.

Branch is also merged up to current main (was 14 behind).

🔍 Evidence — executed at HEAD c5f9547

Driving the real GaiaCliClient.send_message (the gaia prompt route) with a genuine Lemonade exceed_context_size envelope:

--- The retry decision follows the machine's profile (model loaded at 32768) ---
  default_device = npu            LemonadeContextOverflowError  retryable=False
  default_device = gpu            LemonadeContextOverflowError  retryable=True
  default_device = corrupt config LemonadeContextOverflowError  retryable=False
    ERROR gaia.llm.providers.lemonade._loaded_below_profile | Cannot size the
    expected context window: ... Fix or delete <path>, or run `gaia config set
    default_device gpu`.

--- What `gaia prompt` prints on a context overflow (NPU) ---
[profile ctx] 32768
❌ Error: This conversation got too long for the model's context window. Start a fresh task to keep going.
   Details: Error code: 400 - {'error': {'type': 'exceed_context_size', ... 'n_ctx': 32768}}

--- Same, with a corrupt ~/.gaia/config.json ---
[profile ctx] unreadable: GaiaConfigError
❌ Error: This conversation got too long for the model's context window. Start a fresh task to keep going.
   Details: Error code: 400 - {'error': {'type': 'exceed_context_size', ... 'n_ctx': 32768}}

--- Connection refused: typed line, diagnostics kept underneath ---
[profile ctx] 65536
❌ Error: Couldn't reach the local LLM. It may be loading or briefly busy — try sending the message again.
   Details: Connection refused: model 'Gemma-4-E4B-it-GGUF' at http://localhost:8000 (see ~/.cache/lemonade/server.log; run `gaia init`)

How it was tested: real GaiaCliClient.send_message and the real classifiers, each in a clean subprocess with GAIA_CONFIG_FILE pointed at the profile under test, against a backend raising the genuine 400 envelope.

Tests: pytest tests/unit/test_ctx_overflow_device_profile_2884.py 25 passed (19 → 25; six new cover the prompt path, the Details: line, and the corrupt-config survival of both classifiers). pytest tests/unit/test_ctx_overflow_device_profile_2884.py tests/unit/test_lemonade_error_classification.py tests/unit/test_lemonade_base_url_passthrough.py tests/unit/test_cli_config.py tests/unit/chat/ui/ — 1086 passed on the merged head. python util/lint.py --all exit 0.

The rag_quality + context_retention + tool_selection vs Gemma baselines check is red for an infrastructure reason, not this diff: its preflight rejects the judge credential with You've hit your weekly limit · resets Sep 23, 8am, so no scenario ran.

NPU hardware still owed — the profile is exercised by pinning default_device=npu, which is the same input production reads.

@itomek
itomek marked this pull request as ready for review September 22, 2026 05:07
@itomek

itomek commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Green and current — merging.

Evidence above was measured on c5f95479. Head is now 859f0952, which adds only a no-conflict merge of main (#4109, _email/graph.py); nothing it touches is on this PR's surface, and the regression file re-ran green on the new head (91 passed with the incoming email tests included). Evidence unaffected.

CI on 859f0952: 38 green, 0 failures — Unit Tests py3.10 / py3.12 / macOS smoke, Code Quality, MCP Linux+Windows, Security Linux+Windows, RAG unit+integration, Chat / Gaia / Email agent, GAIA CLI Linux, CodeQL, pr-review.

🔍 On the eight jobs still queued

The remaining checks (API Tests, Agent SDK Windows, CLI Windows, Lemonade smoke, SD, Lemonade Embeddings, NPU FLM Embedder, Example Agents stx) all target [self-hosted, Windows, devlab-dispatch, strix-halo]. Four ephemeral runners carry that label and all four are busy; the other idle stx runners don't carry devlab-dispatch and can never pick these up. The backlog is repo-wide and reaches back past 03:00Z — main's own runs are in it — so cancel-and-rerun would only re-queue behind it.

This matches the repo's practice rather than departing from it: #4109 merged at 04:49Z with three of these same jobs queued.

@itomek
itomek added this pull request to the merge queue Sep 22, 2026
Merged via the queue into main with commit 4fe3f60 Sep 22, 2026
55 checks passed
@itomek
itomek deleted the issue-2884 branch September 22, 2026 05:43
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 22, 2026
One conflict, in `lemonade_client.py`: both sides added a new context-size
helper at the same spot, and each has live callers, so both stay.

`resolve_ctx_size(model, device)` (this branch) decides what window to
REQUEST at load time and is what honours `GAIA_CTX_SIZE`; it is called from
the agent base, the CLI, the installer and the manager.
`active_profile_ctx_size()` (main, amd#4095) reports the device profile's own
window with no override applied, and exists so the context-overflow
classifiers can judge a reported `n_ctx`. Collapsing them would break one
caller or the other.

`cli.py` and `agent.py` automerged, and both sides' intent survives: main's
`classify_lemonade_exception` error reporting is intact, and the inline
`GAIA_CTX_SIZE` block this branch replaced with the central resolver stays
deleted (main never touched it after the merge base).
kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 22, 2026
Picks up amd#4095, which landed while the conflict resolution above was in
progress. No conflicts.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents cli CLI changes llm LLM backend changes performance Performance-critical changes ready_for_ci Run CI workflows on draft PR without requesting review tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(agent): NPU context-overflow always misrouted to a reload, not trim-and-retry

1 participant