Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix excessive studio.db writes during chat inference (#9945)

Lee Jacksoneb2c6de9dce0
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 3c17f831ae2..b022dd30984 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -675,6 +675,13 @@ async def lifespan(app: FastAPI):
# Hardware detection and MLX autorepair moved out of this lifespan: both import heavy
# runtimes and uvicorn binds only once this returns, so they held the login screen.
+ # Before the first writer, so startup's own connections stop checkpointing too.
+ try:
+ from storage.studio_db import open_wal_keeper
+ open_wal_keeper()
+ except Exception as exc:
+ _lifespan_log.warning("studio.db WAL keeper failed at startup: %s", exc)
+
# Reap workers/runs orphaned by a previous crash before new work starts.
try:
from storage.studio_db import cleanup_orphaned_runs
@@ -851,6 +858,11 @@ async def lifespan(app: FastAPI):
# Shutdown cleared the state this warm produced, so release the one-per-process latch.
reset_background_warm()
+ # Last, so every other shutdown step has had its final write first.
+ from storage.studio_db import close_wal_keeper
+
+ close_wal_keeper()
+
app = FastAPI(
title = "Unsloth UI Backend",
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index f7a0350e550..057f4de9f66 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -1236,12 +1236,16 @@ def _apply_wal_synchronous(conn: sqlite3.Connection) -> None:
conn.execute("PRAGMA synchronous=NORMAL")
-def get_connection(busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS) -> sqlite3.Connection:
+def get_connection(
+ busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS, *, check_same_thread: bool = True
+) -> sqlite3.Connection:
"""Open studio.db with WAL mode, create tables once per process, enable foreign keys."""
global _schema_ready
db_path = studio_db_path()
ensure_dir(db_path.parent)
- conn = sqlite3.connect(str(db_path), timeout = busy_timeout_seconds)
+ conn = sqlite3.connect(
+ str(db_path), timeout = busy_timeout_seconds, check_same_thread = check_same_thread
+ )
conn.row_factory = sqlite3.Row
# foreign_keys is session-scoped; set per connection
conn.execute("PRAGMA foreign_keys=ON")
@@ -1259,6 +1263,53 @@ def get_connection(busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS) -> sqlit
return conn
+# Every accessor here opens and closes its own connection, so a writer is routinely the last
+# WAL participant, and sqlite checkpoints the WAL back into studio.db on that close. At the
+# durable chat stream's flush cadence that is several rewrites a second (#9934).
+_wal_keeper: sqlite3.Connection | None = None
+_wal_keeper_lock = threading.Lock()
+
+
+def open_wal_keeper() -> bool:
+ """Hold this database's WAL open for the process. Returns whether a keeper is engaged."""
+ # Replace rather than inherit: a keeper from an earlier lifespan can belong to another
+ # database or a dead thread, and reusing it would keep nothing for the current one.
+ close_wal_keeper()
+ global _wal_keeper
+ with _wal_keeper_lock:
+ # Only ever runs the pragma below, on this thread. check_same_thread is off so a
+ # keeper stranded by an earlier lifespan can still be closed from this one.
+ conn = get_connection(check_same_thread = False)
+ try:
+ # What is in force, not what was asked for: journal_mode=WAL declines silently
+ # on filesystems without shared-memory support and persists in the file. Nothing
+ # to hold open there, so those installs go without, as _apply_wal_synchronous.
+ mode = conn.execute("PRAGMA journal_mode").fetchone()[0]
+ except (sqlite3.Error, TypeError, IndexError) as exc:
+ conn.close()
+ logger.warning("Could not read studio.db journal mode: %s", exc)
+ return False
+ if not isinstance(mode, str) or mode.lower() != "wal":
+ conn.close()
+ logger.info("studio.db is in %s mode, not WAL; WAL keeper not engaged.", mode)
+ return False
+ _wal_keeper = conn
+ return True
+
+
+def close_wal_keeper() -> None:
+ """Release the keeper; last-close checkpointing resumes."""
+ global _wal_keeper
+ with _wal_keeper_lock:
+ conn, _wal_keeper = _wal_keeper, None
+ if conn is None:
+ return
+ try:
+ conn.close()
+ except Exception as exc:
+ logger.warning("Could not close the studio.db WAL keeper: %s", exc)
+
+
def create_run(
id: str,
model_name: str,
diff --git a/studio/backend/tests/test_chat_generation_runs.py b/studio/backend/tests/test_chat_generation_runs.py
index 8201c7334a1..cfe7faf282b 100644
--- a/studio/backend/tests/test_chat_generation_runs.py
+++ b/studio/backend/tests/test_chat_generation_runs.py
@@ -1,7 +1,9 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import hashlib
import json
+from pathlib import Path
import pytest
@@ -14,6 +16,7 @@ from routes.chat_generation_runs import (
from storage import chat_generation_runs_db as runs_db
from storage import studio_db
from state.tool_policy import reset_tool_policy, set_tool_policy, set_tool_policy_default
+from utils.paths import studio_db_path
@pytest.fixture(autouse = True)
@@ -333,6 +336,26 @@ def test_batched_events_preserve_receipt_timestamps(chat_home):
assert [event["createdAt"] for event in chunks] == [1001, 1002]
+def test_stream_batches_do_not_rewrite_studio_db_while_the_keeper_holds_the_wal(chat_home):
+ """#9934: each event batch closed the last connection, checkpointing studio.db."""
+ _create()
+ worker_token = runs_db.get_worker_token("run-1")
+ db_path = Path(str(studio_db_path()))
+ wal_path = Path(f"{db_path}-wal")
+
+ assert studio_db.open_wal_keeper() is True
+ try:
+ before = hashlib.sha256(db_path.read_bytes()).hexdigest()
+ for index in range(5):
+ runs_db.append_events("run-1", worker_token, [("chunk", {"text": str(index)})])
+ assert wal_path.is_file()
+ assert hashlib.sha256(db_path.read_bytes()).hexdigest() == before
+ finally:
+ studio_db.close_wal_keeper()
+ assert not wal_path.exists()
+ assert len(runs_db.list_events("run-1")) >= 5
+
+
def test_cancel_before_registration_and_startup_orphan_reconciliation(chat_home):
queued, _created = _create("queued")
cancelled = runs_db.request_cancel("queued", "alice")
diff --git a/studio/backend/tests/test_studio_db_write_lock_contention.py b/studio/backend/tests/test_studio_db_write_lock_contention.py
index f39c3d22364..b43bcc2cd5b 100644
--- a/studio/backend/tests/test_studio_db_write_lock_contention.py
+++ b/studio/backend/tests/test_studio_db_write_lock_contention.py
@@ -12,6 +12,8 @@ poll query, and log levels.
"""
import asyncio
+import hashlib
+import inspect
import logging
import sqlite3
import threading
@@ -33,7 +35,9 @@ def db(tmp_path, monkeypatch):
monkeypatch.setattr(studio_db, "_schema_ready", False)
conn = studio_db.get_connection()
conn.close()
- return tmp_path / "studio.db"
+ yield tmp_path / "studio.db"
+ # A keeper left open would hold this temp database past the test that made it.
+ studio_db.close_wal_keeper()
def _journal_mode(path: Path) -> str:
@@ -738,3 +742,121 @@ def test_server_errors_keep_their_traceback(status):
log_and_http_error(raised, status, "public", event = "e", log = log)
level, kwargs = log.calls[0]
assert level == "error" and kwargs.get("exc_info") is raised
+
+
+def _digest(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def _short_lived_write(path: Path, value: str) -> None:
+ """One writer with the lifetime every studio_db accessor gives its connection."""
+ conn = studio_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ "INSERT OR REPLACE INTO app_settings (key, value_json, updated_at) "
+ "VALUES ('wal-probe', ?, '0')",
+ (value,),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def test_wal_keeper_keeps_short_lived_writers_out_of_the_main_database(db):
+ """The #9934 write amplification: without a keeper every close rewrites studio.db."""
+ wal = Path(f"{db}-wal")
+
+ for index in range(5):
+ _short_lived_write(db, f"unkept-{index}")
+ assert not wal.exists()
+ unkept = _digest(db)
+
+ assert studio_db.open_wal_keeper() is True
+ for index in range(5):
+ _short_lived_write(db, f"kept-{index}")
+ assert wal.is_file()
+ assert _digest(db) == unkept
+
+ studio_db.close_wal_keeper()
+ assert not wal.exists()
+ assert _digest(db) != unkept
+
+
+def test_a_second_open_replaces_the_keeper_instead_of_inheriting_it(db, tmp_path, monkeypatch):
+ """Inheriting a keeper left by an earlier lifespan holds a database this process has
+ stopped using, reporting success while keeping nothing for the current one."""
+ assert studio_db.open_wal_keeper() is True
+ stale = studio_db._wal_keeper
+
+ second = tmp_path / "second" / "studio.db"
+ second.parent.mkdir()
+ monkeypatch.setattr(studio_db, "studio_db_path", lambda: second)
+ monkeypatch.setattr(studio_db, "_schema_ready", False)
+
+ assert studio_db.open_wal_keeper() is True
+ assert studio_db._wal_keeper is not stale
+ _short_lived_write(second, "kept")
+ assert Path(f"{second}-wal").is_file()
+
+ studio_db.close_wal_keeper()
+ assert studio_db._wal_keeper is None
+ assert not Path(f"{second}-wal").exists()
+ studio_db.close_wal_keeper()
+
+
+def test_the_replaced_keeper_is_not_left_open(db):
+ """Replacing must release the old connection, not merely drop the reference."""
+ assert studio_db.open_wal_keeper() is True
+ stale = studio_db._wal_keeper
+ assert studio_db.open_wal_keeper() is True
+
+ with pytest.raises(sqlite3.ProgrammingError, match = "closed database"):
+ stale.execute("SELECT 1")
+ studio_db.close_wal_keeper()
+
+
+def test_a_keeper_left_by_a_dead_thread_is_replaced(db):
+ """sqlite refuses a cross-thread close, so replacing has to survive that failing."""
+ opened = threading.Thread(target = studio_db.open_wal_keeper)
+ opened.start()
+ opened.join()
+ stale = studio_db._wal_keeper
+ assert stale is not None
+
+ assert studio_db.open_wal_keeper() is True
+ assert studio_db._wal_keeper is not stale
+ _short_lived_write(db, "kept")
+ assert Path(f"{db}-wal").is_file()
+
+ studio_db.close_wal_keeper()
+ assert not Path(f"{db}-wal").exists()
+
+
+def test_wal_keeper_declines_when_the_filesystem_refused_wal(db, caplog):
+ """A rollback-journal install has nothing to hold open, and must still boot."""
+ conn = sqlite3.connect(str(db))
+ conn.execute("PRAGMA journal_mode=DELETE")
+ conn.close()
+ assert _journal_mode(db) == "delete"
+
+ with caplog.at_level(logging.INFO, logger = studio_db.logger.name):
+ assert studio_db.open_wal_keeper() is False
+ assert studio_db._wal_keeper is None
+ assert "not WAL" in caplog.text
+
+
+def test_the_lifespan_holds_the_keeper_across_every_writer():
+ """A keeper nothing opens saves nothing, and one released early stops saving early.
+
+ Reads the source rather than running the lifespan, which imports the whole stack.
+ Anchored on the awaited call, since the bare name is also in a comment further up.
+ """
+ import main
+
+ source = inspect.getsource(main.lifespan)
+ served = source.index("yield")
+ assert source.index("open_wal_keeper()") < source.index("cleanup_orphaned_runs()") < served
+ assert (
+ served < source.index("await run_lifespan_shutdown(") < source.index("close_wal_keeper()")
+ )