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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: serialize studio.db connection opens and closes (#10069)
Kenshi86e706864625
diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex 8e1f19ebe9c..89f0afb6c2a 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -25,6 +25,7 @@ from huggingface_hub import HfApi, constants as hf_constantsfrom auth import policyfrom core.inference.gpu_arbiter import GpuBusyForAnotherAccountError+from storage.studio_db import connect_studio_dbfrom utils.paths import storage_rootsfrom utils.paths.storage_roots import project_workspaces_root, studio_db_path, workspace_root@@ -678,7 +679,7 @@ def model_grants() -> set[str]:if not path.is_file():return set()try:- with closing(sqlite3.connect(str(path))) as conn:+ with closing(connect_studio_db(path)) as conn:row = conn.execute("SELECT value_json FROM app_settings WHERE key = 'model_grants'").fetchone()@@ -709,7 +710,7 @@ def record_model_grant(repo_id: str, repo_type: str = "model") -> None:def _write_grant(path: Path, key: str) -> None:- with closing(sqlite3.connect(str(path), timeout = 5.0)) as conn, conn:+ with closing(connect_studio_db(path, timeout = 5.0)) as conn, conn:conn.execute("CREATE TABLE IF NOT EXISTS app_settings (key TEXT NOT NULL PRIMARY KEY, value_json TEXT NOT NULL, updated_at TEXT NOT NULL)")diff --git a/studio/backend/storage/credential_secrets.py b/studio/backend/storage/credential_secrets.pyindex 75736d87bc2..9568f91e3f4 100644--- a/studio/backend/storage/credential_secrets.py+++ b/studio/backend/storage/credential_secrets.py@@ -19,6 +19,7 @@ from typing import Optionalfrom cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom auth.storage import get_or_create_credential_encryption_key+from storage.studio_db import connect_studio_dbfrom utils.paths import ensure_dir, studio_db_pathlogger = logging.getLogger(__name__)@@ -69,7 +70,7 @@ def reset_schema_state_for_tests() -> None:def get_connection() -> sqlite3.Connection:db_path = studio_db_path()ensure_dir(db_path.parent)- conn = sqlite3.connect(str(db_path), timeout = 5.0)+ conn = connect_studio_db(db_path, timeout = 5.0)conn.row_factory = sqlite3.Rowtry:os.chmod(db_path.parent, 0o700)diff --git a/studio/backend/storage/library_db.py b/studio/backend/storage/library_db.pyindex 2cf2582a9fd..bfa4381ce2b 100644--- a/studio/backend/storage/library_db.py+++ b/studio/backend/storage/library_db.py@@ -16,6 +16,7 @@ import uuidfrom pathlib import Pathfrom typing import Optional+from storage.studio_db import connect_studio_dbfrom utils.paths import ensure_dir, studio_db_path_schema_lock = threading.Lock()@@ -82,7 +83,7 @@ def get_connection() -> sqlite3.Connection:# One key for the check and the add, or a home reached through a link never finds its entry# and runs the schema again on every connection.schema_path = db_path.resolve()- conn = sqlite3.connect(str(db_path))+ conn = connect_studio_db(db_path)conn.row_factory = sqlite3.Rowif schema_path not in _schema_ready:with _schema_lock:diff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.pyindex d4635e69b87..484a35659d6 100644--- a/studio/backend/storage/mcp_servers_db.py+++ b/studio/backend/storage/mcp_servers_db.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom datetime import datetime, timezonefrom typing import Optional+from storage.studio_db import connect_studio_dbfrom utils.paths import studio_db_path, ensure_dir_schema_lock = threading.Lock()@@ -49,7 +50,7 @@ def reset_schema_state_for_tests() -> None:def get_connection() -> sqlite3.Connection:db_path = studio_db_path()ensure_dir(db_path.parent)- conn = sqlite3.connect(str(db_path))+ conn = connect_studio_db(db_path)conn.row_factory = sqlite3.Rowif db_path not in _schema_ready:with _schema_lock:diff --git a/studio/backend/storage/providers_db.py b/studio/backend/storage/providers_db.pyindex 6ff5776a8f0..fb16ff5bcd9 100644--- a/studio/backend/storage/providers_db.py+++ b/studio/backend/storage/providers_db.py@@ -24,6 +24,7 @@ from urllib.parse import urlparselogger = logging.getLogger(__name__)+from storage.studio_db import connect_studio_dbfrom utils.paths import studio_db_path, ensure_dir_schema_lock = threading.Lock()@@ -144,7 +145,7 @@ def reset_schema_state_for_tests() -> None:def get_connection() -> sqlite3.Connection:db_path = studio_db_path()ensure_dir(db_path.parent)- conn = sqlite3.connect(str(db_path))+ conn = connect_studio_db(db_path)conn.row_factory = sqlite3.Rowif db_path not in _schema_ready:with _schema_lock:diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 89a139a9ac3..87a8c0a2478 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -139,6 +139,36 @@ def contains_sensitive_path_component(path: str) -> bool:_schema_lock = threading.Lock()_schema_ready: set[Path] = set()++# SQLite 3.51.0-3.51.1 deadlocks when one thread's WAL close (unixIsSharingShmNode) races another+# thread's open or close of the same file: they take the VFS and inode mutexes in opposite order+# (fixed in 3.51.2, #10022). Gating only close() still deadlocks; opens must share the lock.+# Reentrant: a GC finalizer can close a pooled connection inside a gated connect on this thread.+_CONNECTION_GATE = threading.RLock()+++def _reset_connection_gate_after_fork() -> None:+ global _CONNECTION_GATE+ _CONNECTION_GATE = threading.RLock()+++if hasattr(os, "register_at_fork"):+ os.register_at_fork(after_in_child = _reset_connection_gate_after_fork)+++class _StudioDbConnection(sqlite3.Connection):+ # A connection dropped without close() is finalized natively and bypasses this gate.+ def close(self) -> None:+ with _CONNECTION_GATE:+ super().close()+++def connect_studio_db(database: str | os.PathLike[str], **kwargs: Any) -> sqlite3.Connection:+ """sqlite3.connect for studio.db, with opens and closes serialized process-wide."""+ with _CONNECTION_GATE:+ return sqlite3.connect(str(database), factory = _StudioDbConnection, **kwargs)++_SQLITE_IN_CHUNK_SIZE = 900_PROJECT_WORKSPACE_SUBDIRS = ("sandbox",)_CHAT_ATTACHMENT_INVENTORY_VERSION = 5@@ -1322,8 +1352,8 @@ def get_connection() -> sqlite3.Connection:db_path = studio_db_path()ensure_account_dir(db_path.parent)- conn = sqlite3.connect(- str(db_path), timeout = busy_timeout_seconds, check_same_thread = check_same_thread+ conn = connect_studio_db(+ db_path, timeout = busy_timeout_seconds, check_same_thread = check_same_thread)conn.row_factory = sqlite3.Row# foreign_keys is session-scoped; set per connectiondiff --git a/studio/backend/tests/test_studio_db_write_lock_contention.py b/studio/backend/tests/test_studio_db_write_lock_contention.pyindex a39bca92991..7c4c7a6390e 100644--- a/studio/backend/tests/test_studio_db_write_lock_contention.py+++ b/studio/backend/tests/test_studio_db_write_lock_contention.py@@ -192,6 +192,52 @@ def test_concurrent_openers_all_get_normal(db):assert results == [NORMAL] * 16+def test_studio_db_factories_serialize_connection_close(db, monkeypatch):+ """#10022: every studio.db opener shares one open/close gate (SQLite 3.51.0-3.51.1 deadlock)."""+ from storage import credential_secrets, library_db, mcp_servers_db, providers_db++ modules = (providers_db, mcp_servers_db, credential_secrets, library_db)+ for module in modules:+ monkeypatch.setattr(module, "studio_db_path", lambda db = db: db)+ monkeypatch.setattr(module, "_schema_ready", set())+ factories = [studio_db.get_connection] + [module.get_connection for module in modules]++ class TrackingLock:+ def __init__(self):+ self._lock = threading.Lock()+ self.active = self.maximum = self.entered = 0++ def __enter__(self):+ self._lock.acquire()+ self.active += 1+ self.entered += 1+ self.maximum = max(self.maximum, self.active)++ def __exit__(self, *exc):+ self.active -= 1+ self._lock.release()++ gate = TrackingLock()+ monkeypatch.setattr(studio_db, "_CONNECTION_GATE", gate)+ barrier = threading.Barrier(len(factories))+ errors = []++ def open_and_close(factory):+ try:+ conn = factory()+ barrier.wait(timeout = 5)+ conn.close()+ except BaseException as exc: # noqa: BLE001+ errors.append(exc)++ threads = [threading.Thread(target = open_and_close, args = (f,)) for f in factories]+ _shared_setup_1(threads)++ assert not errors, errors+ assert gate.entered >= 2 * len(factories)+ assert gate.maximum == 1++# --- the attachment inventory is dirtied by attachments, not by bookkeeping -------------