Skip to content

feat(rag): search documents from their text and read images in the background - #6286

Open
kovtcharov wants to merge 21 commits into
amd:mainfrom
kovtcharov:kalin/index-text-first
Open

kovtcharov wants to merge 21 commits into
amd:mainfrom
kovtcharov:kalin/index-text-first

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Adding a folder of large PDFs used to lock you out for hours, because every image went through the vision model before anything could be searched. On seven real documents, the first question went from about 1.5 hours away to about 3 minutes: text is indexed first, image reading carries on behind you, and any answer given meanwhile says it may be incomplete, in the Agent UI and the TUI.

Measured on a 37-question set scored out of 74, the score is the same while images are being read as after they all finish (59), and the typical wait for the first word is 63 s against 67 s with nothing reading.

Before After
Time until you can ask about 1.5 h 3 min 19 s
All images read during indexing about 3 h 10 min, in the background

Worth weighing in review:

  • Reading runs on a thread in whichever GAIA process is open, not a separate OS process, because a frozen build can't start a Python worker. It resumes after a restart.
  • Reading stops while a chat answers and for five minutes after, since one vision read pushes the chat out of the model's cache and adds about 50 s to the next answer. Keep chatting and reading waits; the first question after a long idle can still pay that cost once.
  • Scripts and the SDK keep the old behaviour unless they set read_images_later.

Builds on #6265 and #6261, which should land first. Eval categories to watch on the next RC: rag_quality, real_world.

Library

Arabic

Test plan

  • python -m pytest tests/unit/rag tests/unit/chat/ui
  • cd src/gaia/apps/webui && npm test && npm run test:rtl
  • cd tui && go test ./internal/event/... ./internal/ui/...
  • Add a PDF with images in the Agent UI: it is searchable right away, the library shows image progress, and an answer carries the note, also after reopening the chat
  • Ask the same in the TUI: the "may be incomplete" row appears

The library indexes an upload's temp copy and chats index the original.
The cache key includes the path, so a first chat read every page again,
images included: 40 minutes on a 790-page library that was already done.

A cache entry for the same bytes and chunking is now reused from any path.
Adding seven PDFs took 28 minutes and a first chat another 30: most adds
blocked until indexed, nothing showed once the library closed, and a chat
read a file the library was already reading, from page one, silently.

Adding a document now returns at once from the library, file browser, drag
and drop, folders and Retry, and each indexes on its own. A line above the
chat shows N of M done, one bar and the time left, and opens the library,
which shows the same plus the file in hand.

The estimate is measured per phase on this machine and covers later phases
and queued files. It shows nothing until there are enough samples, a lower
bound while a phase is unmeasured, and "taking longer than expected" in place
of a frozen number.

A chat leaves documents that are indexing, cancelled or failed out of the
turn and says so; the agent's own index tools report the running index
instead of starting another. Cancel now reaches queued documents, Retry and
automatic re-indexing, and a restart mid-index stays visible.
Each row sized its bar to its status text, so Cancel sat at a different spot on every line. The bar now takes the row and Cancel stays at its end, in either direction.
…PC has

Scanned Arabic pages were shrunk until the text was unreadable, so the vision
model returned little or nothing and those pages couldn't be searched. Images
now keep their resolution within the model's limits.

Indexing also uses the PC's chat model when it can read images, so a 64 GB PC
running Qwen3.6 doesn't need Gemma downloaded just to read a scan.
A PC running Qwen3.6 with Gemma configured for vision swapped models to read
each scan, evicting chat. A tested vision model already in memory is now used
as it is; a text-only chat model is passed over for Gemma, which is smaller.
Indexing sent every image to the vision model, about 22 seconds each, so a 229-page report took 30 minutes. Of 310 images read across seven documents, 252 gave no text, and pages with under 100 characters held 90% of what was gained.

Images are now read on pages with under 200 characters of their own text, which still covers scans. Charts on text-heavy pages are left unread, and the document's metadata counts those pages.
…ckground

Waiting for every image before a document could be searched took 30 minutes on a long report, and would take days on thousands of documents. A document is now searchable from its text in seconds, and a worker reads its images afterwards, pages short of text first, adding what it finds to the search as it goes. It pauses while a chat is answering and carries on after a restart.

An answer that searched a document with images still unread says so: the tool result tells the model, and the Agent UI and TUI show the warning themselves, so it doesn't depend on the model repeating it.
…installs

Holding one lock across a whole page read made library uploads fail and Stop freeze the backend, so state changes now take a short lock and only reading takes the long one. Packaged installs get the same warning and step aside for relayed turns. Documents match by content rather than name, deleting one stops its reading, a blocked document resumes alone, and a page that keeps failing is recorded and shown.
Questions asked while images were being read took about 45 seconds longer,
because the worker slipped a page in between turns and the question then
waited for it and rebuilt its prompt. Reading now stays away for a minute after
each answer and gives way between images. The status also stays up when a
batch has just finished, and the estimate no longer waits for every document
to have been timed.
The chat guide read as if every image were read whenever a vision model is available.
Measured with 90 seconds between questions, each answer still took about 50
seconds longer, because a single vision read pushes the chat's prompt out of the
model and it has to be processed again. Reading now waits until the user has
stopped asking, so this costs one answer at most in a conversation.
PDF images now come from PDFium, so the skip for images under 2% of a page
moved there too. A page that fails is raised by PDFium's reader itself, which
is what the background pass needs to retry it.
The note under an answer was saved but dropped when the chat was read back,
so it disappeared on reload. Found by opening a real answer; it only showed
during the live turn.
@github-actions github-actions Bot added documentation Documentation changes devops DevOps/infrastructure changes rag RAG system changes llm LLM backend changes tests Test changes electron Electron app changes performance Performance-critical changes agents tui Go terminal UI (gaia-tui) labels Nov 1, 2026
@kovtcharov
kovtcharov marked this pull request as ready for review November 1, 2026 14:45
@github-actions

github-actions Bot commented Nov 1, 2026

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions

Documents become searchable from their text right away, and a background worker reads their images afterwards. The worker resumes after a restart, pauses while a chat is answering, and adds a "may be incomplete" note to answers in the Agent UI and the TUI. It is well built and well tested. Nothing here blocks merge, but one edge case in the worker can save the same image text twice, which is worth closing before this goes live.

  • A page can be added to the search index twice. The worker saves a page's text into the document's cache and only afterwards marks the page as done. If the app exits between those two steps, or the vector save fails, the page is read again and its text is saved a second time, so searches return duplicate passages. Recording which pages have already been saved in the cache would make retries harmless.
  • The pause only applies within one GAIA process. A chat running in the TUI won't stop a reader running inside an open Agent UI server, and the reverse is also true. The PR description presents the pause as unconditional. Either document this limit or share the "turn running" signal between processes.

Real-world evidence

N/A: no evidence bundle was produced for this run. The PR description embeds before→after screenshots of the Agent UI library and the Arabic indicator, which meets the UI evidence bar. The TUI "may be incomplete" row and the background-reading timings rest on the author's description and a static review only.

🔍 Technical details

🟡 Important

  • Appending image text is not idempotent (src/gaia/rag/sdk.py, _read_queued_page, and src/gaia/rag/image_pass.py:341-352). _save_cache(...) writes old_chunks + new_chunks before _commit adds the page to done. Two ways to re-read the page:

    • The process exits between the two steps. The thread is daemon=True, so it is killed at interpreter exit.
    • _save_vectors raises after the cache was saved. _read_one then counts that as a failed attempt and retries.

    Either way the chunks are appended a second time. A fix: record the page in the cache, e.g. metadata.setdefault("image_pages_read", []). At the top of _read_queued_page, return 0 when number is already in that list.

🟢 Minor

  • The state-file read cache keys on mtime only (image_pass.py:110-114). Ext4 without multigrain timestamps, and HFS+, can give two atomic renames in quick succession the same st_mtime_ns. When that happens, _load returns the earlier JSON, and a later _commit writes it back. That can undo a cancel(), or drop a page from done. write_bytes_atomic swaps the inode on POSIX, so adding it and the size to the key is cheap:
              stat = path.stat()
              modified = (stat.st_mtime_ns, stat.st_size, stat.st_ino)
    
    The Tuple[int, str] annotation on _parsed would need to change to match.
  • The temp copy can leak (sdk.py, _keep_for_images). It mkstemps a copy of a converted deck into cache_dir. _read_later deletes it only if indexing gets as far as writing the cache. If indexing fails earlier (embedding error, IndexingStopped), the tmp*.pdf stays behind. _CACHE_OWNED_FILE doesn't match that name, so gaia cache clear never removes it either. Give it a name the regex owns, or delete it in a finally around the indexing body.
  • Resumed reading may use different chunking settings (document_monitor.resume_image_reading). It resumes with RAGSDK(RAGConfig(show_stats=False)), so pages resumed after a restart are split with the default chunking settings, which may differ from the session's own. The cache key's fingerprint stays the same, so if a non-default config was in use, the cache can end up holding chunks split two different ways. Low impact today, since the UI uses defaults.

Strengths

  • Pausing between images (the before_each → ReadPaused hook) instead of only between pages keeps the cost to a waiting chat small, and the reader and state locks are cleanly separated. No lock-order inversions that I could find.
  • State-file keys and names are regex-validated before they are turned into paths, so the new cancel-images endpoint can't be steered outside the cache directory.
  • Thorough test coverage: test_image_pass.py, test_index_tracker.py, background indexing, RTL visual fixtures, and the TUI wire contract.

rezamuliawijaya pushed a commit to rezamuliawijaya/gaia that referenced this pull request Nov 7, 2026
A document edited after it was indexed kept answering from its old text:
indexing it again said "already indexed" and changed nothing, and only a
new session picked up the edit. Now indexing an edited document
re-indexes it, and an unchanged one still returns at once without
re-embedding.

Open PRs amd#6265 and amd#6286 rework background indexing but don't touch this
already-indexed check, so they don't overlap with this fix.

## Test plan
- [ ] `python -m pytest tests/unit/rag/test_edited_document_reindex.py
tests/unit/rag/test_retrieval_bench_harness.py`
- [ ] In `gaia chat`, index a text file and ask about it; edit the file,
ask the agent to index it again, and the answer reflects the edit
- [ ] Index an unchanged file twice; the second call reports it is
already indexed

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

- `RAGSDK` keeps `file_content_keys` (the `_content_key` of the indexed
bytes), set on both publish paths and cleared in `remove_document`
(which LRU eviction uses) and the `reindex_document` rollback snapshot.
- A repeat `index_document` hashes the file outside the lock; a mismatch
calls `reindex_document`, which now passes the progress/wait callbacks
through. The hash, not mtime/size, is the check, so a same-size edit
with a restored timestamp is caught (tested).
- The two race re-checks now compare keys: another writer's index of
different bytes is replaced instead of being reported as current.
- A locked file (Windows exclusive open) reports `file_locked` and keeps
its index rather than being dropped.
- `RAGToolsMixin.index_document` short-circuits only when the new
`is_current()` agrees.
- The `replaced_document` retrieval hard case should flip fail→pass; the
gate reports that as information, and the baseline JSON is left for the
next real run.
- Regression hunt: every rag/index/document unit test plus the
flagship's document tests pass (2376 + 382); the one pdfium-thread
failure in the baseline run didn't reproduce.
</details>

Closes amd#4738
kovtcharov-amd added a commit to huong8373tt-beep/gaia that referenced this pull request Nov 7, 2026
A document edited after it was indexed kept answering from its old text:
indexing it again said "already indexed" and changed nothing, and only a
new session picked up the edit. Now indexing an edited document
re-indexes it, and an unchanged one still returns at once without
re-embedding.

Open PRs amd#6265 and amd#6286 rework background indexing but don't touch this
already-indexed check, so they don't overlap with this fix.

## Test plan
- [ ] `python -m pytest tests/unit/rag/test_edited_document_reindex.py
tests/unit/rag/test_retrieval_bench_harness.py`
- [ ] In `gaia chat`, index a text file and ask about it; edit the file,
ask the agent to index it again, and the answer reflects the edit
- [ ] Index an unchanged file twice; the second call reports it is
already indexed

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

- `RAGSDK` keeps `file_content_keys` (the `_content_key` of the indexed
bytes), set on both publish paths and cleared in `remove_document`
(which LRU eviction uses) and the `reindex_document` rollback snapshot.
- A repeat `index_document` hashes the file outside the lock; a mismatch
calls `reindex_document`, which now passes the progress/wait callbacks
through. The hash, not mtime/size, is the check, so a same-size edit
with a restored timestamp is caught (tested).
- The two race re-checks now compare keys: another writer's index of
different bytes is replaced instead of being reported as current.
- A locked file (Windows exclusive open) reports `file_locked` and keeps
its index rather than being dropped.
- `RAGToolsMixin.index_document` short-circuits only when the new
`is_current()` agrees.
- The `replaced_document` retrieval hard case should flip fail→pass; the
gate reports that as information, and the baseline JSON is left for the
next real run.
- Regression hunt: every rag/index/document unit test plus the
flagship's document tests pass (2376 + 382); the one pdfium-thread
failure in the baseline run didn't reproduce.
</details>

Closes amd#4738
@kovtcharov-amd kovtcharov-amd added the enhancement New feature or request label Nov 12, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents devops DevOps/infrastructure changes documentation Documentation changes electron Electron app changes enhancement New feature or request llm LLM backend changes performance Performance-critical changes rag RAG system changes tests Test changes tui Go terminal UI (gaia-tui)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants