Repository navigation
Fix excessive studio.db writes during chat inference - #9945
Conversation
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. |
Resolves studio/backend/core/inference/chat_generation_runs.py: main added the lease sweeper, including a sweeper stop at the head of ChatGenerationSupervisor.stop(); this branch wrapped that method's body so the WAL keeper is released on the way out. Kept both -- the sweeper stop runs inside the try, and the keeper release stays in the finally.
get_connection now applies synchronous=NORMAL to every studio.db connection, gated on the database really being in WAL mode, and append_events reaches it through _connect. Setting the pragma again per batch is a no-op, and its comment claimed the terminal transaction in finish_run() still syncs at FULL, which is no longer true of any connection. All synchronous policy now lives in one place.
… in WAL mode open_wal_keeper() raised when the database reported any other journal mode, from an unguarded lifespan call, so an install whose filesystem declined WAL would not boot at all. journal_mode=WAL declines silently on filesystems without shared-memory support -- network shares, some FUSE and container mounts -- and the mode is persistent in the file, so this is reachable on a normal desktop install. It now returns None and logs, the lifespan guards the call like every other fallible startup step, and those installs go without the saving rather than without Studio. Matches how _apply_wal_synchronous already treats the same condition.
The keeper was constructed in the lifespan, handed to ChatGenerationSupervisor, and closed in its stop(), which forced that method's whole body into a try/finally. WAL lifetime is a property of the database, not of chat generation: every short-lived writer in the backend benefits, including the mcp_servers_db, credential_secrets and providers_db factories that open the same file. open_wal_keeper()/close_wal_keeper() now hold it as process state next to the existing schema latch, and the lifespan opens it before the first startup write and releases it after the last shutdown write. ChatGenerationSupervisor returns to what it was.
Two failures reachable when a lifespan does not release its keeper -- a shutdown that raised, or an embedded restart. open_wal_keeper() returned the existing keeper if it found one. A second lifespan on a different database therefore reported success while holding a database the process had stopped using, so the saving was silently off for the one it was using. It now releases whatever it finds before opening its own. That release could not happen at all when the keeper belonged to a thread that has since exited: sqlite refuses a cross-thread close, so the connection stayed an open WAL participant for the rest of the process and the WAL was never cleared. get_connection() takes a keyword-only check_same_thread, and the keeper -- which runs one statement, at open, on the opening thread, and is otherwise only closed -- opens with it off. Every other caller keeps the default.
|
Pushed an update on top of your commit (fast-forward, your original commit is untouched). Summary of what changed and why: Merged Dropped the per-batch Moved the keeper into A non-WAL database no longer fails startup. A keeper left by an earlier lifespan no longer breaks the next one. Opening reused an existing keeper if it found one, so a second lifespan on a different database reported success while holding a database the process had stopped using. It now replaces rather than inherits. That release could not happen at all when the keeper belonged to a thread that had exited, since sqlite refuses a cross-thread close, so the keeper opens with ValidationDeterministic A/B on the real
Live Studio regression, real streamed generation through
Cursor replay returned every chunk gapless on all runs, One thing worth noting for anyone reading the issue: the replay and sequence-gap checks pass on Backend suites are green: 122 tests in the two changed test files, and the failures in the wider selection are identical to those already on |
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
Lyxot
left a comment
There was a problem hiding this comment.
LGTM. Real bug, correct fix, and the numbers hold up.
Root cause is confirmed. Every studio.db accessor opens and closes its own connection, so a writer is routinely the last WAL participant and SQLite checkpoints the WAL back into the main database on that close. At the durable chat stream's flush cadence that is several full-database rewrites a second. Holding one connection open for the process lifetime removes the "last participant" condition; nothing else about the write path changes.
Live Studio regression, macOS, real generation through the real append_events path — the main database file was sampled continuously by a separate process while a chat run streamed:
| scenario | build | file samples | main-db rewrites | samples with no WAL |
|---|---|---|---|---|
| completion (172 chunks / 175 events) | main |
456,978 | 60 | 442,150 (97%) |
| completion | this branch | 94,721 | 0 | 0 |
| stop / cancelled | main |
28,215 | 23 | 25,783 (91%) |
| stop / cancelled | this branch | 18,171 | 0 | 0 |
Durability is unchanged in every run: persisted_last_seq matches the event count, cursor replay returns every chunk, sequence_gaps is empty. WAL growth stays bounded — 4000 batches peak the WAL at ~4 MiB flat while the main database grows normally, and PRAGMA integrity_check passes.
Cross-platform A/B, Linux + Windows: https://github.com/Lyxot/unsloth/actions/runs/33369159803 — 64/64 samples show main-database rewrites on the baseline, 0/64 with the fix, on both runners.
Full CI on the same commit: Lyxot#9 — 44 pass, 4 skipped, 3 fail. The three failures are the Core matrix legs, all failing in unsloth_zoo @ main — full pytest (CPU) on the same 5 tests/test_mlx_gated_delta_vjp.py cases (missing mlx.core.argpartition / mlx.core.put_along_axis shim trampolines, mlx_vlm.models.glm5_next, and two dtype errors). Those are red on main with no PR involved — see https://github.com/unslothai/unsloth/actions/runs/33368761281 — and this branch touches four files under studio/backend/, none in unsloth-zoo.
Behaviour on installs where WAL is unavailable is a log line and no keeper, not a startup failure, which matches how _apply_wal_synchronous already treats the same case.
## Summary On Google Colab during a large GGUF download, `POST /api/auth/refresh` returned 500 `sqlite3.OperationalError: database is locked` after about 5 s (raised at `BEGIN IMMEDIATE` in `consume_refresh_token`), and Unsloth Studio signed the user out even though the refresh token was still valid. There were four causes. auth.db kept SQLite's default `synchronous=FULL` under WAL, so every commit fsyncs while holding the write lock. It also had no long-lived connection, so the last close ran a checkpoint inside the process-wide `sqlite_gate` lock. `/api/auth/refresh` was `async def` and ran the blocking SQLite busy wait on the event loop, which stalled the whole server. Finally, the frontend cleared both tokens on any non-OK refresh response. studio.db already had `synchronous=NORMAL` and a WAL keeper (unslothai#9945, unslothai#9996); auth.db now gets the same treatment, and a busy auth.db no longer ends the session. ## Changes - auth.db switches to `synchronous=NORMAL` when it is in WAL mode. The lifespan holds one WAL keeper connection for the server's lifetime. `is_busy_error` and `apply_wal_synchronous` move from `studio_db.py` to `storage/sqlite_gate.py` so both databases share them, and the old names in `studio_db` remain as aliases. - `/api/auth/refresh` is now a sync route, so it runs off the event loop. The new `rotate_refresh_token` deletes the old token and inserts the new one in a single `BEGIN IMMEDIATE` transaction. A busy auth.db rolls back and returns 503 with `Retry-After: 2`, and the old token stays valid. `Retry-After` is added to the CORS exposed headers. - If `validate_api_key_account` finds auth.db busy, it skips the `last_used_at` update and validates read-only. The request no longer fails with 500. - The frontend clears tokens only when refresh returns 401. On 503 or 429 it retries up to 3 times within an 8 s budget, following `Retry-After`. Any other failure keeps the session, and the route guard counts a surviving refresh token as signed in. `refreshSessionOutcome()` returns `ok`, `rejected` or `unavailable`, and `refreshSession()` still returns a boolean. Behavior notes: - `test_config_mutations_on_event_loop.py` now lists `/refresh` among the off-loop routes, because the rotation is atomic in storage and no longer depends on the event loop for serialization. - `synchronous=NORMAL` can lose the last commits on a power loss or OS crash, but not on an application crash. This is the same trade-off as unslothai#9996. - In the desktop app, a refresh that gets no answer now returns the original 401 instead of falling through to desktop auto-auth. ## Testing Fault-injection A/B on a local Unsloth Studio, main `475a02ac18` vs this branch: - S1: another connection holds the auth.db write lock for 8 s. - S2: `fdatasync` on `auth.db-wal` is delayed 7 s via `LD_PRELOAD`. - S3: an API-key request is sent while the lock is held. | Scenario | main | this branch | |---|---|---| | S1 refresh | 500 after 5060 ms, `/api/health` up to 4871 ms | 503 + `Retry-After: 2` after ~5 s, `/api/health` max 230 ms; the same refresh token returns 200 after release; a reused token still returns 401 | | S2 refresh | 500 after 5047 ms, `/api/health` stalled 5258 ms | 200 in 13 ms | | S2 fsyncs (3 refreshes, fault disarmed) | 18 WAL + 6 main-file fsyncs | 0 auth.db fsyncs | | S3 API-key request | 500 | 200 (`last_used_at` update skipped) | | `PRAGMA synchronous` on auth.db | 2 (FULL) | 1 (NORMAL) | A cross-origin (`tauri://localhost`) 503 exposes `Retry-After` via CORS. Automated checks: - New `studio/backend/tests/test_auth_db_lock_contention.py` plus `test_config_mutations_on_event_loop.py` and `test_studio_db_write_lock_contention.py`: 98 passed (`pytest -n 2`). - Broader backend auth, account, credential, desktop, middleware, API-key and studio_db test families: 1806 passed, 16 failed. The same 16 fail on clean main on this host (missing `av` module and sqlite-vec extension). - Frontend: new `tests/auth-refresh-transient.test.ts` 14/14. All 91 frontend test files that touch auth: 1073/1073. `npm run typecheck` (tsc) is clean. ```bash cd studio/backend python -m pytest -n 2 tests/test_auth_db_lock_contention.py tests/test_config_mutations_on_event_loop.py tests/test_studio_db_write_lock_contention.py ``` ## Before / after The app loaded with an expired access token while another connection held the auth.db write lock for 16 s (merge base `475a02ac1` vs head `ae419121f`, each on its own fresh Studio install). - Before: `/api/auth/refresh` answered 500, both tokens were cleared and the page went to the login screen. - After: `/api/auth/refresh` answered 503 twice (retried within the budget), the refresh token was kept and the page stayed in the app.  --------- Co-authored-by: Daniel Han <[email protected]>
Summary
Why
Durable chat generation opens a short-lived SQLite connection for each event batch. When that writer becomes the last WAL participant, closing it checkpoints the WAL into studio.db. On Windows this made the main database rewrite continuously during inference and caused noticeable NVMe activity.
Validation
Durability scope
The NORMAL policy is connection-local and applies only to recoverable event-batch appends. Run creation, terminal status, chat history, and all ordinary Studio database transactions retain FULL synchronous behavior. SQLite auto-checkpointing remains enabled, and shutdown closes the keeper normally.
Closes #9934