Skip to content

fix(rag): make LLM-based chunking terminate and fail loudly - #4262

Merged
kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/rag-llm-chunking-terminate
Sep 26, 2026
Merged

kovtcharov-amd merged 1 commit into
amd:mainfrom
kovtcharov:claude/rag-llm-chunking-terminate

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

Turning on LLM chunking (gaia chat --use-llm-chunking, or use_llm_chunking=True, which the deployment playbook recommends for max quality) hung indexing on every document. The loop never finished, and every pass quietly fell back to word splitting because the LLM call used a method the Lemonade client doesn't have. Now indexing finishes after one LLM call per ~6K-character segment. The model sees the whole segment it's splitting, and no chunk is longer than chunk_size tokens (about 4 characters per token). If the LLM can't be reached or returns no usable split list, indexing reports a clear error that names the model and the character range. It no longer switches strategy without telling you.

Test plan

  • python -m pytest tests/unit/rag/test_llm_chunking.py -q: 9 passed. On main, 6 fail and the 2 failure-path tests hang forever.
  • python -m pytest tests/unit/rag/ tests/test_rag.py tests/unit/test_rag_tools.py tests/unit/test_rag_index_status.py -q: 174 passed
  • python util/lint.py --black --isort: changed files are clean. isort flags 3 unrelated files that are already failing on main.
  • pylint src/gaia/rag/sdk.py with the CI config: clean
  • gaia eval agent --category rag_quality --agent-type doc, compared against the committed baseline. The default path doesn't change (LLM chunking is off by default). Run this to confirm.
  • Manual: gaia chat --use-llm-chunking --index <doc.pdf> against a running Lemonade Server finishes and answers from the document.

Fixes #4195

Indexing with use_llm_chunking=True looped forever on every document: the
segment cursor rewound past the end of the last segment, and the LLM call
used a method LemonadeClient doesn't have, so each pass silently fell back
to word splitting and grew the chunk list without bound.

- Stop after the final segment and guarantee the cursor always advances.
- Call LemonadeClient.completions and send the whole segment, not the first
  2,000 characters, so the model sees what it is asked to split.
- Snap segment edges to whitespace and cap every chunk at chunk_size * 4
  characters.
- LLM or parse failures now raise with the segment range and model name;
  index_document reports that error instead of switching to the heuristic
  chunker behind the user's back.

Fixes amd#4195
@github-actions github-actions Bot added documentation Documentation changes rag RAG system changes tests Test changes performance Performance-critical changes labels Sep 25, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This fixes two real bugs in LLM-based chunking — the loop that never ended, and the call to a Lemonade method that doesn't exist (so every "semantic" chunk was silently word-split). Both fixes are correct and the new tests are good. One regression came in with them.

Chunk overlap is now effectively zero. The code aims the next segment 400 characters back (the configured 20% overlap) and then snaps to a word boundary — but it searches for that boundary in the wrong direction, landing right back at the end of the previous segment. Measured on a 15K-character document, the overlap kept is 7–8 characters instead of 400. That removes the context bridge between segments, which is exactly what chunk_overlap exists to preserve, and it's a regression from the old behaviour. The new tests don't catch it because they only bound the number of LLM calls, not the stride — worth an assertion once it's fixed.

Two smaller things: a chatty model that writes a citation-style [1] before its answer will have that picked up as the split list, and the docs update landed in one playbook page while the sibling deployment page still recommends turning this on for "max quality" without mentioning that it now hard-fails when the LLM is unreachable.

Real-world evidence

No evidence bundle was produced for this PR, and the description's two behavioural checks — the rag_quality eval and a real gaia chat --use-llm-chunking --index <doc.pdf> run — are both left unchecked. The unit tests are solid and I verified the loop's termination and chunk-size bounds myself by re-running the algorithm standalone, but nothing here shows the CLI flag actually indexing a document end-to-end against a live server. Since the flag's behaviour is what changed, that run (or a note marking it N/A with a reason) is the missing artifact. This verdict rests on static review plus a standalone simulation, not on a live run.

🔍 Technical details

Issues

🟡 Overlap between segments collapses to ~0 characters (src/gaia/rag/sdk.py:1470-1474)

_last_whitespace(text, next_start, segment_end) uses rfind, so it returns the whitespace closest to segment_end — not the one nearest next_start. next_start is then reset to almost exactly segment_end.

Measured with the defaults (chunk_size=500, chunk_overlap=100 → overlap_chars=400) on a 15,000-char document:

seg 0: pos=0     end=5993  intended_next=5593  actual_next=5986  overlap_kept=7
seg 1: pos=5986  end=11984 intended_next=11584 actual_next=11976 overlap_kept=8
seg 2: pos=11976 end=14990 intended_next=14590 actual_next=14982 overlap_kept=8

The pre-PR line (position = segment_end - (overlap * 4)) applied the full overlap, so this is a behavioural regression, not a pre-existing gap. Search backwards from next_start instead:

            if segment_end == text_length:
                break
            next_start = max(segment_end - overlap_chars, position + 1)
            boundary = self._last_whitespace(text, position + 1, next_start + 1)
            if boundary > position:
                next_start = boundary + 1
            position = min(next_start, segment_end)

I ran this variant against the same document: overlap_kept becomes 399/404, call count is unchanged at 3, and position still advances strictly every iteration (next_start > position is guaranteed by the max(...) and the boundary > position guard; min(..., segment_end) keeps it from skipping text).

tests/unit/rag/test_llm_chunking.py:89-91 computes stride = segment_size - OVERLAP * 4 but only uses it as an upper bound on call count, so it passes either way. Worth adding a stride assertion — e.g. that a word near a segment boundary appears in two chunks.

🟢 First bracketed integer wins the regex, including citations (src/gaia/rag/sdk.py:1486)

re.search returns the first match, so "Based on [1] I suggest: [245, 502]" parses as [1] — a 1-character chunk followed by the rest. Verified against the real regex. test_split_array_is_found_after_bracketed_prose uses [Page 1], which the digit-only pattern correctly skips, so this case isn't covered. Preferring the longest match is a one-line change:

        matches = re.findall(r"\[\s*-?\d+(?:\s*,\s*-?\d+)*\s*\]|\[\s*\]", response)
        if not matches:
            raise ValueError(f"no JSON array in LLM response: {response[:200]!r}")
        positions = json.loads(max(matches, key=len))

🟢 Sibling doc still implies the old fallback contract (docs/playbooks/chat-agent/part-3-deployment.mdx:425,558)

Part 2 got the "indexing fails with an error" note; part 3 recommends use_llm_chunking=True for the max-quality profile with no mention that an unreachable LLM now aborts indexing rather than degrading. Per CLAUDE.md, a behaviour change should land in every doc that describes it.

🟢 Dead branch in the position filter (src/gaia/rag/sdk.py:1490)

The regex only matches integer literals, so isinstance(p, int) and not isinstance(p, bool) can never be False after json.loads. Harmless, but it reads as though non-int input is expected.

Strengths

  • generate → completions is the real find. LemonadeClient has no generate method (lemonade_client.py:2404 is completions), so the old call raised AttributeError on every segment and the except Exception swallowed it into word-splitting. The # pylint: disable=no-member on that line was suppressing exactly the signal that would have caught it. Signature and response shape both match.
  • Sending the whole segment instead of segment[:2000] is the right correctness fix — split positions returned against a truncated preview were being applied to the full segment, so boundaries past 2000 chars were meaningless.
  • Termination is genuinely fixed. I re-ran the loop standalone on a 15K document, a 20K whitespace-free blob, and a pathological chunk_overlap > 3 × chunk_size config; all terminate, and every chunk is ≤ chunk_size * 4 characters.
  • The tests target the failure modes rather than coverage — the _RunawayLoop(BaseException) trick to escape the chunker's own error handling is a nice way to make a non-terminating loop fail fast instead of hanging CI.

kovtcharov-amd pushed a commit to kovtcharov/gaia that referenced this pull request Sep 25, 2026
)

Document and image extraction failed whenever the model wrote a
placeholder such as `{field}` before its JSON answer: the parser only
tried the first `{`, gave up, and the extraction raised "did not parse".
It now moves past an invalid span and finds the real JSON. It still
never looks inside a broken object, so truncated or malformed output
returns nothing instead of a misleading fragment. Also adds table tests
for the JSON parser behind every VLM extraction path, and tests that pin
the Stable Diffusion prompt text to the real per-model defaults so the
size, steps, and CFG the model is told to use can't drift from them.

Covers the parser and SD-prompt parts of amd#4257. Chunking and
cache-clearing are in amd#4262 and amd#4260. `deltas_cli`,
`code_bench_fixtures`, and the TUI flag wiring already had tests.
`talk/app.py` is left out because it needs a design decision (see the
issue).

## Test plan
- [x] `python -m pytest tests/unit/test_parsing.py`: 2 placeholder cases
fail on `main`, 13/13 pass with the fix
- [x] `python -m pytest tests/unit/test_parsing.py
tests/unit/test_sd_prompts.py tests/unit/test_file_watcher.py
tests/unit/test_structured_vlm_extraction.py
tests/unit/test_vlm_extraction_failures.py tests/unit/test_sd_mixin.py
tests/unit/test_sd_error_messages.py
hub/agents/gaia/python/tests/test_sd_tools_do_not_rewrite_the_prompt.py`:
176 passed, 3 skipped
- [x] black, isort, and pylint (errors-only, CI config) are clean on the
changed files
- [x] `python util/check_test_lane_coverage.py` does not flag either new
file (the `pytest tests/unit/` lane runs them)

Part of amd#4257

Co-authored-by: Kalin Ovtcharov <[email protected]>
@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 7b9057e Sep 26, 2026
36 of 37 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/rag-llm-chunking-terminate branch September 26, 2026 05:11
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.

fix(rag): LLM-based chunking never terminates

2 participants