Skip to content

fix(ui): bound document indexing in parallelism, time and Cancel - #5339

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/rel-ui-indexing
Oct 19, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/rel-ui-indexing

Conversation

@kovtcharov

@kovtcharov kovtcharov commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Before: uploading a few large documents indexed them all at once on the event loop's shared thread pool, the same pool the chat stream loop polls with, so open chats stalled while documents embedded. Cancel marked a document cancelled while its indexing ran on, and a stuck index had no limit. After: indexing has its own pools, two large documents at a time, and small files get two slots of their own so they never wait behind big PDFs. Cancel stops the work at the next page or embedding batch. A document that keeps making progress indexes to the end; one that makes no progress for 10 minutes stops with an error.

Reproduced by tests/unit/chat/ui/test_indexing_bounds.py and tests/unit/rag/test_indexing_stopped.py. On main, six uploads index at once on the shared pool, Cancel leaves the work running, and nothing stops a stalled index. All pass here, including the review's cases: a long but moving PDF finishes, a stalled one stops between pages, a small file finishes while big ones hold the large pool, and a cancelled cached document keeps its cache.

Related to #4744 (the agent's index_document tool timing out on big PDFs). This doesn't change that tool. It bounds the Agent UI's upload indexing, and adds the page heartbeat and stop that the tool could use too.

Merging with #5328: whichever of the two lands second wraps rag.index_document(...) in _index_document._do_index with lease_wait_listener(lambda _e: _step()). That makes lease-queue updates (embedder and VLM waits) count as progress, so an upload waiting behind a long chat isn't stopped as "no progress". Add a test that a long lease queue with updates doesn't trip the limit. Agreed with #5328's author.

Test plan

  • pytest tests/unit/chat/ui tests/unit/rag tests/unit/agents/tools tests/integration/test_files_router.py: all pass
  • python util/lint.py --black --isort --pylint --flake8 --test-lanes
🔍 Technical details
  • _index_document runs on _INDEX_EXECUTOR (2 workers), or _INDEX_SMALL_EXECUTOR (2) for files under 20 MB, never the default executor.
  • RAGSDK.index_document(..., heartbeat=) runs the callback once per PDF page through a thread-local. Raising IndexingStopped from it or from progress_callback leaves index_document as raised: no partial index, cache kept. The body moved to _index_document, and one source-inspection test follows it.
  • The no-progress clock starts when a worker picks the document up, so queued uploads wait without timing out. A job that stops making progress is failed after the limit, and its worker is freed at the job's next page or batch.
  • GAIA_INDEX_TIMEOUT is read at import, so a bad value stops start-up, the same as GAIA_STREAM_TIMEOUT. Documented in the Agent UI guide.
  • Known gaps:
    • A single page's VLM call has no stop point inside it; it's bounded by its own HTTP timeout.
    • After a cancel on Windows, the upload's temp file may stay in the temp dir until its worker lets go.
    • No separate "queued" document state: queued uploads show as indexing.
  • Not LLM-affecting.

@github-actions github-actions Bot added documentation Documentation changes tests Test changes rag RAG system changes performance Performance-critical changes labels Oct 18, 2026
@kovtcharov
kovtcharov marked this pull request as ready for review October 18, 2026 16:56
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Document uploads in the Agent UI now index on their own small pools, so large PDFs no longer stall open chats. Cancel now stops the work, and an index that stops making progress fails after 10 minutes. The design holds up and the tests reproduce each behavior. One edge case to fix: when PowerPoint indexing goes through PDF conversion, which is Windows-only, a Cancel or a stall timeout gets treated as a failed conversion. Indexing then falls back to slide-by-slide extraction and keeps going until the embedding step.

Real-world evidence

N/A: no evidence bundle was produced for this run. The change sits behind the Agent UI's upload/index path, so the verdict rests on static review plus the PR's unit tests. When someone next runs the strix-halo lane, a real upload → Cancel run (watching the document status and a concurrent chat) would be good to attach.

🔍 Technical details

🟢 A stop inside a converted PPTX is caught as a failed conversion (src/gaia/rag/sdk.py:1317)
_extract_text_from_pptx calls _extract_text_from_pdf on the PowerPoint→PDF output inside except Exception as pdf_err. _beat() raises IndexingStopped there, the handler logs "PDF extraction from converted PPTX failed, falling back", and the python-pptx fallback runs in full. It only stops at the first embedding batch, because stop stays set. While that happens it holds an indexing worker that the user believes is free. Re-raise it the same way _extract_text_from_pdf now does:

                except IndexingStopped:
                    raise
                except Exception as pdf_err:

🟢 First-run embedder load counts against the no-progress clock (src/gaia/ui/_chat_helpers.py:212)
The clock starts at the first _step(), before RAGSDK(config) is built and before the embedder loads. If that load is slow (for example, a cold Lemonade pull of the embedding model), it gets no beats, so a first-ever upload on a slow link could hit the 600 s limit. That's unlikely with the default limit; mentioning it in case the embedder load path can download.

Strengths

  • The stop is cooperative and clean: raising IndexingStopped keeps the existing cache, and test_stopping_a_cached_document_keeps_its_cache proves it.
  • The timeout measures progress, not elapsed time, and the clock starts only when a worker picks the document up. Long PDFs that keep moving aren't penalized, and queued uploads don't time out. Both cases are tested.
  • GAIA_INDEX_TIMEOUT fails loudly at import with an actionable message, matching GAIA_STREAM_TIMEOUT, and it's documented in the Agent UI guide.

Uploading several large documents ran them all at once on the event
loop's shared thread pool, which the chat stream loop also needs, so
chats stalled while documents embedded. Cancel marked a document
cancelled but the embedding kept running to the end, and a stuck index
had no time limit.

Indexing now runs on its own pool, two documents at a time; Cancel stops
the embedding at its next progress step; and one document stops after
30 minutes (GAIA_INDEX_TIMEOUT) with an error that says how to raise it.
…free

Review follow-ups on bounded indexing:

- Cancelling (or timing out) a document that was already cached fell into
  the 'cache corrupt' handler, which deleted the cache and re-extracted
  the document before stopping. A stop now leaves index_document as
  IndexingStopped, ahead of both broad handlers, and keeps the cache.
- The time limit started when the document was queued, so the third and
  later uploads could time out without ever starting. It now starts when
  a worker picks the document up.
…first

Review follow-ups on bounded indexing:

- The limit was wall-clock, so a large PDF that was still moving failed.
  It is now time without progress (GAIA_INDEX_TIMEOUT, default 600 s): a
  page extracted or a batch embedded resets it.
- Extraction couldn't be stopped, so a timed-out or cancelled PDF kept its
  worker and two of them blocked every later upload. RAG now calls a
  heartbeat per PDF page, and raising IndexingStopped there stops it.
- Files under 20 MB index on their own two workers, so a quick upload
  never waits behind big documents.
- A cancelled queued upload no longer logs 'Future exception was never
  retrieved'.
…y slide

The stop raised from the page heartbeat was caught by the converted-PDF
handler, which then fell back to reading the deck slide by slide with the
vision model. The stop is now re-raised ahead of that handler and the
deck's outer handler, and the slide-by-slide reader beats once per slide
so it can be stopped too.
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Oct 19, 2026
Merged via the queue into amd:main with commit 446e752 Oct 19, 2026
40 of 42 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rel-ui-indexing branch October 19, 2026 16:32
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]>
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Oct 21, 2026
…ancel reaches it (amd#5448)

Before: an Agent UI upload waiting in line for the model slot (the
embedder load, or a vision model call) got no page or batch done, so
after `GAIA_INDEX_TIMEOUT` (10 min) it was stopped as "no progress",
even though it was only queued behind a long chat. Cancel didn't reach
it either: it waited for the slot, loaded the model, embedded a batch,
and only then stopped. After: queue updates from the broker count as
progress, and Cancel or the no-progress stop end the wait at once. A
cancelled wait on a cached document keeps its cache.

This is the amd#5339 × amd#5328 merge item, "whichever lands second wires
`lease_wait_listener`". It didn't land with either PR.

Reproduced by
`tests/unit/chat/ui/test_indexing_bounds.py::test_waiting_in_line_for_the_embedder_counts_as_progress`,
`::test_cancel_reaches_an_index_waiting_in_line_for_the_model` and
`tests/unit/rag/test_indexing_stopped.py::test_a_cancelled_wait_for_the_model_keeps_the_cache_too`;
all three fail on main and pass here.

## Test plan
- [x] `pytest tests/unit/chat/ui tests/unit/rag tests/unit/agents/tools
tests/unit/test_broker_wiring.py`: 2655 passed
- [x] `python util/lint.py --black --isort --pylint --flake8 --imports
--test-lanes`

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

- `_index_document._do_index` runs `rag.index_document` inside
`lease_wait_listener(_queue_update)` and `lease_cancel_scope(stop)`.
Both are contextvars set on the indexing thread, which is where the
embedder's `load_model` and the VLM calls take their leases. The
listener only notes the time, since it runs on the waiting thread and
must not block or raise.
- `LeaseWaitCancelled` from that scope becomes `IndexingStopped`. In
`rag/sdk.py`, both of `index_document`'s broad handlers re-raise it, as
they do `IndexingStopped`. Without that, the cache-hit path took it for
a corrupt cache.
- Not LLM-affecting.
</details>

---------

Co-authored-by: Kalin Ovtcharov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Documentation changes performance Performance-critical changes rag RAG system changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants