Skip to content

Studio: cancel + bound conversation-archive embeddings before inference (#14519) - #14546

Merged
danielhanchen merged 33 commits into
unslothai:mainfrom
indrajeetapache:fix/archive-embed-cancel-14519
Oct 23, 2026
Merged

danielhanchen merged 33 commits into
unslothai:mainfrom
indrajeetapache:fix/archive-embed-cancel-14519

Conversation

@indrajeetapache

@indrajeetapache indrajeetapache commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Confirms #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 fix(rag): avoid long CPU stalls when archiving tool calls #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 #14519

…ation path

Long chats spent minutes in a single SentenceTransformer.encode inside archive_turns before llama.cpp saw the request, and Chat Stop could not interrupt it (unslothai#14519). Batch embeds with cooperative cancel_check, cap chunks per call, and keep already-written groups.
Griggelor added a commit to Griggelor/unsloth that referenced this pull request Oct 21, 2026
@danielhanchen danielhanchen self-assigned this Oct 22, 2026
… cap test

A timeout late in a long archive pass discarded every batch already embedded, so the
next request redid them all. Write the groups those batches fully cover, then report
the failure as before. The cap test assumed one follow-up drains the backlog; loop
until it does and check every call stays under the cap.

[skip ci]
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-23T12:41:39.116488Z 43fd862 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f31c2cd399

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

)
_widen_span(conn, scope, digest, span)
continue
if collected >= max_chunks:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound the crossing group before chunking it

When collected is below the cap but the next evicted turn expands beyond the remaining budget (for example, 255 chunks followed by a large pasted turn), this newly added guard still lets chunk_pages tokenize and materialize the entire turn before the later kept pass discards it. Since cancellation is only polled around whole groups, Stop cannot interrupt that work, and the discarded turn is processed again on the next compaction, so a single large group can still recreate the pre-inference stall this cap is meant to prevent; make chunk production honor the remaining budget or defer the group without fully chunking it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is: the wasted step is tokenizing one oversized turn, not embedding it. Measured, a 191k-token turn chunks in 2.9 s against roughly 40 s to embed its 439 chunks, and that turn is embedded on the next request once it is first in line.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: f31c2cd399

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: c5071ab1a9

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 8c9350d336

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# Conflicts:
#	studio/backend/core/inference/diffusion.py

[skip ci]
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 43fd862d8f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 7dbc8b9 into unslothai:main Oct 23, 2026
6 of 57 checks passed
danielhanchen added a commit that referenced this pull request Oct 23, 2026
Two more backend checks fail on `main` (60c7715). Both reproduce on a
clean `main` worktree, and in both the test needed to change, not the
product.

| Check | Introduced by | Fix |
|---|---|---|
|
`studio/backend/tests/test_inference_dispatcher_resilience.py::test_route_llama_streaming_async_clients_disable_proxy_env`
(`assert 0 == 5`) | #14546 | That PR builds the five local llama-server
clients in `routes/inference.py` through `gated_async_client`. It wraps
`httpx.AsyncClient` so that conversation-archive embedding pauses for
the request. The AST walk only matched `httpx.AsyncClient(...)`, so it
found none. It now counts both spellings and still requires
`trust_env=False` on each of the five. It also pins that
`gated_async_client` passes its `**kwargs` to the `httpx.AsyncClient` it
builds, which is the step that keeps a proxy setting from reaching the
local server. |
|
`tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[6]`
| #14868 | `test_diffusion_zimage_cfg_split.py` read `diffusion.py` with
`read_text()`. That read now passes `encoding = "utf-8"`. |

The product side checks out: all five `gated_async_client(...)` calls
pass `trust_env = False`, and the wrapper forwards it.

## Verification

- `test_inference_dispatcher_resilience.py` and
`test_diffusion_zimage_cfg_split.py`: 38 passed.
- `tests/test_source_read_encoding.py`: 16 passed.
- Sabotage checks, each fails the guard:
  - removing `trust_env = False` from one of the five calls;
  - making `gated_async_client` drop its `**kwargs`;
  - restoring the bare `read_text()`.
danielhanchen added a commit that referenced this pull request Oct 23, 2026
`studio/backend/tests/test_gguf_load_cache_reuse.py::TestLoadHubDownloadExclusion::test_load_marker_precedes_hub_guard_which_precedes_the_gpu_handoff`
fails on `main`, for example in Backend CI `(Python 3.13, a-k)` on
#15000 and #15001.

## Cause

The test's last assertion is a literal source match:
`"@_with_gguf_load_marker\n def load_model("`. #14546 added
`@holds_inference` between that decorator and `def load_model`, so the
string no longer appears. The load marker still wraps
`LlamaCppBackend.load_model`, so the product is fine and the test was
out of date.

## Fix

The check now parses `llama_cpp.py`, finds `LlamaCppBackend.load_model`,
and asserts that `_with_gguf_load_marker` is in its decorator list, in
any position. The rest of the test, including the ordering in
`routes/inference.py`, is unchanged.

## Verification

- `studio/backend/tests/test_gguf_load_cache_reuse.py`: 75 passed. On
`main` this test failed when run alone.
- Sabotage check: removing `@_with_gguf_load_marker` from `load_model`
fails the test.
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.

[Bug] Long chats stall before inference in CPU conversation-archive embeddings; Stop does not cancel archiving

2 participants