Skip to content

Fix excessive studio.db writes during chat inference - #9945

Merged
Lyxot merged 6 commits into
unslothai:mainfrom
Imagineer99:fix/9934-studio-db-write-barriers-pr
Aug 31, 2026
Merged

Lyxot merged 6 commits into
unslothai:mainfrom
Imagineer99:fix/9934-studio-db-write-barriers-pr

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

Summary

  • Keep one engaged WAL connection for the Studio backend lifespan so short-lived event writers do not checkpoint on every close.
  • Use SQLite synchronous NORMAL only for high-frequency durable chat event appends; ordinary and final transactions remain FULL.
  • Close the keeper during supervisor shutdown and add regression coverage for both policies.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 29, 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-08-31T08:09:21.685434Z d7a3e79 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.

Lyxot added 5 commits August 31, 2026 15:19
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.
@Lyxot

Lyxot commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator

Pushed an update on top of your commit (fast-forward, your original commit is untouched). Summary of what changed and why:

Merged main. The branch had conflicted since main grew the chat-generation lease sweeper. The conflict was in ChatGenerationSupervisor.stop() and is resolved keeping both: the sweeper stop inside the try, the keeper release in the finally.

Dropped the per-batch PRAGMA synchronous=NORMAL. #9996 landed after this PR opened and now sets synchronous=NORMAL on every connection in get_connection, gated on the database really being in WAL mode. append_events reaches it through _connect, so the local pragma had become a no-op duplicate.

Moved the keeper into storage.studio_db. WAL lifetime is a property of the database rather than of chat generation, and every short-lived writer benefits, including the mcp_servers_db, credential_secrets and providers_db factories that open the same file. The lifespan opens it before the first startup write and releases it after the last shutdown write, so ChatGenerationSupervisor goes back to what it was.

A non-WAL database no longer fails startup. open_wal_keeper() raised from an unguarded lifespan call when the database reported any other journal mode. 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 that was reachable on a normal install: Studio would not boot at all. It now reports that it did not engage and those installs behave exactly as before.

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 check_same_thread off.

Validation

Deterministic A/B on the real append_events path, 64 batches of 16 events. The control runs the identical script with the keeper closed, which is the pre-fix path exactly:

platform before after
Windows 64/64 batches rewrote the main database 0/64
Linux 64/64 0/64

Live Studio regression, real streamed generation through /api/inference/chat-runs with a small GGUF, studio.db sampled from a separate process throughout:

before after
completion, 172 chunks / 175 events 60 main-database rewrites, no WAL present for 97% of samples 0 rewrites, WAL present throughout
cancelled mid-stream 23 rewrites 0

Cursor replay returned every chunk gapless on all runs, integrity_check ok, and a graceful shutdown removed the -wal and -shm files.

One thing worth noting for anyone reading the issue: the replay and sequence-gap checks pass on main too. The durable log was always intact, so this is write amplification and disk wear rather than a data-integrity problem, and no existing database is damaged. It also reproduces identically on Linux and macOS — Windows users noticed because Task Manager surfaces the NVMe busy time.

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 main.

@Lyxot

Lyxot commented Aug 31, 2026

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: d7a3e79483

ℹ️ 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".

@Lyxot Lyxot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

@Lyxot
Lyxot merged commit eb2c6de into unslothai:main Aug 31, 2026
45 of 49 checks passed
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
## 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.

![Before: signed out to the login screen. After: still in the
app.](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14151/pr14151_auth_busy_before_after-836515eee83c.png)

---------

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.

a lot of writes to studio.db

3 participants