Repository navigation
Studio RAG: reuse one rag.db connection per thread within a linked-folder sync pass - #16607
Merged
Merged
Conversation
…rkers or only stats files
…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
marked this pull request as ready for review
November 5, 2026 12:46
Member
Author
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_jobprogress,_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.commit()calls, so every commit point stays where it was. Theirclose()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.row_factory = sqlite3.Row,busy_timeout = 5000). A dead connection is replaced. A different database path (another account) never shares.account_db.get_connection(), theRAG_AVAILABLEcheck, the schema step and the WAL keeper step still run on every call.sqlite_gate.sqlite_gate.connectnow accepts afactory(it must subclassGatedConnection). Existing callers are unchanged.folder_syncuses the block in four places:finish_pending_ingest_folder_documentHandle 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:drain_one)_snapshot(copy into the account's uploads folder),_hash_file,_check_root_identityand_source_reappeared(stats), and_remove_snapshot(unlink, including the removals_install_mappingand_delete_mappingdo 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 infinish_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 -wforfolder_sync.pyis 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_syncon 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.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:BEGIN IMMEDIATEwriter orwal_checkpoint(TRUNCATE)release_reused()closing only an idle shared connection, and a stale close not ending another caller's transactiondrain_onewait, 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)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:
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 HEADon the changed files: PASS.Python 3.9 / 3.10 / 3.11 / 3.12 / 3.13: checked that a
sqlite3.Connectionsubclass created through afactoryrolls back on an overridden close.Not covered
test_retiring_an_account_mid_sync_keeps_the_shared_folder_worker_aliveon windows-latest because the coordinator held the idle shared connection during the snapshot copy; 1b68c0f still failed it, because the test wraps_snapshotand 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'sstart_ingestionpath resolution (account_path) runs in such a gap and is not released.closing()or a singlefinally), and telling the two apart would need a separate handle per checkout, so it is not guarded.