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.

1.9 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""Serializes every open and close: SQLite 3.51.0-3.51.1 deadlocks when a WAL close races another open"""

from __future__ import annotations

import os
import sqlite3
import threading
from typing import Any

# 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 GatedConnection(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(database: str | os.PathLike[str], **kwargs: Any) -> sqlite3.Connection:
    """sqlite3.connect with opens and closes serialized process-wide. A ``factory`` must subclass
    GatedConnection so its close stays gated."""
    kwargs.setdefault("factory", GatedConnection)
    with _CONNECTION_GATE:
        return sqlite3.connect(str(database), **kwargs)


def is_busy_error(exc: sqlite3.OperationalError) -> bool:
    """Writer lock held elsewhere, not a fault; the message is the only signal."""
    message = str(exc).lower()
    return "locked" in message or "busy" in message


def apply_wal_synchronous(conn: sqlite3.Connection) -> None:
    """Use synchronous=NORMAL only if WAL is really in force; journal_mode=WAL can silently decline."""
    try:
        mode = conn.execute("PRAGMA journal_mode").fetchone()[0]
    except (sqlite3.Error, TypeError, IndexError):
        return
    if isinstance(mode, str) and mode.lower() == "wal":
        conn.execute("PRAGMA synchronous=NORMAL")