Skip to content

Studio RAG: reuse one rag.db connection per thread within a linked-folder sync pass - #16607

Merged
danielhanchen merged 6 commits into
mainfrom
perf/r26-ragsync
Nov 5, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
perf/r26-ragsync

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

What changes

During a linked-folder sync pass, every bookkeeping step opened its own rag.db connection: _check_running (lease renewal plus the cancel check), _set_job progress, _update_mapping_metadata, _install_mapping, delete_terminal_job, get_job_status, release, and so on. That came to about 14 opens per ingested file and 4 per file whose mtime changed but whose content did not. Each fresh connection costs about 0.5 ms before it does any work: the open, the sqlite-vec load, and a parse of the 52-entry schema on its first statement. A reused connection runs the same statement in 5 to 7 us.

storage/rag_db.reuse_connections() is a thread-local block. Inside it, get_connection() gives every caller on that thread the same connection, and the block closes it when it ends.

  • Callers keep their own commit() calls, so every commit point stays where it was. Their close() now rolls back whatever they left uncommitted, which is exactly what a real close throws away. Any lease row, mapping row or progress update is durable at the same moment as before.
  • If a caller opens a connection while the shared one is still checked out, it gets a separate, normal connection, so an inner close can never end an outer caller's transaction.
  • On checkout the connection gets the fresh-connection settings back (row_factory = sqlite3.Row, busy_timeout = 5000). A dead connection is replaced. A different database path (another account) never shares.
  • The account retirement check in account_db.get_connection(), the RAG_AVAILABLE check, the schema step and the WAL keeper step still run on every call.
  • Opens and closes still go through sqlite_gate. sqlite_gate.connect now accepts a factory (it must subclass GatedConnection). Existing callers are unchanged.

folder_sync uses the block in four places:

  • the coordinator's work loop (including draining in-flight files)
  • finish_pending
  • the deletion loop
  • each worker's _ingest_folder_document

Handle parity rule: wherever base holds no rag.db handle, head holds none either. rag_db.release_reused() closes the thread's shared connection if no caller holds it, and the next open in the block starts a new shared one. It is called:

  • before the coordinator waits on in-flight workers (drain_one)
  • as the first step of each file-work helper the blocks reach: _snapshot (copy into the account's uploads folder), _hash_file, _check_root_identity and _source_reappeared (stats), and _remove_snapshot (unlink, including the removals _install_mapping and _delete_mapping do after their commit)

The coordinator also releases right before it calls _snapshot, so a wrapper or slow start around the helper sees no handle either. Where a helper runs while a caller still has the connection checked out (as on base, which holds its own connection there), the release does nothing. So an account-delete rename on Windows sees the same set of open handles as on base at every file copy, hash, stat, unlink and wait. A repeated close of an idle shared connection does nothing.

What is left shared: back-to-back database steps with only in-memory work between them, chiefly the worker's per-file sequence (_check_running, start_ingestion, the ingestion run, lease release, get_job_status, _check_running) and the install, prune and progress steps in finish_pending.

The directory scan, the rescan and the steps before and after a pass still open connections as before. Lease renewal, cancellation checks, ordering, errors and job rows are unchanged. The git diff -w for folder_sync.py is 4 added lines; the rest of that file's diff is indentation.

How often this runs: on every folder attach, on Sync changes / Rebuild, on the 30 s auto-sync of any folder that has changed files, and on the startup reconcile. An unchanged folder on the 30 s loop does about 20 opens per pass on both base and head, so it is unaffected.

Results (base 6f79197 vs head)

Real folder_sync on a real rag.db with sqlite-vec, stub embeddings, 4 ingest workers, CPU only. One interleaved base/head round, median of 5 runs, min to max in brackets.

Pass Base ms Head ms Change Opens base -> head
Attach 100 txt files 1557 (1359-4764) 1124 (1013-1188) -28% 1414 -> 517
Resync, 100 files mtime-only 465 (386-486) 502 (347-518) none (noise) 420 -> 320
Resync, 50 of 100 edited 819 (776-916) 716 (640-886) -13% 706 -> 318
Resync, 50 of 100 deleted 339 (278-339) 271 (208-308) about -20%, near noise 170 -> 121
Resync, unchanged 47 (40-81) 37 (34-94) none 20 -> 20

The gain is now in ingestion: about 4 ms per ingested file, mostly from the worker's per-file sequence. Metadata-only resyncs (mtime changed, content not) gain nothing: every database step there is separated by a copy, hash, stat or unlink, so parity forces a fresh open each time. With real embeddings the per-file saving is the same in absolute terms; it is a large share with GPU or llama-server embedding of small files and a small share with CPU embedding.

Tests

  • New tests/test_rag_connection_reuse.py (14 tests). It covers:

    • one connection per block, and close discarding uncommitted work
    • a nested open getting its own connection
    • nested blocks sharing one connection
    • settings restored on checkout
    • a dead connection being replaced
    • a different database path not sharing
    • blocks being per thread
    • an idle shared connection not blocking a BEGIN IMMEDIATE writer or wal_checkpoint(TRUNCATE)
    • a retired account still being refused inside a block
    • release_reused() closing only an idle shared connection, and a stale close not ending another caller's transaction
    • no rag.db connection open on the coordinator thread inside the drain_one wait, the snapshot copy, every root identity stat, the deletion-loop recheck and every snapshot removal, over attach, touch and delete passes (fails without the releases)
    • a folder sync committing each file's mapping before the next file starts (checked from an independent connection), with an open-count check

    Base fails the open-count checks (183 opens against a bound of 96 on attach); head passes.

  • Base-vs-head differential, 16 seeds, 1 ingest worker, deterministic ids, 160 passes, 0 differences across every rag.db table, including the FTS and sqlite-vec shadow tables. Each seed has:

    • a random folder: txt / md / unsupported files, empty files, duplicate content, subfolders, files that fail to embed
    • a mutate pass: edits, mtime-only touches, renames, deletions, additions
    • four injected passes, each followed by a follow-up pass:
      • a crash (BaseException) at a random point
      • an OSError at a random point
      • the lease row deleted mid-pass
      • a cancel mid-pass

    Opens went from 11669 to 7054.

  • With 4 workers the tables are not deterministic on base itself (insertion order across threads; how many workers finish before a simulated crash). A/A base vs base and base vs head show the same kind of differences, so this setting is reported only as no new failure.

  • Neighbour suites:

    • tests/test_rag_*.py, account storage and the folder sync rotation tests: 1664 passed on base, 1678 on head (the 14 new tests), same (empty) failing set.
    • tests/studio -k "rag or folder or sqlite or gate or lease": 1849 passed on both.
  • scripts/verify_import_hoist.py --before 6f791972ef --after HEAD on the changed files: PASS.

  • Python 3.9 / 3.10 / 3.11 / 3.12 / 3.13: checked that a sqlite3.Connection subclass created through a factory rolls back on an overridden close.

Not covered

  • Windows and macOS were not run locally. Earlier head commits failed test_retiring_an_account_mid_sync_keeps_the_shared_folder_worker_alive on windows-latest because the coordinator held the idle shared connection during the snapshot copy; 1b68c0f still failed it, because the test wraps _snapshot and blocks before the helper's own release ran; 7dd7e67 also releases at the call site, and the handle-parity test now probes a wrapped _snapshot (it sees 1 open handle without that release, 0 with it). The probes cover that point and every other file-work point. Between back-to-back database steps with only in-memory work between them, one idle handle stays open for microseconds where base opened and closed several. The worker's start_ingestion path resolution (account_path) runs in such a gap and is not released.
  • A second close by the same caller while another caller has the shared connection checked out would roll back that caller's work. No caller closes twice (all use closing() or a single finally), and telling the two apart would need a separate handle per checkout, so it is not guarded.
  • Real embedding models were not timed end to end on this host. The CPU here is shared and too noisy: bge-small took 0.45 to 2 s per file.

…py, hash, stat and snapshot removal in a sync
… site too

A wrapper or slow start around _snapshot ran before the helper's own release, so the
coordinator still held an idle rag.db handle there. The handle-parity test now probes a
wrapped _snapshot and fails without this release.
@danielhanchen
danielhanchen marked this pull request as ready for review November 5, 2026 12:46
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 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-11-05T12:48:35.392911Z 8df7546 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 8df7546c7e

ℹ️ 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 f240d74 into main Nov 5, 2026
@danielhanchen
danielhanchen deleted the perf/r26-ragsync branch November 5, 2026 13:27
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Nov 6, 2026
…g every linked-folder file (unslothai#16722)

Fixes unslothai#16714

## What was wrong

When a linked folder synced while the embedding model's Settings
transfer was still pending, every file went to the embedder and each one
failed the same `EmbeddingModelDownloadRequiredError` check in `_load`.
All of them were then saved to the folder's `failed_files` list, which
keeps unchanged failed files out of periodic syncs for 6 hours (unslothai#13095).
The folder stayed at "N files that couldn't be indexed" after the
download finished, until a manual Rebuild.

## What this changes

- `embeddings.download_required(model)`: True while the model's
pending-download marker is set and the cache-only loader still can't
load it. It costs nothing when no transfer is pending. Otherwise it asks
the loader, which retires the marker once the cache is complete, so a
finished download reads False.
- `folder_sync._reconcile_folder`: before ingesting, if there is work
and the download is still pending, the job fails with one job-level
message ("The embedding model '...' is not downloaded yet. Indexing
starts on its own once its Settings download finishes."; a folder with
auto sync off is told to sync again instead). No file is marked failed
and the existing index is left as it is. The periodic sync then indexes
the folder by itself once the transfer lands, with no Rebuild needed.
- A download-required error that still happens mid-sync (the transfer
going pending after the check) is not written to `failed_files`, so the
next sync retries those files. Entries written that way before this
change are no longer held back either, so folders already stuck like the
one in the report recover on the next periodic sync.
- The three raise sites now build the message with one shared helper, so
the stored error text can be recognized reliably.

## Testing

On Windows 11, Ryzen 5600H, RTX 3050 4 GB, Python 3.12:

- New `tests/test_rag_folder_sync_download_pending.py` (8 tests): the
check skips the loader when nothing is pending, follows a pending
transfer to completion, and leaves other load failures to the documents.
The sync waits without marking files, then a periodic sync indexes all
of them once the download lands. A Rebuild while pending keeps the
existing index. Mid-sync download errors aren't held back, but a
genuinely bad file still is. Pre-existing stuck entries retry.
- Real Studio end to end (`run.py --api-only`, sentence-transformers on
CPU, empty HF cache, `RAG_FOLDER_SYNC_INTERVAL_S=5`): saved
`unsloth/bge-small-en-v1.5` in Settings (stored with `download_pending:
true`), linked a 40-file folder, then started Studio's own download
through `POST /api/hub/download` and waited, triggering only periodic
syncs.
- main: `40 file(s) could not be indexed`, each failing with "is not
downloaded yet". After the download completed, the folder still showed
40 failures and 0 documents.
- this branch: "The embedding model 'unsloth/bge-small-en-v1.5' is not
downloaded yet..." with 0 failed files. After the download completed,
the folder went idle with 40 documents and 0 failures.
- Related suites on this branch and on a clean copy of main gave
identical results: test_rag_linked_folders,
test_rag_folder_sync_retirement, test_rag_folder_scan_filters,
test_rag_linked_folder_grant_retry, test_folder_sync_account_rotation,
test_embedding_model_settings/resolve/security_gate,
test_offline_embedding_minimal, test_openai_embeddings_studio_fallback,
test_rag_embed_llama_server, test_rag_embeddings,
test_rag_embedding_identity, test_rag_reembed, test_rag_ingestion,
test_rag_source_files_indexing, test_conversation_archive,
test_rag_reconcile_orphaned. The failures that do occur (symlinks and
case-sensitive paths in test_offline_embedding_minimal,
test_openai_embeddings_studio_fallback and test_rag_embed_llama_server)
happen on clean main too on this Windows machine.
- `ruff check` is clean on the changed files.

Not covered: the llama-server embedding backend end to end (no
llama-server binary on this machine). Its raise site only switched to
the shared message helper.

## Follow-up (maintainer)

- Merged current main (conflict with unslothai#16607's per-thread connection
reuse in `finish_pending`, resolved keeping both).
- The job-level message no longer says "still downloading": the pending
marker is also set when the Settings download was never started, so it
now says the model is not downloaded yet.
- The new test module clears the process-wide embedding resolution memo
around each test; without it, 7 tests in
`test_rag_embed_llama_server.py` failed when run after it in one
session.
- Real loader repro (no mocks, CPU, tiny sentence-transformers model,
empty HF cache, pending marker set, 40-file folder, then the snapshot
lands and the next periodic sync runs): main fails all 40 files and
still holds back all 40 after the download; this branch fails 0, then
indexes all 40 on the next periodic sync and retires the marker.

---------

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.

1 participant