Skip to content

fix(rag): avoid long CPU stalls when archiving tool calls - #14098

Merged
oobabooga merged 4 commits into
unslothai:mainfrom
ATAMAH:perf/conversation-archive-tool-call-matching
Oct 19, 2026
Merged

oobabooga merged 4 commits into
unslothai:mainfrom
ATAMAH:perf/conversation-archive-tool-call-matching

Conversation

@ATAMAH

@ATAMAH ATAMAH commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

Long chats with large tool calls could spend minutes comparing messages
in the conversation archive before GPU inference even started.

The matcher tried every possible word split, rebuilding both halves of
the message each time. Most of those splits could never match.

Use space positions instead and narrow down the possible splits before
checking them. This keeps the existing matching behavior, including
repeated spaces and the alternative JSON representation of tool arguments.

In the reported case, this removed the CPU-only delay before inference.

@ATAMAH
ATAMAH requested a review from danielhanchen as a code owner October 18, 2026 00:57
@ATAMAH

ATAMAH commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

Maybe this issue affects only me. In my case, I have several chats with GLM 5.3 Flash using a 1M-token context. After several compactions, these chats become unusable: when the model attempts to retrieve content from archived messages, it gets stuck in the _same() function, pinning one CPU core at 100%. Every subsequent prompt in such a chat times out after 1200 seconds.

@oobabooga oobabooga self-assigned this Oct 19, 2026
@oobabooga

Copy link
Copy Markdown
Member

Reached Codex review convergence at oobabooga#391.

@oobabooga

Copy link
Copy Markdown
Member

Thanks! This speeds up conversation archiving when tool calls contain large arguments. I found no behavior changes in testing.

Speed

Synthetic tool-call histories, using Studio's actual matcher:

History searched Main With PR
10 earlier calls with 4,000-word arguments 1.35 s 9 ms
3 earlier calls with 16,000-word arguments 7.12 s 17 ms

Both versions found the same transcript position.

Validation

  • CI on the mirror PR, with the same commit and diff: 43 passed, 3 skipped, 1 neutral.
  • All 32 adversarial cases passed on main and with the PR applied. These used Studio's code and SQLite, with simulated embeddings and token counting.
  • Saved archive data matched exactly, apart from generated IDs and timestamps. All six checks with deliberately broken matchers failed as expected.
  • All 317 archive/compaction tests passed on both versions. More than 1.29 million string comparisons also produced identical results.
Scenario Result
Large, nearly identical file edits Finds the correct turn, including differences near the end and filename case changes
Python, Unicode, whitespace, nested JSON, repetitive text Handles JSON spacing differences and fallback from incomplete arguments
Same arguments, different result or assistant text Keeps the exchanges separate
Repeated calls, including one still in context Archives only the copies removed from context
Embedding changes and chat rewinds Keeps turn order and removes only extra copies
Empty results, reasoning, cancelled calls, multiple tool rounds Keeps the correct turn positions
Archiving before the chat message is saved Avoids duplicates when the message is saved later
Failed archive write Rolls back and allows retry
Recall after context is trimmed Works with inline recall, tool-style recall, and automatic recall disabled

Limits

Very repetitive inputs can still be slow, and some successful matches take a few extra milliseconds.

@oobabooga
oobabooga merged commit 104bc89 into unslothai:main Oct 19, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 23, 2026
…ce (unslothai#14519) (unslothai#14546)

## Summary
- Confirms [unslothai#14519](unslothai#14519):
on long chats, `archive_turns` blocked the generation worker in a single
synchronous `SentenceTransformer.encode` of every pending chunk, and
Chat Stop did not interrupt it (distinct from the string-matcher fix in
unslothai#14098).
- Embed pending archive chunks in batches (`_ARCHIVE_EMBED_BATCH = 64`)
and poll an optional `cancel_check` between batches;
`_archive_and_recall` forwards `cancel_event` from the chat Stop path.
- Cap chunks per `archive_turns` call (default 256, override
`RAG_ARCHIVE_EMBED_MAX_CHUNKS`); deferred groups stay unindexed and are
picked up on a later request (idempotent by digest). Already-written
groups are kept; incomplete groups are not written.
- Adds unit coverage for cancel-between-batches and per-call chunk
capping.

@danielhanchen - this matches the reporter’s py-spy stack
(`_archive_and_recall` → `archive_turns` → `encode_with_identity`).
Happy to adjust batch/cap defaults if you prefer different numbers.

## Test plan
- [ ] `pytest
studio/backend/tests/test_conversation_archive.py::test_a_first_compaction_embeds_its_turns_in_one_pass`
- [ ] `pytest
studio/backend/tests/test_conversation_archive.py::test_archive_embed_honors_cancel_between_batches`
- [ ] `pytest
studio/backend/tests/test_conversation_archive.py::test_archive_embed_caps_chunks_per_call`
- [ ] Manual: long tool-heavy chat with `RAG_CONVERSATION_ARCHIVE=1`,
send a short follow-up, press Stop during the pre-inference CPU spike -
embed work should stop between batches and inference path should not
stay pegged at ~17 cores
- [ ] Manual: same chat with archiving enabled - first follow-up should
not stall for many minutes before llama.cpp receives work; leftover
archive groups appear on later turns

## Follow-up changes
- Embedding failures keep every finished batch, and a backend swap
mid-pass restarts the pass in the new embedding space.
- Stop is honoured before chunking and before automatic recall, and
reaches the archive on managed engines (MLX, vLLM, SGLang).
- Idle-gap pre-embedding: turns that will be evicted are embedded into
an in-memory, content-keyed vector cache only while no inference is
running (tool calls, between turns), so a later compaction usually
encodes nothing. Every inference entry point pauses it and waits out its
batch in flight: chat streams on every engine, image and video
generation and loads, training starts, speech to text, the
OpenAI-compatible, Messages and Responses API passthroughs and direct
llama-server calls. The worker never queues on an embedder lock, and
nothing is written to the archive in the background, so edited turns
simply miss the cache.

Fixes unslothai#14519

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants