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.

Studio: reuse one database connection per thread for durable chat generation runs (#11525)

Daniel Hand4a402b570a0
diff --git a/studio/backend/storage/chat_generation_runs_db.py b/studio/backend/storage/chat_generation_runs_db.py
index 5dd0f37c2dc..98868b7058b 100644
--- a/studio/backend/storage/chat_generation_runs_db.py
+++ b/studio/backend/storage/chat_generation_runs_db.py
@@ -11,10 +11,12 @@ import secrets
import sqlite3
import threading
import time
+import weakref
from pathlib import Path
from typing import Any, Iterable, Union
-from storage.studio_db import get_connection
+from storage.studio_db import get_connection, on_wal_keeper_closed
+from utils.account_context import current_account_id
from utils.paths import studio_db_path
ACTIVE_STATUSES = frozenset({"queued", "running", "cancelling"})
@@ -28,6 +30,170 @@ ChatGenerationEventInput = Union[tuple[str, dict[str, Any]], tuple[str, dict[str
_schema_ready: set[Path] = set()
_schema_lock = threading.Lock()
+# One reusable connection per (thread, account), because opening one costs far more than the query
+# it carries, and a streaming generation opens one per producer flush and three per SSE delivery
+# turn per attached tab. Keyed by the acting account: that is what selects the database, and unlike
+# resolving the path it costs nothing (see _connect).
+_pool = threading.local()
+
+
+class _PoolEntry:
+ """One thread's cached connection. A real object rather than a dict so it can be weak-referenced
+ and so its finalizer can close the connection when the owning thread goes away."""
+
+ __slots__ = ("key", "conn", "busy", "schema_ready", "generation", "_closer", "__weakref__")
+
+ def __init__(self, key: str, conn: sqlite3.Connection, schema_ready: Any, generation: int):
+ self.key = key
+ self.conn = conn
+ self.busy = True
+ self.schema_ready = schema_ready
+ self.generation = generation
+ # Runs when the last reference goes, which for a short-lived thread is when its thread-local
+ # storage is torn down.
+ self._closer = weakref.finalize(self, _close_quietly, conn)
+
+ def release(self) -> None:
+ """Close now, and disarm the finalizer so it cannot close it a second time."""
+ self._closer()
+
+
+class _Borrowed:
+ """A cached connection whose ``close()`` returns it to the cache instead of closing it.
+
+ Every caller already pairs ``_connect()`` with ``close()`` in a ``finally``, so honouring that
+ contract while keeping the handle open is what keeps reuse local instead of a rewrite of
+ fourteen call sites.
+ """
+
+ __slots__ = ("_conn", "_key", "_released")
+
+ def __init__(self, conn: sqlite3.Connection, key: str) -> None:
+ object.__setattr__(self, "_conn", conn)
+ object.__setattr__(self, "_key", key)
+ object.__setattr__(self, "_released", False)
+
+ def close(self) -> None:
+ if self._released:
+ return
+ object.__setattr__(self, "_released", True)
+ # Before the lock: while this borrow is out the handle belongs to this thread alone, and a
+ # connection left mid-transaction would hand its caller's work to the next borrower.
+ reusable = True
+ try:
+ if self._conn.in_transaction:
+ self._conn.rollback()
+ except Exception:
+ # The transaction is still open. Parking it would give the next borrower a handle whose
+ # BEGIN IMMEDIATE fails, or worse, let its commit carry this caller's uncommitted work.
+ reusable = False
+ park = False
+ with _pool_lock:
+ entry = getattr(_pool, "entry", None)
+ if entry is not None and entry.conn is self._conn:
+ if reusable and entry.generation == _pool_generation:
+ entry.busy = False
+ park = True
+ else:
+ # Invalidated while this borrow was out, or unusable after a failed rollback:
+ # either way releasing the file is what matters now.
+ _pool.entry = None
+ _unregister_locked(entry)
+ if not park:
+ self._conn.close()
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._conn, name)
+
+ def __setattr__(self, name: str, value: Any) -> None:
+ setattr(self._conn, name, value)
+
+
+#: Pooled entries, held WEAKLY: the sweeper reconciles on a FRESH daemon thread every 60s per
+#: account (_sweep_in_daemon_thread), so a strong registry would retain one open sqlite handle per
+#: sweep forever and exhaust the file descriptor limit.
+#:
+#: A registry at all because a thread retiring an account must close handles it does not own:
+#: retirement renames the account directory, and Windows refuses that while any file under it is
+#: open. Idle entries close here; one in use is left to its borrower.
+_pool_registry: list[weakref.ref[_PoolEntry]] = []
+_pool_generation = 0
+_pool_lock = threading.Lock()
+
+
+def _close_quietly(conn: sqlite3.Connection) -> None:
+ try:
+ conn.close()
+ except Exception:
+ pass
+
+
+def _live_entries_locked() -> list[_PoolEntry]:
+ """Every entry still alive, dropping refs whose thread has gone. Caller holds ``_pool_lock``."""
+ live: list[_PoolEntry] = []
+ surviving: list[weakref.ref[_PoolEntry]] = []
+ for ref in _pool_registry:
+ entry = ref()
+ if entry is not None:
+ live.append(entry)
+ surviving.append(ref)
+ _pool_registry[:] = surviving
+ return live
+
+
+def _unregister_locked(entry: _PoolEntry | None) -> None:
+ """Drop ``entry`` from the registry, and any reference whose thread has gone with it.
+
+ Pruning here and on insert keeps the list bounded. Not a weakref callback: those fire during
+ collection at an arbitrary point, including while this thread holds ``_pool_lock``, which is
+ not reentrant. Caller holds it.
+ """
+ surviving: list[weakref.ref[_PoolEntry]] = []
+ for ref in _pool_registry:
+ alive = ref()
+ if alive is None or alive is entry:
+ continue
+ surviving.append(ref)
+ _pool_registry[:] = surviving
+
+
+def _discard_pooled() -> None:
+ """Drop this thread's cached connection, for when it has errored or its database has gone."""
+ entry = getattr(_pool, "entry", None)
+ if entry is None:
+ return
+ _pool.entry = None
+ with _pool_lock:
+ _unregister_locked(entry)
+ entry.release()
+
+
+def _discard_all_pooled() -> None:
+ """Close every pooled connection on every thread, idle ones immediately.
+
+ The thread retiring an account is never the worker that parked the handle: the SSE loop waits
+ on a 32 thread pool of its own. One in use is left alone and closed by its borrower on return,
+ since yanking it would fail that caller's query.
+ """
+ global _pool_generation
+ with _pool_lock:
+ _pool_generation += 1
+ entries = _live_entries_locked()
+ _pool_registry.clear()
+ for entry in entries:
+ if entry.busy:
+ continue
+ entry.release()
+
+
+def reset_connection_pool_for_tests() -> None:
+ _discard_all_pooled()
+
+
+# Closing the keeper is meant to checkpoint the database and remove its -wal (#9934), and a pooled
+# connection outliving it would silently hold that open.
+on_wal_keeper_closed(_discard_all_pooled)
+
class ChatGenerationConflictError(RuntimeError):
pass
@@ -38,6 +204,10 @@ def now_ms() -> int:
def reset_schema_state_for_tests() -> None:
+ # The pool goes with it. The suite gives each test its own UNSLOTH_STUDIO_HOME and deletes the
+ # last one, so a cached handle to a database that has been removed underneath it is the one way
+ # reuse could leak across tests.
+ _discard_all_pooled()
with _schema_lock:
_schema_ready.clear()
@@ -49,11 +219,87 @@ def _database_path(conn: sqlite3.Connection) -> Path:
def _connect() -> sqlite3.Connection:
- """get_connection plus the one-off progress-lease migration for this database."""
- conn = get_connection()
+ """get_connection plus the one-off progress-lease migration for this database.
+
+ Returns this thread's cached connection when there is one for the database the acting account
+ resolves to right now. Falls back to a fresh connection whenever reuse would be unsafe, so the
+ cache can only ever make things faster, never change what a caller sees.
+ """
+ # NOT the resolved path: test_a_durable_run_poll_resolves_the_account_root_once and
+ # test_warm_owner_connections_do_not_resolve_database_again pin that a warm connect resolves the
+ # account root zero times, and studio_db_path() is exactly that resolution.
+ #
+ # Paired with the identity of _schema_ready, which conftest rebinds per test: an account id
+ # alone cannot see a home that moved beneath it.
+ key = current_account_id() or ""
+ reuse = None
+ superseded = None
+ # Under the lock: read the generation outside it and an invalidator can see this entry as idle
+ # between the check and the busy flip, close it, and leave the borrow holding a dead handle.
+ # Retirement invalidates every account's pool, so that aborts unrelated live generations.
+ with _pool_lock:
+ generation_before = _pool_generation
+ entry = getattr(_pool, "entry", None)
+ if entry is not None and entry.generation != _pool_generation:
+ # Invalidated while this thread was elsewhere; _discard_all_pooled already closed it.
+ _pool.entry = None
+ entry = None
+ if entry is not None and not entry.busy:
+ if entry.key == key and entry.schema_ready is _schema_ready:
+ entry.busy = True
+ reuse = entry.conn
+ else:
+ # A different account, or a home that moved beneath this one. Either way the cached
+ # handle points at a database this caller must not be given.
+ superseded = entry.conn
+ _unregister_locked(entry)
+ _pool.entry = None
+ entry = None if reuse is None else entry
+ if reuse is not None:
+ return _Borrowed(reuse, key)
+ if superseded is not None:
+ try:
+ superseded.close()
+ except Exception:
+ pass
+ entry = None
+
+ conn, migrated = _prepare_connection()
+ # An unmigrated connection is never pooled, so the next call runs _prepare_connection again and
+ # the retry this contention path exists for still happens.
+ #
+ # A nested _connect() on one thread (a borrowed handle is already out) also keeps the old
+ # behaviour of its own connection: sharing one would put two callers in one transaction.
+ if entry is None and migrated:
+ with _pool_lock:
+ # Fenced on the generation read BEFORE preparing: opening a connection takes long
+ # enough for an invalidation to land, and this handle is not in the registry yet to be
+ # caught by it. Registering it under the new generation would hide it from the
+ # invalidator that retirement just ran, and the uncached path always closed.
+ if _pool_generation == generation_before:
+ entry = _PoolEntry(key, conn, _schema_ready, generation_before)
+ _pool.entry = entry
+ # Drops references left by threads that have since exited, so a server that
+ # reconciles on a fresh daemon thread every minute does not grow this list without
+ # bound and make every later scan longer.
+ _unregister_locked(None)
+ _pool_registry.append(weakref.ref(entry))
+ return _Borrowed(conn, key)
+ return conn
+
+
+def _prepare_connection() -> tuple[sqlite3.Connection, bool]:
+ """The original, uncached body, plus whether the lease migration is done for this database.
+
+ The flag keeps a blocked migration retryable: when the ALTER loses to another writer this
+ returns without marking the path ready so the NEXT call retries, and caching such a connection
+ would skip that call forever, leaving the lease columns missing and reconcile_runs reaping
+ nothing.
+ """
+ conn = get_connection(check_same_thread = False)
db_path = _database_path(conn)
if db_path in _schema_ready:
- return conn
+ return conn, True
try:
with _schema_lock:
schema_path = db_path.resolve()
@@ -83,7 +329,7 @@ def _connect() -> sqlite3.Connection:
except Exception:
conn.close()
raise
- return conn
+ return conn, db_path.resolve() in _schema_ready
def _loads(value: str | None, fallback: Any) -> Any:
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 406f25c7002..b83d4fcb0b8 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -20,7 +20,7 @@ from datetime import datetime, timezone
from pathlib import Path
logger = logging.getLogger(__name__)
-from typing import Any, Iterable, Optional
+from typing import Any, Callable, Iterable, Optional
from utils.account_context import is_owner_context
@@ -1308,12 +1308,33 @@ def _close_keeper(conn: sqlite3.Connection) -> None:
logger.warning("Could not close the studio.db WAL keeper: %s", exc)
+#: Called when a keeper is closed, so modules holding their own long-lived connections can drop
+#: them too. Closing the keeper is meant to leave the database checkpointed and its -wal gone
+#: (#9934), and any other open connection silently prevents that.
+_keeper_close_listeners: list[Callable[[], None]] = []
+
+
+def on_wal_keeper_closed(listener: Callable[[], None]) -> None:
+ _keeper_close_listeners.append(listener)
+
+
+def _notify_keeper_closed() -> None:
+ for listener in tuple(_keeper_close_listeners):
+ try:
+ listener()
+ except Exception:
+ logger.warning("A WAL keeper close listener failed", exc_info = True)
+
+
def close_wal_keeper_for(path: str | Path) -> None:
db_path = Path(path).resolve()
with _wal_keeper_lock:
conn = _wal_keepers.pop(db_path, None)
if conn is not None:
_close_keeper(conn)
+ # Unconditionally: journal_mode=WAL declines on filesystems without shared memory, so those
+ # installs never have a keeper to close, and the caller still means "let go of this database".
+ _notify_keeper_closed()
def close_wal_keeper() -> None:
@@ -1322,6 +1343,7 @@ def close_wal_keeper() -> None:
_close_keeper(conn)
_wal_keepers.clear()
_wal_unsupported.clear()
+ _notify_keeper_closed()
def create_run(
diff --git a/studio/backend/tests/test_chat_generation_lease_compat.py b/studio/backend/tests/test_chat_generation_lease_compat.py
index 0fe6df3a16a..26a82c50209 100644
--- a/studio/backend/tests/test_chat_generation_lease_compat.py
+++ b/studio/backend/tests/test_chat_generation_lease_compat.py
@@ -201,7 +201,7 @@ def test_duplicate_column_error_is_swallowed(clock, monkeypatch):
def __getattr__(self, name):
return getattr(self._inner, name)
- monkeypatch.setattr(runs_db, "get_connection", lambda: _Racy(real_get()))
+ monkeypatch.setattr(runs_db, "get_connection", lambda **kw: _Racy(real_get(**kw)))
runs_db._connect() # must not raise
assert state["fired"], "the simulated race did not fire"
@@ -385,7 +385,7 @@ def _migration_blocked(monkeypatch):
def __getattr__(self, name):
return getattr(self._inner, name)
- monkeypatch.setattr(runs_db, "get_connection", lambda: _Locked(real_get()))
+ monkeypatch.setattr(runs_db, "get_connection", lambda **kw: _Locked(real_get(**kw)))
try:
yield
finally:
@@ -460,7 +460,7 @@ def test_a_real_no_such_column_error_is_not_swallowed(clock, monkeypatch):
def __getattr__(self, name):
return getattr(self._inner, name)
- monkeypatch.setattr(runs_db, "get_connection", lambda: _Boom(real_get()))
+ monkeypatch.setattr(runs_db, "get_connection", lambda **kw: _Boom(real_get(**kw)))
with pytest.raises(sqlite3.OperationalError, match = "some_other_column"):
runs_db.get_progress("run-1")
diff --git a/studio/backend/tests/test_chat_generation_runs_pool.py b/studio/backend/tests/test_chat_generation_runs_pool.py
new file mode 100644
index 00000000000..9e467a674be
--- /dev/null
+++ b/studio/backend/tests/test_chat_generation_runs_pool.py
@@ -0,0 +1,445 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""The reused connection behind the durable-run write path.
+
+Opening a connection costs ~50x what the query costs, so this module keeps one per thread per
+database. These are the properties that make that safe to do; each fails if the reuse in
+``chat_generation_runs_db._connect`` is removed or mis-keyed.
+"""
+
+import gc
+import sqlite3
+import threading
+
+import pytest
+
+from storage import chat_generation_runs_db as runs_db
+from storage import studio_db
+from utils.account_context import OWNER, AccountContext, run_as
+from utils.paths import storage_roots as roots
+
+ALICE = AccountContext("11111111111111111111111111111111", "alice")
+BOB = AccountContext("22222222222222222222222222222222", "bob")
+
+
[email protected](autouse = True)
+def _isolated_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ studio_db.close_wal_keeper()
+ runs_db.reset_connection_pool_for_tests()
+ studio_db.reset_schema_state_for_tests()
+ runs_db.reset_schema_state_for_tests()
+ yield
+ runs_db.reset_connection_pool_for_tests()
+
+
+def test_one_thread_reuses_a_single_connection_for_the_same_database():
+ first = runs_db._connect()
+ underlying = first._conn
+ first.close()
+ second = runs_db._connect()
+ try:
+ assert second._conn is underlying
+ finally:
+ second.close()
+
+
+def test_a_borrowed_connection_is_usable_after_being_returned():
+ conn = runs_db._connect()
+ conn.close()
+ again = runs_db._connect()
+ try:
+ assert again.execute("SELECT 1").fetchone()[0] == 1
+ finally:
+ again.close()
+
+
+def test_a_nested_borrow_gets_its_own_connection():
+ """Two live borrows on one thread must not share a handle: BEGIN IMMEDIATE on a connection
+ already inside a transaction raises, and one caller's rollback would discard the other's work."""
+ outer = runs_db._connect()
+ inner = runs_db._connect()
+ try:
+ assert getattr(inner, "_conn", inner) is not outer._conn
+ finally:
+ inner.close()
+ outer.close()
+
+
+def test_an_unfinished_transaction_is_rolled_back_before_reuse():
+ conn = runs_db._connect()
+ conn.execute("BEGIN IMMEDIATE")
+ assert conn.in_transaction
+ conn.close()
+ nxt = runs_db._connect()
+ try:
+ # A handle still inside a transaction would fail here, or worse, silently adopt it.
+ assert not nxt.in_transaction
+ nxt.execute("BEGIN IMMEDIATE")
+ nxt.rollback()
+ finally:
+ nxt.close()
+
+
+def test_two_accounts_never_share_a_cached_connection():
+ """Two accounts resolve to two databases, so a handle cached under one account id must never be
+ handed to the other."""
+ paths = {}
+ handles = {}
+ for account in (ALICE, BOB):
+
+ def grab(account = account):
+ conn = runs_db._connect()
+ paths[account.account_id] = roots.studio_db_path().resolve()
+ handles[account.account_id] = conn._conn
+ conn.close()
+
+ run_as(account, grab)
+
+ assert paths[ALICE.account_id] != paths[BOB.account_id]
+ assert handles[ALICE.account_id] is not handles[BOB.account_id]
+
+
+def test_switching_account_does_not_write_to_the_previous_database():
+ """The sharpest form of the isolation risk: a stale handle would send Bob's row to Alice."""
+
+ def write(marker):
+ conn = runs_db._connect()
+ try:
+ conn.execute("CREATE TABLE IF NOT EXISTS pool_probe (marker TEXT)")
+ conn.execute("INSERT INTO pool_probe (marker) VALUES (?)", (marker,))
+ conn.commit()
+ finally:
+ conn.close()
+
+ def read():
+ conn = runs_db._connect()
+ try:
+ return [row[0] for row in conn.execute("SELECT marker FROM pool_probe").fetchall()]
+ finally:
+ conn.close()
+
+ run_as(ALICE, lambda: write("alice"))
+ run_as(BOB, lambda: write("bob"))
+ assert run_as(ALICE, read) == ["alice"]
+ assert run_as(BOB, read) == ["bob"]
+
+
+def test_each_thread_gets_its_own_connection():
+ """sqlite connections here are created with check_same_thread = True, so a handle shared
+ across threads would raise ProgrammingError on use."""
+ seen = {}
+
+ def grab(name):
+ conn = runs_db._connect()
+ seen[name] = getattr(conn, "_conn", conn)
+ conn.execute("SELECT 1").fetchone()
+ conn.close()
+
+ threads = [threading.Thread(target = grab, args = (name,)) for name in ("a", "b")]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert seen["a"] is not seen["b"]
+
+
+def test_rebinding_schema_ready_drops_the_pooled_connection(monkeypatch):
+ """conftest's _isolate_studio_home rebinds _schema_ready per test. An account id alone cannot
+ see a home that moved beneath it, so the pool keys on that object's identity too."""
+ conn = runs_db._connect()
+ underlying = conn._conn
+ conn.close()
+ monkeypatch.setattr(runs_db, "_schema_ready", set())
+ fresh = runs_db._connect()
+ try:
+ assert fresh._conn is not underlying
+ finally:
+ fresh.close()
+
+
+def test_resetting_schema_state_drops_the_pooled_connection():
+ """reset_schema_state_for_tests is the explicit hook, used by tests that swap homes directly."""
+ conn = runs_db._connect()
+ underlying = conn._conn
+ conn.close()
+ runs_db.reset_schema_state_for_tests()
+ with pytest.raises(sqlite3.ProgrammingError):
+ underlying.execute("SELECT 1")
+
+
+def test_append_events_still_persists_through_a_reused_connection():
+ studio_db.upsert_chat_thread(
+ {"id": "t", "title": "Chat", "modelType": "base", "modelId": "local", "createdAt": 1}
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": "u",
+ "threadId": "t",
+ "role": "user",
+ "content": [{"type": "text", "text": "x"}],
+ "createdAt": 2,
+ }
+ )
+ runs_db.create_run(
+ run_id = "r",
+ owner_subject = "alice",
+ thread_id = "t",
+ user_message_id = "u",
+ assistant_message_id = "a",
+ request_payload = {"model": "local", "messages": [], "stream": True},
+ )
+ token = runs_db.get_worker_token("r")
+ runs_db.mark_running("r", token)
+ chunk = ("chunk", {"choices": [{"delta": {"content": "hi "}, "index": 0}]})
+ for _ in range(5):
+ runs_db.append_events("r", token, [chunk] * 3)
+ assert len(runs_db.list_events("r", 0)) >= 15
+
+
+def test_an_idle_connection_on_another_LIVE_thread_is_closed_by_a_global_discard():
+ """Account retirement renames the account directory from a request thread, while the SSE loop
+ parks its connections on a 32 thread pool of its own. Windows refuses the rename while any file
+ underneath is open, so an idle handle on a worker that is still alive has to be closed from
+ here. The worker is held alive deliberately: a thread that exits releases its own entry."""
+ parked = {}
+ parked_ready = threading.Event()
+ may_exit = threading.Event()
+
+ def park():
+ conn = runs_db._connect()
+ parked["conn"] = conn._conn
+ conn.close()
+ parked_ready.set()
+ may_exit.wait(timeout = 30)
+
+ worker = threading.Thread(target = park)
+ worker.start()
+ try:
+ assert parked_ready.wait(timeout = 30)
+ assert parked["conn"].execute("SELECT 1").fetchone()[0] == 1
+
+ runs_db._discard_all_pooled()
+ with pytest.raises(sqlite3.ProgrammingError):
+ parked["conn"].execute("SELECT 1")
+ finally:
+ may_exit.set()
+ worker.join(timeout = 30)
+
+
+def test_a_short_lived_threads_connection_is_released_when_it_exits():
+ """The lease sweeper reconciles each account on a FRESH daemon thread every 60 seconds
+ (_sweep_in_daemon_thread). Its pooled entry can never be borrowed again once that thread is
+ gone, so holding it strongly would leak one sqlite handle per sweep until the process runs out
+ of file descriptors. The registry is weak, and the entry closes its connection when collected.
+ """
+ parked = {}
+
+ def park():
+ conn = runs_db._connect()
+ parked["conn"] = conn._conn
+ conn.close()
+
+ worker = threading.Thread(target = park)
+ worker.start()
+ worker.join(timeout = 30)
+
+ gc.collect()
+ with pytest.raises(sqlite3.ProgrammingError):
+ parked["conn"].execute("SELECT 1")
+
+ with runs_db._pool_lock:
+ alive = [ref for ref in runs_db._pool_registry if ref() is not None]
+ assert alive == [], "a dead thread must leave nothing behind in the registry"
+
+
+def test_closing_the_keeper_drops_the_pool_even_when_there_was_no_keeper():
+ """journal_mode=WAL declines on filesystems without shared memory, so those installs never have
+ a keeper. Retirement still calls close_wal_keeper_for and still needs the handle released."""
+ studio_db.close_wal_keeper()
+ conn = runs_db._connect()
+ underlying = conn._conn
+ conn.close()
+ assert studio_db._wal_keepers == {}, "no keeper should be held for this test to mean anything"
+
+ studio_db.close_wal_keeper_for(studio_db.studio_db_path())
+ with pytest.raises(sqlite3.ProgrammingError):
+ underlying.execute("SELECT 1")
+
+
+def test_a_connection_in_use_during_a_global_discard_is_closed_on_return():
+ """Yanking a handle mid query would fail that caller, so the borrower closes it instead of
+ parking it back into a pool that has moved on."""
+ borrowed = runs_db._connect()
+ underlying = borrowed._conn
+ runs_db._discard_all_pooled()
+ assert underlying.execute("SELECT 1").fetchone()[0] == 1, "an in-use handle must survive"
+ borrowed.close()
+ with pytest.raises(sqlite3.ProgrammingError):
+ underlying.execute("SELECT 1")
+
+
+def test_borrowing_races_a_global_discard_without_handing_out_a_closed_handle():
+ """Retirement invalidates every account's pool from an unrelated thread.
+
+ The interleaving is forced rather than hoped for: the entry's key compares equal via a probe
+ that, mid-comparison, lets another thread run _discard_all_pooled. That comparison sits between
+ the generation check and the idle-to-busy transition. Holding _pool_lock across both makes the
+ other thread block until the borrow is marked busy, so the handle survives; without the lock it
+ is closed underneath the borrow and the next query raises ProgrammingError, aborting a live
+ generation belonging to an account nobody deleted.
+ """
+ primed = runs_db._connect()
+ underlying = primed._conn
+ primed.close()
+
+ entry = runs_db._pool.entry
+ assert entry is not None and not entry.busy, "an idle pooled entry is the precondition"
+
+ invalidated = threading.Event()
+
+ def invalidate():
+ runs_db._discard_all_pooled()
+ invalidated.set()
+
+ class _KeyProbe(str):
+ def __eq__(self, other):
+ worker = threading.Thread(target = invalidate)
+ worker.start()
+ # Long enough that an unlocked borrow really does lose the handle, short enough that the
+ # locked one is not slowed: with the lock held the worker cannot get past its acquire.
+ worker.join(timeout = 2.0)
+ return str(self) == str(other)
+
+ def __hash__(self):
+ return str.__hash__(self)
+
+ entry.key = _KeyProbe(entry.key)
+
+ borrowed = runs_db._connect()
+ try:
+ assert borrowed.execute("SELECT 1").fetchone()[0] == 1
+ finally:
+ borrowed.close()
+ invalidated.wait(timeout = 10)
+ assert underlying is not None
+
+
+def test_a_connection_whose_migration_lost_the_lock_is_not_pooled():
+ """_prepare_connection deliberately returns without marking the path ready when the ALTER loses
+ to another writer, so the NEXT call retries. Caching such a connection would skip that next call
+ for the life of the thread: the lease columns would stay missing, progress updates would keep
+ degrading, and reconcile_runs(stale_after_ms=...) would keep reaping nothing."""
+ runs_db.reset_connection_pool_for_tests()
+ runs_db.reset_schema_state_for_tests()
+
+ real_prepare = runs_db._prepare_connection
+ calls = {"n": 0}
+
+ def blocked():
+ conn, _ready = real_prepare()
+ calls["n"] += 1
+ return conn, False
+
+ runs_db._prepare_connection = blocked
+ try:
+ first = runs_db._connect()
+ first.close()
+ second = runs_db._connect()
+ second.close()
+ assert (
+ calls["n"] == 2
+ ), "an unmigrated connection must not be reused; the retry is the point"
+ finally:
+ runs_db._prepare_connection = real_prepare
+ runs_db.reset_connection_pool_for_tests()
+
+ # And once it does complete, pooling resumes.
+ third = runs_db._connect()
+ underlying = third._conn
+ third.close()
+ fourth = runs_db._connect()
+ try:
+ assert fourth._conn is underlying
+ finally:
+ fourth.close()
+
+
+def test_a_handle_prepared_across_an_invalidation_is_not_pooled():
+ """_prepare_connection opens a real connection, so an invalidation can land while it runs, and
+ the new handle is not in the registry yet to be caught by it. Registering it under the new
+ generation would make a connection the invalidator meant to close look freshly pooled, and
+ retirement renames the account roots immediately after invalidating. The uncached path always
+ closed, so leaving this one open would be a regression rather than an inherited gap."""
+ runs_db.reset_connection_pool_for_tests()
+ real_prepare = runs_db._prepare_connection
+
+ def prepare_then_invalidate():
+ conn, migrated = real_prepare()
+ # Exactly the window: prepared, not yet registered.
+ runs_db._discard_all_pooled()
+ return conn, migrated
+
+ runs_db._prepare_connection = prepare_then_invalidate
+ try:
+ borrowed = runs_db._connect()
+ underlying = getattr(borrowed, "_conn", borrowed)
+ borrowed.close()
+ finally:
+ runs_db._prepare_connection = real_prepare
+
+ assert runs_db._pool_registry == [], "a handle raced by invalidation must not be pooled"
+ with pytest.raises(sqlite3.ProgrammingError):
+ underlying.execute("SELECT 1")
+
+
+def test_the_registry_does_not_grow_with_every_short_lived_thread():
+ """The sweeper adds a pooled entry per account per minute on a fresh daemon thread. The entry
+ itself is collected, but a dead weakref left behind would accumulate for the life of the
+ process and lengthen every later scan. Insert and unregister prune."""
+ runs_db.reset_connection_pool_for_tests()
+
+ def park():
+ conn = runs_db._connect()
+ conn.close()
+
+ for _ in range(25):
+ worker = threading.Thread(target = park)
+ worker.start()
+ worker.join(timeout = 30)
+
+ gc.collect()
+ with runs_db._pool_lock:
+ depth = len(runs_db._pool_registry)
+ assert depth <= 2, f"registry grew to {depth} entries across 25 short-lived threads"
+
+
+def test_a_handle_whose_rollback_failed_is_discarded_rather_than_parked():
+ """If rollback raises, the transaction is still open. Parking that handle would hand the next
+ borrower a connection whose BEGIN IMMEDIATE fails, or let its commit carry the previous
+ caller's uncommitted work."""
+ runs_db.reset_connection_pool_for_tests()
+ borrowed = runs_db._connect()
+ underlying = borrowed._conn
+
+ class _StuckInTransaction:
+ def __getattr__(self, name):
+ return getattr(underlying, name)
+
+ @property
+ def in_transaction(self):
+ return True
+
+ def rollback(self):
+ raise sqlite3.OperationalError("disk I/O error")
+
+ object.__setattr__(borrowed, "_conn", _StuckInTransaction())
+ runs_db._pool.entry.conn = borrowed._conn
+ borrowed.close()
+
+ with runs_db._pool_lock:
+ alive = [ref for ref in runs_db._pool_registry if ref() is not None]
+ assert alive == [], "a handle whose rollback failed must not stay in the pool"
+ assert getattr(runs_db._pool, "entry", None) is None
+ runs_db.reset_connection_pool_for_tests()