Repository navigation
perf(llm): side work runs beside the conversation instead of queueing behind it - #5287
Closed
kovtcharov wants to merge 6 commits into
Closed
kovtcharov wants to merge 6 commits into
kovtcharov wants to merge 6 commits into
Conversation
The turn log said how long each model call took, but not how much of that the server spent computing, so "is GAIA keeping the backend busy?" had no answer. With GAIA_TURN_LOG set, each local model call now carries llama.cpp's own prefill/decode time and cache reuse (from the stream's timings) and the time GAIA spent before the request reached the server: model-slot lease, request lock, status probe, stats fetch. Each turn reports server compute, non-model time, named spans (memory recall, post-init upkeep, eviction, tool logging) and what filled the gaps between model calls; work after the answer is a second gaia.turn_post/1 line. - gaia.utils.perf_trace: thread-local hooks the LLM client reports into, one attribute read when recording is off. - The flagship sidecar serves the last records at GET /v1/gaia/debug/turns while recording is on (off the published contract; hidden routes no longer count in the capability matrix). - util/perf_turns.py drives /v1/gaia/query and samples the llama.cpp server (/slots, /metrics, per-process GPU utilization on Windows). - The TUI gains --pprof <loopback host:port>. - Memory's tool-history logging failures log a warning instead of debug.
… fragment A changed system prompt between two turns of one chat makes Gemma-4 re-read the whole prompt; the record now carries its hash and each mixin fragment's size, so the fragment that changed is named instead of guessed.
… behind it GAIA held one lock per model for the whole of every request, plus a cross-process daemon lease per request, so llama.cpp's second slot never ran anything at the same time as the first. A turn that arrived during memory extraction waited 5-9 s for it; in a 20-turn chat turns waited 2-28 s each (23% of the chat's wall time); a second chat waited 67 s for the first turn of the other. On Gemma-4-E4B / Radeon 8060S two concurrent decodes run at 88-90 tok/s against 46-49 for one, so the wait bought nothing. The lock is replaced by a per-model slot gate (gaia.llm.slot_gate): one request per llama.cpp slot, admitted only while the active requests' KV need fits the pool the model is actually loaded with — two active requests that outgrow a --kv-unified pool both fail, which is why the lock existed. Loads, unpinned requests and models whose loaded window is not yet known still hold the model exclusively, and a request's own pre-flight load check runs inside its slot hold. Within one process, concurrent same-model requests share one broker lease, joined only by a request that will finish well inside the broker's reclaim TTL, so no other process can swap the model mid-request.
3 tasks
…path - The prompt fingerprint uses SHA-256; Bandit blocks SHA-1 (B324). - A test now drives LemonadeClient._model_slot_lease and _ensure_model_loaded under an active recorder, with another request holding the lock, so the lock, lease and status-probe waits are proven to land on the open call rather than only when fed in by hand. - prompt.fragments counts only fragments present in the prompt that was sent. - dev.mdx says /debug/turns returns every session's records. - test_wait_tools patched the global time.sleep, so on Windows the rotating log handler's lock-retry sleep was counted as a nap and the "already stopped" test failed intermittently; the fixture now patches only the tool's clock.
3 of 4 tasks
2 tasks
kovtcharov-amd
added a commit
to kovtcharov/gaia
that referenced
this pull request
Oct 19, 2026
When one session started, or switched model with `/model`, every other session on the same sidecar froze. No tokens or heartbeats arrived for as long as the agent build or client switch took, so the TUI and the daemon relay saw an idle connection. Session setup now runs on a worker thread, so other sessions keep streaming. A busy or failed session still returns the same 409, 503 or 500 as before. Reproduced by `hub/agents/gaia/python/tests/test_server_event_loop.py`, which runs a real uvicorn sidecar and measures the heartbeat gap on one stream while another session builds, switches, or runs a one-shot. It fails on main with a 1.5 s gap and passes here. `test_another_session_cannot_evict_this_one_mid_setup` reproduces the spurious "already running a turn" 409 that a worker thread would otherwise open. <details> <summary>🔍 Technical details</summary> - `_off_loop()` runs the blocking setup on a worker thread: the session checkout, `session.switch_model`, and the one-shot `build_query_agent`. - The new `_SessionRegistry.checkout()` takes the session's run lock under the same lock eviction holds. Another request therefore can't evict the session between finding it and taking its turn. That window appeared once setup awaited a worker. - If the request is cancelled mid-setup, the abandoned call still releases what it took (the run lock, or the agent it built). That cleanup runs on its own thread, since closing an agent blocks. Route-level tests cover a cancelled `/model` switch, a cancelled one-shot build, and a cancelled wait for a stopped turn. These paths can't be cancelled on main at all, since setup there is synchronous. - Not done here: sending response headers before setup and streaming a "waiting" status. That would turn today's 409 and 503 into in-stream errors, a contract change for the TUI and relay. - amd#5328 also edits this file and **conflicts** where `_acquire_turn` used to be. This PR replaces that function with `_checkout_turn`; keep this version when resolving, and keep both CHANGELOG entries. amd#5287 touches other hunks. - `test_full_tool_bundles` and `test_manifest_tools_count_matches_real_registry` also fail on main on this dev box, where the optional browser tools aren't installed. - The real two-session check below hasn't run yet: another session's eval was using the shared Lemonade. </details> ## Test plan - [ ] `python -m pytest hub/agents/gaia/python/tests/test_server_event_loop.py hub/agents/gaia/python/tests/test_server_query.py hub/agents/gaia/python/tests/test_session_registry.py -q` - [ ] With two TUI sessions on one sidecar, stream a long answer in one and run `/model <other>` in the other. The first keeps streaming. --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
kovtcharov-amd
added a commit
to kovtcharov/gaia
that referenced
this pull request
Oct 19, 2026
…ws it is waiting (amd#5328) When several GAIA processes shared the model, a turn queued behind another failed after 300 s with "Check `gaia daemon logs`", even though the request ahead was legitimately running (local calls may take up to an hour). Leases were reclaimed mid-generation after 900 s. A request whose client had gone (Ctrl+C, Stop, app closed) still got the slot later and held it for nobody. The user saw nothing while waiting. Now a queued request waits for as long as the request ahead is alive. The Agent UI shows "Waiting for the model — `<who>` is using it" with its place in line and seconds waited. Stop or disconnect takes it out of the queue, and the holder keeps its lease while it renews. Independent review: a `code-reviewer` agent reviewed the diff. Its findings are fixed: Stop now cancels a queued wait, a grant that races a cancel is released on both sides, a stop during the pre-flight load stays quiet, only the holder can renew or release, and error messages don't leak lease ids. A bot review's follow-ups are fixed too: a Stop while queued is a cancelled turn, not an LLM error, and the heartbeat logs when it loses its credential. Reproduced by `tests/unit/test_daemon_broker_queue.py`. All of its 13 original tests fail on main and pass here. The two that show the user-facing symptoms with main's own API are `test_model_lease_waits_out_a_busy_holder_instead_of_failing` (504 on main) and `test_a_waiter_that_disconnects_is_never_granted_the_slot` (the dead waiter stays queued on main). Builds alongside amd#5327, which stops a busy daemon being killed. They share one identical hunk (the async credential check in `broker_routes.py`), so either can land first. amd#5287 replaces the per-model lock this PR makes reportable; whichever lands second keeps the wait reporting and cancel on the slot gate. Its shared-lease TTL margin can go once leases renew. Merge order with amd#5336: whichever lands second makes two additions. - `except LeaseWaitCancelled` in amd#5336's `_preflight_load`, ahead of its catch-all. - `lease_wait_limit(30)` around `_generate_session_title._ask`'s lease, so a title gives up rather than holding a default-pool thread behind a long queue. This PR's author does both if this lands second; amd#5336's does if that does. For the `except` clause, the guard is `test_stop_during_a_queued_preflight_stays_quiet_on_the_non_streaming_path`. It covers the turn that passes no handler and no cancel event, where only that clause keeps a stopped wait from being reported as a failed load. The handler-based variant passes either way, because amd#5336's wrapper already ignores errors once Stop is set. Merge order with amd#5339 (Agent UI indexing), same rule: whichever lands second wraps `rag.index_document(...)` in `_index_document._do_index` with `lease_wait_listener(lambda _event: _step())`. Queue updates then count as indexing progress, so an upload waiting for the embedder behind a long chat isn't stopped at amd#5339's 600 s no-progress limit. A test covers an index that waits on a lease longer than that limit. Merge order with amd#5359 (idle exit for non-default daemons), same rule. It stamps `_last_activity` in `ModelSlotBroker`, which conflicts with this PR in `broker.py` in two places, each resolved by keeping both sides. In `_grant_locked`, keep `_renewed_at` and `_last_activity`. In `_reclaim_if_stale_locked`, take this PR's version and add `self._last_activity = self._now()` before `notify_all()`. Eval categories to watch at the next RC. No prompt or tool surface changed. The agent-loop catchall gained one case: a Stop while queued for the model is a cancelled turn. Turn timing under a busy model also changed. Watch `rag_quality` and the `gaia_*` turn timings. Live run against the real daemon app (queue stream, queue route, a requester leaving, the wait cap): [output](amd#5328 (comment)). ## Test plan - [x] `python -m pytest tests/unit/test_daemon_broker_queue.py tests/unit/test_daemon_broker.py tests/unit/test_daemon_broker_routes.py tests/unit/test_broker_wiring.py tests/unit/chat/ui/test_model_queue_status.py -q` - [x] `python util/lint.py --black --isort --flake8 --pylint --test-lanes` - [ ] With a daemon running, hold the slot with a raw `POST /host/v1/models/lease`, then send an Agent UI turn. It shows the waiting line and updates it every 2 s. Press Stop, and `GET /host/v1/models/queue` shows nothing waiting. - [x] With `GAIA_MODEL_LEASE_WAIT_S=5`, the same turn fails after 5 s with where it stood in line and who held the model. <details> <summary>🔍 Technical details</summary> - **Protocol.** `POST /host/v1/models/lease` with `"stream": true` returns NDJSON: `queued` lines, then one `granted` or `error` line. Without `stream`, it is the old single JSON response with the old 300 s default, so older clients are unchanged. A new client talking to an older daemon reads its JSON reply, and never starts a heartbeat because there is no `renew_interval_s`. - **Renewal.** `"renewable": true` leases are kept by `POST …/lease/{id}/renew` every `heartbeat_ttl/4`. They are reclaimed after 60 s without a renewal, with a 4 h cap. Non-renewing leases keep the 900 s TTL. - **Cancellation.** Each wait runs on its own daemon thread (`broker_routes._Wait`), never the shared anyio pool. A disconnect or abandon sets the broker's `cancel` and calls `wake()`. A grant that races the abandon is released exactly once, under `_Wait._guard`. A streamed grant counts as delivered only after its send returns. - **Silence detection.** The client sets a 30 s socket timeout on the body only, so older daemons can still take 300 s to send headers. On the client, a cancel that arrives with the grant line releases that lease. - **Turn scope.** `broker_client.interactive_turn` sets context vars for priority, the wait listener and cancel. Plain threads (memory extraction) start without them and stay background. Threads that copy the context (tool runners, the stream watchdog) stay part of the turn. The UI cancel checks both `TurnCancel` and the SSE handler's Stop flag. - **Ownership.** Renew and release check the caller is the lease's holder. `LeaseNotHeldError` no longer echoes the active lease id. `GET /host/v1/models/queue` strips it too. - **Surfaces.** The queued state goes out as a `status` event with `phase: "model_queue"` and a `queue` object (`event` queued/granted, position, holder, seconds waited). It goes on the Agent UI's SSE stream and on the `/query` streams of the gaia agent (which the TUI reads; amd#5319 renders it) and the email agent. Both canonical translators keep `queue`, and the contract is in `agent-ui-query-sse-contract.md` §4.4. Stop in the Agent UI and `/query/{run_id}/cancel` on either sidecar end the wait. The stdio transport still only logs it. A non-streaming Agent UI turn has no stream to show it on, so queue updates only keep its idle stop from firing. - **Bounds.** A renewing lease is held at most its holder's declared hold. LemonadeClient declares the call's own timeout (the request budget when none is passed), plus the retry deadline after which no new attempt starts, plus 15 min for a load. Undeclared leases keep main's 900 s, and the ceiling is 2 h. Background waits have no ceiling, but they age: after 10 min queued they rank as interactive. Side work that must not tie up a worker thread wraps itself in `lease_wait_limit(seconds)`; the chat title gets it from whichever of this and amd#5336 lands second (above). Background work a turn starts (indexing) runs outside the turn's scope. The lease route refuses NaN or infinite `timeout` and `max_hold_s`. - **Not in this PR.** Cross-home arbitration (eval homes sharing one Lemonade through separate brokers) is designed and staged for a follow-up. </details> --------- Co-authored-by: Kalin Ovtcharov <[email protected]>
…oved lock Co-Authored-By: Claude Opus 5.5 <[email protected]>
3 tasks
huong8373tt-beep
pushed a commit
to huong8373tt-beep/gaia
that referenced
this pull request
Nov 1, 2026
…shes (amd#6234) A model the user had set up in Lemonade with their own llama.cpp arguments (here Gemma 4 E4B with an MTP draft and `-np 1`) was loaded with GAIA's two-slot chat flags instead, and GAIA's save then erased the user's arguments. On llama.cpp b12020 those flags abort that model at startup, and every chat turn re-sent the same load, so llama-server crashed several times per message and chat never worked. Now GAIA loads the model with the arguments the user saved and leaves their saved options alone. A load that still crashes fails once with an error naming the flags and how to change them, and isn't re-sent unchanged for 2 minutes. Closes amd#6222. Fixes the GAIA side of amd#6221: the abort itself is a llama.cpp bug, which GAIA can't fix. The user can now avoid it by saving their own arguments for the model. ## Test plan - [ ] `python -m pytest tests/unit/test_lemonade_load_args_and_crash.py tests/unit/test_lemonade_single_slot.py tests/unit/test_lemonade_chat_slots.py -q` - [ ] `python -m pytest tests/unit -q -k "lemonade or load or slot"` - [ ] On a Lemonade with a model whose `llamacpp_args` are saved (`lemonade load <model> --llamacpp-args "-np 1" --save-options`, then unload it), select that model in GAIA and send a message. GAIA's `/load` carries no `llamacpp_args` and no `save_options`, llama-server starts with `-np 1` and without `--kv-unified`, and `recipe_options.json` is unchanged afterwards (re-running `gaia init` doesn't change it either). <details> <summary>🔍 Technical details</summary> - The saved args come from `recipe_options.llamacpp_args` in a fresh `/models?show_all=true` read. Per Lemonade's API docs, that field holds the model's registry options plus `recipe_options.json` on top. Blank values and GAIA's own current or earlier (`--parallel 1`) flags are not treated as the user's. - For such a model the request omits `llamacpp_args`, so Lemonade resolves the saved options exactly as for the user's own load. Request args would also replace the architecture defaults. `save_options` is never sent for it, even when the caller asks (as `gaia init` does), because a save replaces the whole stored entry (ctx, backend, args). The crash key includes the saved args, so saving new ones lets the load through at once. - If that catalog read fails, the load now fails loudly instead of guessing, because sending GAIA's flags could override the user's arguments. - The crash memo is process-wide, keyed by base URL, model, and every load option except `save_options`. Only the transient-classified `llama-server failed to start` is remembered, after its retries run out. Any successful POST /load of the model clears it. Within one call the 3 retries are unchanged, because the Vulkan startup fault they exist for gives the same error text as a deterministic crash. - Slot pinning already follows `slot_count()`, which reads `-np` / `--parallel` from `/health`. A one-slot model keeps all requests on slot 0, and a test covers this. - Overlap with amd#5287 (draft): it rewrites the per-model request lock and slot lease. This PR touches neither, so the two only meet in `lemonade_client.py`, in separate hunks. - Not done on purpose: retrying a crashed load without the chat flags. That would be a silent fallback. </details>
Contributor
Author
|
Closing: main now covers the case this PR mainly targeted, and the rest needs a fresh design on main's current code.
The branch stays on the fork for reference. |
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.
GAIA let only one request at a time reach the local model, even though Lemonade runs it with two llama.cpp slots, so background memory extraction made the user wait. A message sent during extraction waited 5–9 s. In a 20-turn chat, turns waited 2–28 s each (23% of the chat's wall time), and a second chat waited 67 s for the first. On this Strix Halo two decodes run together at 88–90 tok/s against 46–49 tok/s for one, so the wait bought nothing. Side work now runs beside the conversation. In the same 20-turn chat, GAIA's wait dropped to 0 s on every turn.
Draft because one question is open. In the after-run's 20-turn chat, the system prompt changed between turns of one session (27,356 ↔ 29,063 chars), and each change cost a full ~19K-token re-read. Controlled tests show that concurrency itself does not break the cache: slot 0 kept all of it with a 2.5K-token prefill running on slot 1. The baseline chat never changed its prompt, though, so this PR (or #5286, or #5288) may let a background job finish mid-chat and change it. #5285 adds a per-fragment prompt fingerprint that names the culprit on the next run.
Builds on #5285 (it contains that PR's commits); review that one first.
--kv-unifiedKV pool both fail. The new gate admits a request only while every active request's estimated KV need fits the window the model is actually loaded with. Loads, requests with no slot, and models whose loaded window isn't known yet still hold the model exclusively.Test plan
python -m pytest tests/unit/test_slot_gate.py tests/unit/test_lemonade_chat_slots.py tests/unit/test_broker_wiring.py -qGAIA_TURN_LOGset, send a message right after a turn that triggers memory extraction. The second turn'sllm_calls[].client.lock_wait_sis ~0 andutil/perf_turns.pyreports both slots busy.prompt.system_shastays the same across turns. This is the open question above.