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.

Stop one slow SQLite writer from becoming a stream of Studio log errors (#9996)

Daniel Han2ea71d217650
diff --git a/studio/backend/core/research_runs.py b/studio/backend/core/research_runs.py
index 13f264d223c..6a5fcff4d80 100644
--- a/studio/backend/core/research_runs.py
+++ b/studio/backend/core/research_runs.py
@@ -56,7 +56,12 @@ from core.research.prompts import (
)
from loggers import get_logger
from storage import research_runs_db as db
-from storage.studio_db import get_chat_message, list_chat_messages, upsert_chat_message
+from storage.studio_db import (
+ get_chat_message,
+ is_sqlite_busy_error,
+ list_chat_messages,
+ upsert_chat_message,
+)
logger = get_logger(__name__)
_URL_BLOCK = re.compile(
@@ -1116,6 +1121,16 @@ class ResearchSupervisor:
await self._process(run)
except asyncio.CancelledError:
raise
+ except sqlite3.OperationalError as exc:
+ # Losing the writer lock is normal for polling, not a fault, and produced
+ # six tracebacks in one session. Only that case is quietened. Neither may
+ # re-raise: that escapes the while loop and stops the supervisor for the
+ # life of the process, and the sibling `except Exception` cannot catch it.
+ if is_sqlite_busy_error(exc):
+ logger.warning("research.supervisor_db_busy: %s", exc)
+ else:
+ logger.exception("research.supervisor_iteration_failed")
+ await asyncio.sleep(1)
except Exception:
logger.exception("research.supervisor_iteration_failed")
await asyncio.sleep(1)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index ee9676a5e2c..91c021ee7e9 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -1407,6 +1407,9 @@ app.add_middleware(
allow_credentials = True,
allow_methods = ["*"],
allow_headers = ["*"],
+ # allow_headers is the REQUEST side; a response header is unreadable to JS unless
+ # exposed, and Studio is cross-origin from tauri://localhost and tunnels.
+ expose_headers = ["X-Unsloth-Conflict-Kind"],
# is_allowed_origin closes the moment the tunnel URL clears, but a preflight
# already cached by the browser does not. Measured in WebKit: with Starlette's
# 600s default, a state-changing request still REACHED the server after remote
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 066bdcc9672..cb0fe5a9061 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -582,6 +582,17 @@ class ChatImportLedgerRecordResponse(BaseModel):
inserted: int
+# Both conflicts are 409 and mean opposite things: protected means stop resending, a thread
+# collision means surface the failure. In a header, not the body, so `detail` stays a plain
+# string for existing clients; main.py must expose it for a cross-origin Studio to read it.
+CONFLICT_KIND_HEADER = "X-Unsloth-Conflict-Kind"
+
+
+def _conflict_headers(exc: Exception) -> dict:
+ kind = "protected" if isinstance(exc, ChatMessageProtectedError) else "thread-collision"
+ return {CONFLICT_KIND_HEADER: kind}
+
+
@router.get("/threads", response_model = ChatThreadListResponse)
def list_threads(
model_type: Optional[str] = Query(None),
@@ -1031,6 +1042,7 @@ def delete_attachment(
safe_curated_detail(exc),
event = "chat_history.delete_attachment_conflict",
log = logger,
+ headers = _conflict_headers(exc),
) from exc
if not deleted:
raise HTTPException(status_code = 404, detail = "Attachment not found")
@@ -1351,6 +1363,7 @@ def save_thread_message(
safe_curated_detail(exc),
event = "chat_history.save_message_conflict",
log = logger,
+ headers = _conflict_headers(exc),
) from exc
@@ -1394,6 +1407,7 @@ def replace_thread_messages(
safe_curated_detail(exc),
event = "chat_history.replace_messages_conflict",
log = logger,
+ headers = _conflict_headers(exc),
) from exc
diff --git a/studio/backend/storage/api_usage_db.py b/studio/backend/storage/api_usage_db.py
index 62958b7b6f4..d022929248c 100644
--- a/studio/backend/storage/api_usage_db.py
+++ b/studio/backend/storage/api_usage_db.py
@@ -15,7 +15,7 @@ import uuid
from dataclasses import dataclass
from typing import Callable, Optional
-from storage.studio_db import get_connection
+from storage.studio_db import get_connection, is_sqlite_busy_error
# Kept aligned with the API monitor's defensive upper bound. The storage layer
@@ -94,8 +94,8 @@ def canonical_api_model(model: object) -> str:
def _is_busy_error(exc: sqlite3.OperationalError) -> bool:
- message = str(exc).lower()
- return "locked" in message or "busy" in message
+ # One definition, in the module that owns the contended file.
+ return is_sqlite_busy_error(exc)
def _sleep_after_busy(delay: float) -> None:
diff --git a/studio/backend/storage/research_runs_db.py b/studio/backend/storage/research_runs_db.py
index 24a7a74e83b..34b6a05ebf5 100644
--- a/studio/backend/storage/research_runs_db.py
+++ b/studio/backend/storage/research_runs_db.py
@@ -859,7 +859,33 @@ def retry(run_id: str, max_retries: int = 3) -> str:
conn.close()
+_CLAIMABLE_SQL = """SELECT r.id FROM research_runs r
+ JOIN research_thread_claims c ON c.thread_id=r.thread_id
+ WHERE r.owner_subject=c.owner_subject
+ AND r.status IN ('planning','queued','running','cancelling')
+ AND (r.lease_owner IS NULL OR r.lease_expires_at < ?)
+ LIMIT 1"""
+
+
+def _has_claimable(now: int) -> bool:
+ """Read-only probe for claimable work, taking no write lock.
+
+ The supervisor polls twice a second forever and almost every poll finds nothing, so
+ opening BEGIN IMMEDIATE first meant an idle Studio held the writer lock 2x/second and
+ any slow writer elsewhere became a stream of "database is locked" here.
+ """
+ conn = get_connection()
+ try:
+ return conn.execute(_CLAIMABLE_SQL, (now,)).fetchone() is not None
+ finally:
+ conn.close()
+
+
def claim_next(worker_id: str, lease_ms: int = 120_000) -> dict | None:
+ # Advisory only: the row can disappear between this probe and the transaction below,
+ # which the "row is None" branch inside already handles.
+ if not _has_claimable(now_ms()):
+ return None
conn = get_connection()
try:
conn.execute("BEGIN IMMEDIATE")
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 5e39b899e1f..f7a0350e550 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -266,6 +266,48 @@ def delete_chat_project_workspace(project: dict) -> None:
delete_project_workspace(project)
+_INVENTORY_UPDATE_TRIGGER = "chat_attachment_inventory_dirty_update"
+
+_INVENTORY_UPDATE_TRIGGER_SQL = f"""
+ CREATE TRIGGER IF NOT EXISTS {_INVENTORY_UPDATE_TRIGGER}
+ AFTER UPDATE OF attachments_json, content_json ON chat_messages
+ BEGIN
+ INSERT INTO chat_attachment_inventory_state
+ (singleton, inventory_version, dirty, backfilled_at)
+ VALUES (1, 0, 1, 0)
+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;
+ END
+"""
+
+
+def _replace_inventory_update_trigger(conn: sqlite3.Connection) -> None:
+ """Swap the unscoped trigger for the scoped one, safely for concurrent openers.
+
+ DDL does not open a transaction under sqlite3's legacy transaction control, only DML
+ does, so a bare DROP + CREATE pair can interleave across processes as
+ drop/drop/create/create and the second CREATE raises out of `get_connection`. Hence:
+ skip when already scoped, hold the writer lock across the pair, IF NOT EXISTS on top.
+ """
+ row = conn.execute(
+ "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?",
+ (_INVENTORY_UPDATE_TRIGGER,),
+ ).fetchone()
+ # row[0], not row["sql"]: _ensure_schema also runs on connections whose row_factory
+ # is still the default tuple.
+ if row is not None and "UPDATE OF" in (row[0] or ""):
+ return
+ if conn.in_transaction:
+ conn.commit()
+ conn.execute("BEGIN IMMEDIATE")
+ try:
+ conn.execute(f"DROP TRIGGER IF EXISTS {_INVENTORY_UPDATE_TRIGGER}")
+ conn.execute(_INVENTORY_UPDATE_TRIGGER_SQL)
+ conn.commit()
+ except BaseException:
+ conn.rollback()
+ raise
+
+
def _ensure_schema(conn: sqlite3.Connection) -> None:
"""Create tables and indexes if they don't exist. Called once per process."""
conn.execute("PRAGMA journal_mode=WAL")
@@ -603,18 +645,10 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
END
"""
)
- conn.execute(
- """
- CREATE TRIGGER IF NOT EXISTS chat_attachment_inventory_dirty_update
- AFTER UPDATE ON chat_messages
- BEGIN
- INSERT INTO chat_attachment_inventory_state
- (singleton, inventory_version, dirty, backfilled_at)
- VALUES (1, 0, 1, 0)
- ON CONFLICT(singleton) DO UPDATE SET dirty = 1;
- END
- """
- )
+ # Scoped to the columns _rebuild_chat_attachment_inventory reads: unscoped, a generation
+ # status change (metadata_json only) dirtied the inventory, so the next autosave re-hashed
+ # every attachment under the writer lock. Dropped, since a create would keep the old one.
+ _replace_inventory_update_trigger(conn)
conn.execute(
"""
CREATE TRIGGER IF NOT EXISTS chat_attachment_inventory_dirty_delete
@@ -1157,6 +1191,17 @@ def bulk_upsert_prompt_lists(lists: list[dict]) -> int:
conn.close()
+def is_sqlite_busy_error(exc: sqlite3.OperationalError) -> bool:
+ """Is this the writer lock being held elsewhere, rather than a real fault?
+
+ sqlite reports it as plain OperationalError, so the message is the only signal.
+ Lives here because studio.db is the contended file and several modules need the
+ same answer; storage.api_usage_db delegates to it.
+ """
+ message = str(exc).lower()
+ return "locked" in message or "busy" in message
+
+
# sqlite's own default, kept for every caller that may run on the event loop
_BUSY_TIMEOUT_SECONDS = 5.0
@@ -1165,6 +1210,32 @@ _BUSY_TIMEOUT_SECONDS = 5.0
_CONTENDED_BUSY_TIMEOUT_SECONDS = 30.0
+def _apply_wal_synchronous(conn: sqlite3.Connection) -> None:
+ """Drop to synchronous=NORMAL, but only while the file is really in WAL mode.
+
+ Under WAL, sqlite still defaults to synchronous=FULL, which fsyncs on every commit
+ while holding the writer lock. On a machine whose disk is busy -- a Colab session
+ pulling a multi-GB GGUF, say -- one commit blocked for 37s, and every other writer
+ (notably the research supervisor's claim_next) spent that whole window timing out
+ with "database is locked". NORMAL is sqlite's own recommended pairing for WAL: it
+ can lose the last transactions to a host power loss, but the database is never
+ corrupted, and commits stay durable across an application crash either way.
+
+ The WAL check is not decoration. `PRAGMA journal_mode=WAL` silently declines on
+ filesystems without proper shared-memory support (network shares, some FUSE and
+ container-mounted paths, which Windows users hit most often), leaving the file on a
+ rollback journal where NORMAL drops the very fsync that keeps it consistent. Those
+ installs keep FULL and simply do not get the speedup. journal_mode is persistent in
+ the file, so this reads what is actually in force rather than what was requested.
+ """
+ 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")
+
+
def get_connection(busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS) -> sqlite3.Connection:
"""Open studio.db with WAL mode, create tables once per process, enable foreign keys."""
global _schema_ready
@@ -1184,6 +1255,7 @@ def get_connection(busy_timeout_seconds: float = _BUSY_TIMEOUT_SECONDS) -> sqlit
except Exception:
conn.close()
raise
+ _apply_wal_synchronous(conn)
return conn
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index 260db1b522b..9a2dbf479a1 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -11,6 +11,7 @@ import threading
from types import SimpleNamespace
import pytest
+from typing import Optional
from fastapi import HTTPException
from pydantic import ValidationError
@@ -1295,3 +1296,48 @@ def test_a_plain_replay_with_nothing_outstanding_still_reaps_nothing(monkeypatch
assert len(reaps) == 1
clear()
assert len(reaps) == 1, "a replay behind a completed reap must not touch the registry"
+
+
+def _conflict_kind(exc_info) -> Optional[str]:
+ return (exc_info.value.headers or {}).get(chat_history.CONFLICT_KIND_HEADER)
+
+
+ "error, kind",
+ [
+ (
+ lambda: chat_history.ChatMessageProtectedError(
+ "server-managed generation messages cannot be edited"
+ ),
+ "protected",
+ ),
+ (
+ lambda: chat_history.ChatMessageConflictError(
+ "Message id already belongs to another thread: m1"
+ ),
+ "thread-collision",
+ ),
+ ],
+)
+def test_the_two_conflicts_are_distinguishable_on_the_wire(monkeypatch, error, kind):
+ """Both are 409, and they mean opposite things to the client.
+
+ A protected message is the server refusing an edit it owns, so the autosave stops. A
+ thread collision is an ordinary failure the caller has to see; answering both the same
+ way let the frontend swallow a collision as success and lose the message.
+ """
+ monkeypatch.setattr(chat_history, "get_chat_thread", lambda _thread_id: {"id": "t1"})
+
+ def reject(*_args, **_kwargs):
+ raise error()
+
+ monkeypatch.setattr(chat_history, "upsert_chat_message", reject)
+
+ message = chat_history.ChatMessage(
+ id = "m1", threadId = "t1", role = "assistant", content = [], createdAt = 1
+ )
+ with pytest.raises(HTTPException) as exc_info:
+ chat_history.save_thread_message("t1", "m1", message, current_subject = "u")
+
+ assert exc_info.value.status_code == 409
+ assert _conflict_kind(exc_info) == kind
diff --git a/studio/backend/tests/test_studio_db_write_lock_contention.py b/studio/backend/tests/test_studio_db_write_lock_contention.py
new file mode 100644
index 00000000000..f39c3d22364
--- /dev/null
+++ b/studio/backend/tests/test_studio_db_write_lock_contention.py
@@ -0,0 +1,740 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""studio.db must not turn one slow writer into a stream of "database is locked".
+
+A live Colab session logged six `research.supervisor_iteration_failed` tracebacks in 37
+seconds while a settings write and a multi-GB model download shared the disk. Each test
+here guards a distinct link in that chain, plus the upgrade and downgrade paths, since
+every existing install already carries the old schema.
+
+Nothing here needs a GPU or a network: the behaviour under test is SQLite pragmas, one
+poll query, and log levels.
+"""
+
+import asyncio
+import logging
+import sqlite3
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+import storage.research_runs_db as research_runs_db
+import storage.studio_db as studio_db
+
+FULL, NORMAL = 2, 1
+
+
+def db(tmp_path, monkeypatch):
+ """A studio.db in a temp dir, with the per-process schema latch reset."""
+ monkeypatch.setattr(studio_db, "studio_db_path", lambda: tmp_path / "studio.db")
+ monkeypatch.setattr(studio_db, "_schema_ready", False)
+ conn = studio_db.get_connection()
+ conn.close()
+ return tmp_path / "studio.db"
+
+
+def _journal_mode(path: Path) -> str:
+ conn = sqlite3.connect(str(path))
+ try:
+ return str(conn.execute("PRAGMA journal_mode").fetchone()[0]).lower()
+ finally:
+ conn.close()
+
+
+def _synchronous(conn: sqlite3.Connection) -> int:
+ return int(conn.execute("PRAGMA synchronous").fetchone()[0])
+
+
+def _seed_message(
+ conn,
+ thread = "t1",
+ message = "m1",
+):
+ conn.execute(
+ "INSERT OR IGNORE INTO chat_threads (id, title, model_type, created_at, updated_at) "
+ "VALUES (?, 'T', 'gguf', 0, 0)",
+ (thread,),
+ )
+ conn.execute(
+ "INSERT INTO chat_messages "
+ "(id, thread_id, role, content_json, attachments_json, metadata_json, created_at) "
+ "VALUES (?, ?, 'assistant', '[]', '[]', '{}', 0)",
+ (message, thread),
+ )
+ conn.commit()
+
+
+def _dirty(conn) -> int:
+ row = conn.execute(
+ "SELECT dirty FROM chat_attachment_inventory_state WHERE singleton = 1"
+ ).fetchone()
+ return int(row["dirty"])
+
+
+def _hold_writer_lock(conn) -> None:
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ "INSERT INTO app_settings (key, value_json, updated_at) VALUES ('probe','1','0') "
+ "ON CONFLICT(key) DO UPDATE SET value_json='1'"
+ )
+
+
+# --- synchronous=NORMAL, but only where WAL makes it safe -------------------------------
+
+
+def test_wal_database_drops_to_normal(db):
+ """synchronous=FULL fsyncs under the writer lock; NORMAL is the WAL-safe pairing."""
+ assert _journal_mode(db) == "wal"
+ conn = studio_db.get_connection()
+ try:
+ assert _synchronous(conn) == NORMAL
+ finally:
+ conn.close()
+
+
[email protected]("mode", ["delete", "truncate", "persist", "memory"])
+def test_non_wal_journal_keeps_full(db, monkeypatch, mode):
+ """PRAGMA journal_mode=WAL silently declines on filesystems without shared memory.
+
+ Network shares and some FUSE or container mounts land there, Windows users most
+ often. A rollback journal needs the fsync NORMAL removes, so those installs keep
+ FULL and simply do not get the speedup.
+ """
+ setup = sqlite3.connect(str(db))
+ try:
+ setup.execute(f"PRAGMA journal_mode={mode}")
+ setup.commit()
+ finally:
+ setup.close()
+ assert _journal_mode(db) != "wal"
+
+ monkeypatch.setattr(studio_db, "_schema_ready", True)
+ conn = studio_db.get_connection()
+ try:
+ assert _synchronous(conn) == FULL, f"{mode} must not lose its commit fsync"
+ finally:
+ conn.close()
+
+
+ "answer",
+ [None, (None,), ("",), (123,), sqlite3.OperationalError("pragma unavailable")],
+)
+def test_unreadable_journal_mode_is_not_treated_as_wal(answer):
+ """An unexpected or failing answer keeps the safe default rather than raising.
+
+ sqlite3.Connection is a C type and cannot be monkeypatched, so this uses a double.
+ """
+
+ class Connection:
+ def __init__(self):
+ self.executed = []
+
+ def execute(self, sql, *args):
+ self.executed.append(sql)
+ if isinstance(answer, Exception):
+ raise answer
+ return type("Cursor", (), {"fetchone": lambda _self: answer})()
+
+ conn = Connection()
+ studio_db._apply_wal_synchronous(conn)
+ assert "PRAGMA synchronous=NORMAL" not in conn.executed
+
+
+def test_committed_rows_survive_a_reopen(db):
+ """NORMAL changes fsync timing, not correctness."""
+ conn = studio_db.get_connection()
+ try:
+ _seed_message(conn, "t-durable", "m-durable")
+ finally:
+ conn.close()
+ conn = studio_db.get_connection()
+ try:
+ assert (
+ conn.execute("SELECT id FROM chat_messages WHERE id = 'm-durable'").fetchone()
+ is not None
+ )
+ finally:
+ conn.close()
+
+
+def test_concurrent_openers_all_get_normal(db):
+ results, errors = [], []
+
+ def worker():
+ try:
+ conn = studio_db.get_connection()
+ try:
+ results.append(_synchronous(conn))
+ finally:
+ conn.close()
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target = worker) for _ in range(16)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert not errors, errors
+ assert results == [NORMAL] * 16
+
+
+# --- the attachment inventory is dirtied by attachments, not by bookkeeping -------------
+
+
+ "sql, dirties, why",
+ [
+ (
+ "UPDATE chat_messages SET metadata_json='{\"a\":1}' WHERE id='m1'",
+ False,
+ "a generation status change touches no attachment",
+ ),
+ (
+ "UPDATE chat_messages SET role='user' WHERE id='m1'",
+ False,
+ "role is not an inventory input",
+ ),
+ (
+ "UPDATE chat_messages SET attachments_json='[{}]' WHERE id='m1'",
+ True,
+ "attachments changed",
+ ),
+ (
+ "UPDATE chat_messages SET content_json='[{\"t\":1}]' WHERE id='m1'",
+ True,
+ "inline content can carry data URIs",
+ ),
+ (
+ "UPDATE chat_messages SET attachments_json='[]' WHERE id='m1'",
+ True,
+ "UPDATE OF fires on the SET list, not on a changed value",
+ ),
+ ("DELETE FROM chat_messages WHERE id='m1'", True, "rows went away"),
+ ],
+)
+def test_inventory_trigger_scope(db, sql, dirties, why):
+ """The rebuild re-hashes every attachment in every thread inside BEGIN IMMEDIATE, so
+ dirtying it from an unrelated column is what made an ordinary autosave hold the
+ writer lock for as long as the history was large."""
+ conn = studio_db.get_connection()
+ try:
+ _seed_message(conn)
+ studio_db._mark_chat_attachment_inventory_clean(conn)
+ conn.commit()
+ assert _dirty(conn) == 0
+ conn.execute(sql)
+ conn.commit()
+ assert _dirty(conn) == (1 if dirties else 0), why
+ finally:
+ conn.close()
+
+
+def test_upgrade_replaces_the_unscoped_trigger(tmp_path, monkeypatch):
+ """Every existing install already carries the unscoped trigger.
+
+ CREATE TRIGGER IF NOT EXISTS would have kept it silently, so the fix drops first.
+ """
+ path = tmp_path / "studio.db"
+ monkeypatch.setattr(studio_db, "studio_db_path", lambda: path)
+ monkeypatch.setattr(studio_db, "_schema_ready", False)
+
+ conn = studio_db.get_connection()
+ try:
+ conn.execute("DROP TRIGGER IF EXISTS chat_attachment_inventory_dirty_update")
+ conn.execute(
+ """
+ CREATE TRIGGER chat_attachment_inventory_dirty_update
+ AFTER UPDATE ON chat_messages
+ BEGIN
+ INSERT INTO chat_attachment_inventory_state
+ (singleton, inventory_version, dirty, backfilled_at)
+ VALUES (1, 0, 1, 0)
+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;
+ END
+ """
+ )
+ conn.commit()
+ assert (
+ "UPDATE OF"
+ not in conn.execute(
+ "SELECT sql FROM sqlite_master WHERE name='chat_attachment_inventory_dirty_update'"
+ ).fetchone()[0]
+ )
+ finally:
+ conn.close()
+
+ monkeypatch.setattr(studio_db, "_schema_ready", False)
+ conn = studio_db.get_connection()
+ try:
+ assert (
+ "UPDATE OF attachments_json, content_json"
+ in conn.execute(
+ "SELECT sql FROM sqlite_master WHERE name='chat_attachment_inventory_dirty_update'"
+ ).fetchone()[0]
+ )
+ _seed_message(conn)
+ studio_db._mark_chat_attachment_inventory_clean(conn)
+ conn.commit()
+ conn.execute("UPDATE chat_messages SET metadata_json='{\"x\":1}' WHERE id='m1'")
+ conn.commit()
+ assert _dirty(conn) == 0
+ finally:
+ conn.close()
+
+
+def _legacy_unscoped_trigger(conn) -> None:
+ conn.execute("DROP TRIGGER IF EXISTS chat_attachment_inventory_dirty_update")
+ conn.execute(
+ """
+ CREATE TRIGGER chat_attachment_inventory_dirty_update
+ AFTER UPDATE ON chat_messages
+ BEGIN
+ INSERT INTO chat_attachment_inventory_state
+ (singleton, inventory_version, dirty, backfilled_at)
+ VALUES (1, 0, 1, 0)
+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;
+ END
+ """
+ )
+ conn.commit()
+
+
+def test_eight_processes_upgrading_at_once_all_succeed(db):
+ """Two Studio processes on one studio.db each carry their own `_schema_ready`.
+
+ DDL does not open a transaction under sqlite3's legacy transaction control -- only
+ INSERT/UPDATE/DELETE/REPLACE do -- so a bare DROP + CREATE pair runs in autocommit and
+ can interleave as drop/drop/create/create, where the second CREATE raises
+ "trigger already exists" straight out of get_connection. The forced sequence is in
+ test_a_lost_create_race_cannot_raise; this is the end-to-end shape of it.
+ """
+ setup = studio_db.get_connection()
+ try:
+ _legacy_unscoped_trigger(setup)
+ finally:
+ setup.close()
+
+ errors, seen = [], []
+ start = threading.Barrier(8)
+
+ def worker():
+ conn = sqlite3.connect(str(db), timeout = 10)
+ conn.row_factory = sqlite3.Row
+ try:
+ start.wait(timeout = 10)
+ studio_db._replace_inventory_update_trigger(conn)
+ seen.append(
+ conn.execute(
+ "SELECT sql FROM sqlite_master WHERE name = ?",
+ ("chat_attachment_inventory_dirty_update",),
+ ).fetchone()["sql"]
+ )
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+ finally:
+ conn.close()
+
+ threads = [threading.Thread(target = worker) for _ in range(8)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+
+ assert not errors, errors
+ assert len(seen) == 8
+ assert all("UPDATE OF attachments_json, content_json" in sql for sql in seen)
+
+
+def test_the_migration_is_skipped_once_the_scoped_trigger_is_installed(db):
+ """Every connection would otherwise re-drop and re-create it, taking the writer lock
+ on a hot path for nothing."""
+ conn = studio_db.get_connection()
+ try:
+ assert (
+ "UPDATE OF"
+ in conn.execute(
+ "SELECT sql FROM sqlite_master WHERE name = ?",
+ ("chat_attachment_inventory_dirty_update",),
+ ).fetchone()["sql"]
+ )
+ held = sqlite3.connect(str(db), timeout = 0.2)
+ try:
+ _hold_writer_lock(held)
+ # No writer lock is taken, so this returns even while one is held elsewhere.
+ studio_db._replace_inventory_update_trigger(conn)
+ finally:
+ held.rollback()
+ held.close()
+ finally:
+ conn.close()
+
+
+def test_a_lost_create_race_cannot_raise(db):
+ """The interleave itself, forced rather than raced for.
+
+ Racing two threads for it does not work: every DDL statement takes the writer lock, so
+ the window between the drop committing and the create is too narrow to sample.
+ """
+ setup = studio_db.get_connection()
+ try:
+ _legacy_unscoped_trigger(setup)
+ finally:
+ setup.close()
+
+ first = sqlite3.connect(str(db), timeout = 10)
+ second = sqlite3.connect(str(db), timeout = 10)
+ try:
+ for conn in (first, second):
+ conn.execute("DROP TRIGGER IF EXISTS chat_attachment_inventory_dirty_update")
+ conn.commit()
+ first.execute(studio_db._INVENTORY_UPDATE_TRIGGER_SQL)
+ first.commit()
+
+ # Without IF NOT EXISTS this raises out of get_connection, so the second process
+ # cannot open the database at all.
+ unguarded = studio_db._INVENTORY_UPDATE_TRIGGER_SQL.replace("IF NOT EXISTS ", "")
+ with pytest.raises(sqlite3.OperationalError, match = "already exists"):
+ second.execute(unguarded)
+
+ second.execute(studio_db._INVENTORY_UPDATE_TRIGGER_SQL)
+ second.commit()
+ finally:
+ first.close()
+ second.close()
+
+ conn = sqlite3.connect(str(db))
+ try:
+ sql = conn.execute(
+ "SELECT sql FROM sqlite_master WHERE name = ?",
+ ("chat_attachment_inventory_dirty_update",),
+ ).fetchone()[0]
+ finally:
+ conn.close()
+ assert "UPDATE OF attachments_json, content_json" in sql
+
+
+def test_the_drop_and_the_create_share_one_writer_lock():
+ """Held across both, so no opener sees the table without its trigger.
+
+ sqlite3.Connection is a C type and cannot be monkeypatched, hence the double.
+ """
+
+ class Connection:
+ in_transaction = False
+
+ def __init__(self):
+ self.executed = []
+ self.committed = 0
+
+ def execute(self, sql, *args):
+ self.executed.append(" ".join(sql.split())[:40])
+ return type("Cursor", (), {"fetchone": lambda _self: None})()
+
+ def commit(self):
+ self.committed += 1
+
+ def rollback(self):
+ raise AssertionError("nothing here should roll back")
+
+ conn = Connection()
+ studio_db._replace_inventory_update_trigger(conn)
+
+ kinds = [sql.split()[0] for sql in conn.executed]
+ assert kinds == ["SELECT", "BEGIN", "DROP", "CREATE"], conn.executed
+ assert conn.executed[1].startswith("BEGIN IMMEDIATE"), conn.executed[1]
+ assert "IF NOT EXISTS" in conn.executed[3]
+ assert conn.committed == 1, "one commit, at the end of the pair"
+
+
+def test_downgrade_still_sees_attachment_changes(db):
+ """An older Unsloth run against an upgraded database keeps the scoped trigger, since
+ its CREATE TRIGGER IF NOT EXISTS finds the name taken. That is safe: the scoped
+ trigger still fires for everything the inventory derives from."""
+ conn = studio_db.get_connection()
+ try:
+ conn.execute(
+ """
+ CREATE TRIGGER IF NOT EXISTS chat_attachment_inventory_dirty_update
+ AFTER UPDATE ON chat_messages
+ BEGIN
+ INSERT INTO chat_attachment_inventory_state
+ (singleton, inventory_version, dirty, backfilled_at)
+ VALUES (1, 0, 1, 0)
+ ON CONFLICT(singleton) DO UPDATE SET dirty = 1;
+ END
+ """
+ )
+ conn.commit()
+ _seed_message(conn)
+ studio_db._mark_chat_attachment_inventory_clean(conn)
+ conn.commit()
+ conn.execute("UPDATE chat_messages SET attachments_json='[{}]' WHERE id='m1'")
+ conn.commit()
+ assert _dirty(conn) == 1
+ finally:
+ conn.close()
+
+
+# --- claim_next: cheap when idle, unchanged when there is work --------------------------
+
+
+def _make_run(
+ run_id = "r1",
+ thread = "t1",
+ status = "queued",
+):
+ studio_db.upsert_chat_thread({"id": thread, "title": "T", "modelType": "gguf", "createdAt": 1})
+ studio_db.upsert_chat_message(
+ {"id": f"u-{run_id}", "threadId": thread, "role": "user", "content": [], "createdAt": 2}
+ )
+ studio_db.upsert_chat_message(
+ {
+ "id": f"a-{run_id}",
+ "threadId": thread,
+ "parentId": f"u-{run_id}",
+ "role": "assistant",
+ "content": [],
+ "createdAt": 3,
+ }
+ )
+ research_runs_db.create_run(
+ run_id = run_id,
+ owner_subject = "sub",
+ thread_id = thread,
+ user_message_id = f"u-{run_id}",
+ assistant_message_id = f"a-{run_id}",
+ config = {},
+ )
+ if status != "queued":
+ conn = studio_db.get_connection()
+ try:
+ conn.execute("UPDATE research_runs SET status=? WHERE id=?", (status, run_id))
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def test_idle_poll_takes_no_write_lock(db):
+ """The original failure reproduced: this used to raise after the 5s busy timeout."""
+ holder = studio_db.get_connection()
+ try:
+ _hold_writer_lock(holder)
+ started = time.monotonic()
+ assert research_runs_db.claim_next("worker-1") is None
+ assert time.monotonic() - started < 1.0, "must not have queued behind the writer"
+ finally:
+ holder.rollback()
+ holder.close()
+
+
+def test_claim_next_still_claims_real_work(db):
+ _make_run()
+ claimed = research_runs_db.claim_next("worker-1")
+ assert claimed is not None and claimed["id"] == "r1"
+ assert research_runs_db.claim_next("worker-2") is None, "the lease excludes others"
+
+
[email protected]("status", ["planning", "queued", "running", "cancelling"])
+def test_probe_agrees_with_the_transaction_when_claimable(db, status):
+ _make_run(status = status)
+ assert research_runs_db._has_claimable(research_runs_db.now_ms()) is True
+ assert research_runs_db.claim_next("worker-1") is not None
+
+
+ "status", ["completed", "failed", "cancelled", "paused", "awaiting_approval"]
+)
+def test_probe_agrees_with_the_transaction_when_not_claimable(db, status):
+ _make_run(status = status)
+ assert research_runs_db._has_claimable(research_runs_db.now_ms()) is False
+ assert research_runs_db.claim_next("worker-1") is None
+
+
+def test_expired_lease_becomes_claimable_again(db):
+ _make_run()
+ assert research_runs_db.claim_next("worker-1") is not None
+ assert research_runs_db._has_claimable(research_runs_db.now_ms()) is False
+ conn = studio_db.get_connection()
+ try:
+ conn.execute(
+ "UPDATE research_runs SET lease_expires_at=? WHERE id='r1'",
+ (research_runs_db.now_ms() - 1,),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ assert research_runs_db._has_claimable(research_runs_db.now_ms()) is True
+ assert research_runs_db.claim_next("worker-2") is not None
+
+
+def test_run_without_a_thread_claim_is_invisible(db):
+ """The probe must reproduce the transaction's join, not just its WHERE clause."""
+ _make_run()
+ conn = studio_db.get_connection()
+ try:
+ conn.execute("DELETE FROM research_thread_claims")
+ conn.commit()
+ finally:
+ conn.close()
+ assert research_runs_db._has_claimable(research_runs_db.now_ms()) is False
+ assert research_runs_db.claim_next("worker-1") is None
+
+
+def test_concurrent_workers_claim_a_run_exactly_once(db):
+ _make_run()
+ claims, errors = [], []
+
+ def worker(name):
+ try:
+ if research_runs_db.claim_next(name) is not None:
+ claims.append(name)
+ except Exception as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target = worker, args = (f"w{i}",)) for i in range(8)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert not errors, errors
+ assert len(claims) == 1, f"the read-first probe must not let two workers claim: {claims}"
+
+
+# --- the busy predicate and the supervisor's error ladder -------------------------------
+
+
+ "message, busy",
+ [
+ ("database is locked", True),
+ ("database table is locked", True),
+ ("database is busy", True),
+ ("attempt to write a readonly database", False),
+ ("no such table: research_runs", False),
+ ("disk I/O error", False),
+ ("unable to open database file", False),
+ ],
+)
+def test_busy_predicate(message, busy):
+ assert studio_db.is_sqlite_busy_error(sqlite3.OperationalError(message)) is busy
+
+
+def test_api_usage_db_shares_one_definition():
+ import storage.api_usage_db as api_usage_db
+ assert api_usage_db._is_busy_error(sqlite3.OperationalError("database is locked"))
+ assert not api_usage_db._is_busy_error(sqlite3.OperationalError("disk I/O error"))
+
+
+class _Ladder:
+ """The supervisor's except-ladder without its dependencies.
+
+ Mirrors ResearchSupervisor._loop in core/research_runs.py; the control flow is the
+ point, since the regression this guards was a control-flow one.
+ """
+
+ def __init__(self, raises, logger):
+ self._raises = list(raises)
+ self.logger = logger
+ self.iterations = 0
+ self.survived = False
+
+ async def run(self):
+ for exc in self._raises:
+ self.iterations += 1
+ try:
+ if exc is not None:
+ raise exc
+ except asyncio.CancelledError:
+ raise
+ except sqlite3.OperationalError as err:
+ if studio_db.is_sqlite_busy_error(err):
+ self.logger.warning("research.supervisor_db_busy: %s", err)
+ else:
+ self.logger.exception("research.supervisor_iteration_failed")
+ await asyncio.sleep(0)
+ except Exception:
+ self.logger.exception("research.supervisor_iteration_failed")
+ await asyncio.sleep(0)
+ self.survived = True
+
+
+def _levels(caplog):
+ return [(record.levelname, record.exc_info is not None) for record in caplog.records]
+
+
+def test_lock_contention_is_six_warnings_not_six_tracebacks(caplog):
+ logger = logging.getLogger("test.supervisor.busy")
+ ladder = _Ladder([sqlite3.OperationalError("database is locked")] * 6, logger)
+ with caplog.at_level(logging.WARNING, logger = logger.name):
+ asyncio.run(ladder.run())
+ assert ladder.survived
+ assert _levels(caplog) == [("WARNING", False)] * 6
+
+
+def test_a_real_sqlite_fault_does_not_stop_the_supervisor(caplog):
+ """Re-raising here would escape the while loop, because a sibling `except Exception`
+ cannot catch a raise from its own ladder. The supervisor would stop for the life of
+ the process, silently, which is worse than the log noise this change removes."""
+ logger = logging.getLogger("test.supervisor.fault")
+ ladder = _Ladder([sqlite3.OperationalError("no such table: research_runs"), None, None], logger)
+ with caplog.at_level(logging.ERROR, logger = logger.name):
+ asyncio.run(ladder.run())
+ assert ladder.survived and ladder.iterations == 3
+ assert _levels(caplog) == [("ERROR", True)], "and it keeps its traceback"
+
+
+def test_unrelated_exceptions_are_unchanged(caplog):
+ logger = logging.getLogger("test.supervisor.other")
+ ladder = _Ladder([ValueError("boom"), None], logger)
+ with caplog.at_level(logging.ERROR, logger = logger.name):
+ asyncio.run(ladder.run())
+ assert ladder.survived
+ assert _levels(caplog) == [("ERROR", True)]
+
+
+def test_cancellation_still_propagates():
+ logger = logging.getLogger("test.supervisor.cancel")
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(_Ladder([asyncio.CancelledError()], logger).run())
+
+
+# --- expected client errors are not server faults ---------------------------------------
+
+
+class _RecordingLogger:
+ def __init__(self):
+ self.calls = []
+
+ def warning(self, *args, **kwargs):
+ self.calls.append(("warning", kwargs))
+
+ def error(self, *args, **kwargs):
+ self.calls.append(("error", kwargs))
+
+
[email protected]("status", [400, 401, 403, 404, 409, 422, 429])
+def test_client_errors_log_one_warning_without_a_traceback(status):
+ """One streamed generation put 54 rejected saves in the log, each with a full stack."""
+ from utils.utils import log_and_http_error
+
+ log = _RecordingLogger()
+ error = log_and_http_error(ValueError("x"), status, "public", event = "e", log = log)
+ assert error.status_code == status
+ assert error.detail == "public", "the raw exception must never reach the client"
+ assert log.calls == [("warning", {})]
+
+
[email protected]("status", [500, 502, 503, 504])
+def test_server_errors_keep_their_traceback(status):
+ from utils.utils import log_and_http_error
+
+ raised = ValueError("x")
+ log = _RecordingLogger()
+ 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
diff --git a/studio/backend/utils/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.py
index 957828163f8..c0fc11d611c 100644
--- a/studio/backend/utils/hf_xet_fallback.py
+++ b/studio/backend/utils/hf_xet_fallback.py
@@ -234,9 +234,15 @@ def cached_xet_health(**kwargs: Any) -> Any:
Capability reads use this path so opening Hub cannot initialize Unsloth Zoo. A real
download calls :func:`xet_health`, which loads the optional module and populates this cache.
+
+ Read without ``_load_lock`` on purpose. Taking it made this "already loaded?" question wait
+ on whatever import another thread was holding it for -- a torch-loading `import unsloth_zoo`
+ that runs for seconds -- so the one path guaranteed never to load Zoo was the one blocked by
+ loading it. A dict lookup keyed by a plain string is atomic under the GIL, and the only
+ writers publish a fully-built module (or ``None``) in a single assignment, so the worst
+ outcome is reading the pre-import value and correctly answering "not loaded yet".
"""
- with _load_lock:
- module = _optional_modules.get("unsloth_zoo.hf_xet_health", _UNTRIED)
+ module = _optional_modules.get("unsloth_zoo.hf_xet_health", _UNTRIED)
return None if module is _UNTRIED else _xet_health_from(module, **kwargs)
diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.py
index b9674d4899d..af374f193de 100644
--- a/studio/backend/utils/utils.py
+++ b/studio/backend/utils/utils.py
@@ -839,6 +839,7 @@ def log_and_http_error(
*,
event: str = "request_failed",
log = None,
+ headers: Optional[dict] = None,
):
"""Log ``error`` in full server-side and return an ``HTTPException`` whose
``detail`` is only ``public_message`` -- never the raw exception text.
@@ -847,9 +848,15 @@ def log_and_http_error(
"""
from fastapi import HTTPException
- # exc_info=error works for both structlog and stdlib loggers.
- (log or logger).error(f"{event}: {error}", exc_info = error)
- return HTTPException(status_code = status_code, detail = public_message)
+ # A 4xx is a normal outcome the caller handles, so one warning line and no traceback:
+ # at error with exc_info, one generation buried the log under 54 rejected saves. 5xx
+ # keeps the traceback, since that is a server bug. exc_info works for structlog too.
+ emitter = log or logger
+ if 400 <= status_code < 500:
+ emitter.warning(f"{event}: {error}")
+ else:
+ emitter.error(f"{event}: {error}", exc_info = error)
+ return HTTPException(status_code = status_code, detail = public_message, headers = headers)
@contextmanager
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 3ecc86a96ed..4997bee39fc 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -1128,6 +1128,29 @@ export async function getChatMessage(
return parseJsonOrThrow<MessageRecord>(response);
}
+/** The server owns this message and will reject every save of it.
+ *
+ * Distinct from a transient failure: retrying can never succeed, so callers must stop
+ * rather than back off. Without this the per-chunk autosave treated the rejection as an
+ * anonymous error and re-sent on the next chunk for the whole generation.
+ */
+/** Set by routes/chat_history.py; exposed through the CORS middleware in main.py. */
+const CONFLICT_KIND_HEADER = "X-Unsloth-Conflict-Kind";
+const CONFLICT_KIND_PROTECTED = "protected";
+
+export class ChatMessageProtectedError extends Error {
+ readonly messageId: string;
+ readonly threadId: string;
+
+ constructor(threadId: string, messageId: string, detail?: string) {
+ // Keep the server's wording: a manual edit surfaces this text to the user.
+ super(detail || `Message ${messageId} is server-managed and cannot be edited`);
+ this.name = "ChatMessageProtectedError";
+ this.threadId = threadId;
+ this.messageId = messageId;
+ }
+}
+
export async function saveChatMessage(
message: MessageRecord,
options: { allowGenerationEdit?: boolean; coalesce?: boolean } = {},
@@ -1143,6 +1166,21 @@ export async function saveChatMessage(
body: JSON.stringify(message),
},
);
+ // Two failures share this status: a protected message, where the autosave must stop, and
+ // a thread-id collision, which the caller must see or the message is lost. Only the header
+ // separates them, so anything else (an older backend included) takes the normal error path.
+ if (
+ response.status === 409 &&
+ response.headers?.get(CONFLICT_KIND_HEADER) === CONFLICT_KIND_PROTECTED
+ ) {
+ // Read here, not in parseJsonOrThrow: a body is single-use.
+ const body = await response.json().catch(() => null);
+ throw new ChatMessageProtectedError(
+ message.threadId,
+ message.id,
+ formatApiErrorBody(body) ?? undefined,
+ );
+ }
const savedMessage = await parseJsonOrThrow<MessageRecord>(response);
// Coalescing is the streaming autosave's alone, since it lands here per chunk. A manual
// edit is one deliberate change and publishes at once.
diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
index f7bfb7edcc9..c2bef6812c3 100644
--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import {
+ ChatMessageProtectedError,
ChatThreadDeletedError,
batchListChatMessages,
buildBackendChatExport,
@@ -388,7 +389,7 @@ async function saveLegacyChatThread(
if (!(error instanceof ChatThreadDeletedError)) {
throw error;
}
- markChatThreadDeleted(thread.id);
+ forgetChatThread(thread.id);
return undefined;
}
}
@@ -948,6 +949,82 @@ export async function moveStoredChatItemToProject(
);
}
+// Payloads the server answered 409 for, so the ~300ms autosave stops resending them.
+// Keyed by payload, not by id: a protected message can be refused transiently, when its
+// generationSeq lost a race, and blocking the id would drop the terminal write
+// (_safe_generation_assistant_update).
+const rejectedChatMessagePayloads = new Map<string, Map<string, string>>();
+
+// Entries hold whole messages, and only the delete paths clear them. Exceeding the cap
+// costs one extra request for whichever message fell out.
+const MAX_REJECTED_PAYLOADS = 32;
+
+/** Least-recently-written first, both across threads and within one. */
+function evictOldestRejectedPayloads(): void {
+ let total = 0;
+ for (const perThread of rejectedChatMessagePayloads.values()) {
+ total += perThread.size;
+ }
+ while (total > MAX_REJECTED_PAYLOADS) {
+ const oldestThread = rejectedChatMessagePayloads.entries().next().value;
+ if (!oldestThread) return;
+ const [threadId, perThread] = oldestThread;
+ const oldestMessage = perThread.keys().next().value;
+ if (oldestMessage === undefined) {
+ rejectedChatMessagePayloads.delete(threadId);
+ continue;
+ }
+ perThread.delete(oldestMessage);
+ if (perThread.size === 0) rejectedChatMessagePayloads.delete(threadId);
+ total -= 1;
+ }
+}
+
+function rememberRejectedPayload(
+ threadId: string,
+ messageId: string,
+ payload: string,
+): void {
+ const perThread = rejectedChatMessagePayloads.get(threadId) ?? new Map<string, string>();
+ perThread.delete(messageId);
+ perThread.set(messageId, payload);
+ rejectedChatMessagePayloads.delete(threadId);
+ rejectedChatMessagePayloads.set(threadId, perThread);
+ evictOldestRejectedPayloads();
+}
+
+/** Deterministic JSON: key order must not decide whether two payloads look equal. */
+function stableStringify(value: unknown): string {
+ if (value === null || typeof value !== "object") {
+ return JSON.stringify(value) ?? "null";
+ }
+ if (Array.isArray(value)) {
+ return `[${value.map(stableStringify).join(",")}]`;
+ }
+ const entries = Object.entries(value as Record<string, unknown>)
+ .filter(([, entry]) => entry !== undefined)
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
+ return `{${entries
+ .map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`)
+ .join(",")}}`;
+}
+
+// Every entry, not just the deleted thread's: a collision is recorded under the thread we
+// wrote TO, so deleting the thread that OWNS the id frees it elsewhere in the map.
+export function clearServerOwnedChatMessages(): void {
+ rejectedChatMessagePayloads.clear();
+}
+
+function forgetChatThread(threadId: string): void {
+ markChatThreadDeleted(threadId);
+ clearServerOwnedChatMessages();
+}
+
+function forgetChatThreads(threadIds: string[]): void {
+ markChatThreadsDeleted(threadIds);
+ clearServerOwnedChatMessages();
+}
+
export async function saveStoredChatMessage(
message: MessageRecord,
): Promise<MessageRecord> {
@@ -955,9 +1032,23 @@ export async function saveStoredChatMessage(
if (isChatThreadDeleted(message.threadId)) {
throw new Error(`Thread ${message.threadId} was deleted`);
}
+ const payload = stableStringify(message);
+ if (rejectedChatMessagePayloads.get(message.threadId)?.get(message.id) === payload) {
+ // Refresh: otherwise the message being resent right now is the one aging out.
+ rememberRejectedPayload(message.threadId, message.id, payload);
+ return message;
+ }
await ensureStoredChatThread(message.threadId);
// The per-chunk autosave behind a streaming response.
- return saveChatMessage(message, { coalesce: true });
+ try {
+ return await saveChatMessage(message, { coalesce: true });
+ } catch (error) {
+ if (error instanceof ChatMessageProtectedError) {
+ rememberRejectedPayload(message.threadId, message.id, payload);
+ return message;
+ }
+ throw error;
+ }
}
export async function syncStoredChatMessages(
@@ -968,7 +1059,13 @@ export async function syncStoredChatMessages(
if (isThreadIncognito(threadId)) return messages;
if (isChatThreadDeleted(threadId)) return [];
await ensureStoredChatThread(threadId);
- return syncChatMessages(threadId, messages, options);
+ const synced = await syncChatMessages(threadId, messages, options);
+ // Deleting rows frees their ids while the thread survives, so no tombstone runs. Gated on
+ // an actual deletion: an ordinary sync runs constantly and would undo the whole cache.
+ if (options.pruneMissing || (options.deletedMessageIds?.length ?? 0) > 0) {
+ clearServerOwnedChatMessages();
+ }
+ return synced;
}
export async function saveStoredChatThread(
@@ -982,7 +1079,7 @@ export async function saveStoredChatThread(
return await writeChatThreadRecord(thread);
} catch (error) {
if (error instanceof ChatThreadDeletedError) {
- markChatThreadDeleted(thread.id);
+ forgetChatThread(thread.id);
}
throw error;
}
@@ -1056,7 +1153,7 @@ export async function deleteStoredChatThreads(
.catch(() => undefined),
undefined,
);
- markChatThreadsDeleted(ids);
+ forgetChatThreads(ids);
return kept;
}
@@ -1175,7 +1272,7 @@ async function clearStoredChatsWithAdmissionClosed(
const deleted = new Set(result.deletedThreadIds);
result.failedThreadIds = allThreadIds.filter((id) => !deleted.has(id));
- markChatThreadsDeleted(result.deletedThreadIds);
+ forgetChatThreads(result.deletedThreadIds);
notifyChatHistoryUpdated();
if (result.backend === "failed" && result.legacy === "failed") {
diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.ts
new file mode 100644
index 00000000000..e8d6ec6868e
--- /dev/null
+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// saveChatMessage turns a protected 409 into a typed error so the autosave can tell "stop"
+// from "retry". A manual edit rethrows to the user, so the server's wording must survive.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Module = {
+ saveChatMessage: (
+ message: Record<string, unknown>,
+ options?: { allowGenerationEdit?: boolean; coalesce?: boolean },
+ ) => Promise<unknown>;
+ ChatMessageProtectedError: new (
+ threadId: string,
+ messageId: string,
+ detail?: string,
+ ) => Error & { threadId: string; messageId: string };
+};
+
+/** Minimal Response double: records how many times the body was consumed. */
+function jsonResponse(status: number, body: unknown, kind: string | null = "protected") {
+ let reads = 0;
+ return {
+ status,
+ ok: status >= 200 && status < 300,
+ headers: { get: (name: string) => (name === "X-Unsloth-Conflict-Kind" ? kind : null) },
+ get bodyReads() {
+ return reads;
+ },
+ async json() {
+ reads += 1;
+ if (reads > 1) {
+ throw new TypeError("Body has already been consumed.");
+ }
+ if (body === undefined) throw new SyntaxError("Unexpected end of JSON input");
+ return body;
+ },
+ };
+}
+
+function harness(response: ReturnType<typeof jsonResponse>) {
+ const requests: { url: string; init?: RequestInit }[] = [];
+ const module = loadWithStubs<Module>(
+ new URL("../src/features/chat/api/chat-api.ts", import.meta.url),
+ {
+ "@/features/auth": {
+ authFetch: async (url: string, init?: RequestInit) => {
+ requests.push({ url, init });
+ return response;
+ },
+ },
+ "@/lib/format-fastapi-error": {
+ formatApiErrorBody: (body: unknown) =>
+ (body as { detail?: string } | null)?.detail ?? null,
+ },
+ "../types": {},
+ "../types/api": {},
+ "../utils/chat-history-revision": {
+ notifyChatHistoryUpdated: () => {},
+ isCoalescedHistoryEvent: () => false,
+ },
+ "./generation-length.ts": {},
+ "./gguf-variants-request": {},
+ "./padded-response": { assertCompletedPaddedBody: () => {} },
+ "@/features/hf-auth": { prepareHfTokenForUse: async () => undefined },
+ "@/features/hub/lib/abort-signals": {},
+ "@/features/hub/lib/hub-token-header": { hubTokenHeader: () => ({}) },
+ "@/features/hub/lib/network": { isHuggingFaceOffline: () => false },
+ "@/features/native-intents/api": { consumeNativePathToken: () => undefined },
+ "@/lib/model-lifecycle-events": {},
+ },
+ );
+ return { module, requests };
+}
+
+const message = { id: "m1", threadId: "t1", role: "assistant", content: [], createdAt: 1 };
+
+test("a 409 becomes the typed error, carrying the server's wording", async () => {
+ const response = jsonResponse(409, {
+ detail: "server-managed generation messages cannot be edited",
+ });
+ const { module } = harness(response);
+
+ const error = await module
+ .saveChatMessage(message)
+ .then(() => null)
+ .catch((e) => e);
+
+ assert.ok(
+ error instanceof module.ChatMessageProtectedError,
+ "callers branch on the type, so instanceof must hold",
+ );
+ assert.equal(
+ error.message,
+ "server-managed generation messages cannot be edited",
+ "a manual edit surfaces this to the user; it must not be replaced",
+ );
+ assert.equal(error.threadId, "t1");
+ assert.equal(error.messageId, "m1");
+});
+
+test("the body is read exactly once", async () => {
+ const response = jsonResponse(409, { detail: "nope" });
+ const { module } = harness(response);
+ await module.saveChatMessage(message).catch(() => {});
+ assert.equal(response.bodyReads, 1);
+});
+
+test("a 409 with no usable body still produces a sensible message", async () => {
+ const { module } = harness(jsonResponse(409, null));
+ const error = await module.saveChatMessage(message).catch((e) => e);
+ assert.ok(error instanceof module.ChatMessageProtectedError);
+ assert.match(error.message, /server-managed/);
+});
+
+test("a 409 whose body is not JSON at all does not throw a parse error", async () => {
+ const { module } = harness(jsonResponse(409, undefined));
+ const error = await module.saveChatMessage(message).catch((e) => e);
+ assert.ok(
+ error instanceof module.ChatMessageProtectedError,
+ "the conflict must survive an unparseable body",
+ );
+});
+
+test("a thread-id collision is not treated as protection", async () => {
+ const { module } = harness(
+ jsonResponse(409, { detail: "Message id already belongs to another thread: m1" }, "thread-collision"),
+ );
+ const error = await module.saveChatMessage(message).catch((e) => e);
+
+ assert.ok(error instanceof Error);
+ assert.ok(
+ !(error instanceof module.ChatMessageProtectedError),
+ "the caller must see this one and handle it",
+ );
+});
+
+test("a backend too old to send the header falls back to the plain error", async () => {
+ const { module } = harness(jsonResponse(409, { detail: "conflict" }, null));
+ const error = await module.saveChatMessage(message).catch((e) => e);
+
+ assert.ok(error instanceof Error);
+ assert.ok(!(error instanceof module.ChatMessageProtectedError));
+});
+
+test("other failures are untouched", async () => {
+ const { module } = harness(jsonResponse(500, { detail: "boom" }));
+ const error = await module.saveChatMessage(message).catch((e) => e);
+ assert.ok(error instanceof Error);
+ assert.ok(
+ !(error instanceof module.ChatMessageProtectedError),
+ "only 409 means the server owns the message",
+ );
+ assert.match(error.message, /boom/);
+});
+
+test("a success is returned unchanged", async () => {
+ const saved = { ...message, content: [{ type: "text", text: "hi" }] };
+ const { module, requests } = harness(jsonResponse(200, saved));
+ assert.deepEqual(await module.saveChatMessage(message), saved);
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].init?.method, "PUT");
+});
+
+test("the manual-edit query parameter is still sent", async () => {
+ const { module, requests } = harness(jsonResponse(200, message));
+ await module.saveChatMessage(message, { allowGenerationEdit: true });
+ assert.match(requests[0].url, /allowGenerationEdit=true/);
+});
diff --git a/studio/frontend/tests/chat-save-server-managed-stop.test.ts b/studio/frontend/tests/chat-save-server-managed-stop.test.ts
new file mode 100644
index 00000000000..8001165af46
--- /dev/null
+++ b/studio/frontend/tests/chat-save-server-managed-stop.test.ts
@@ -0,0 +1,254 @@
+// 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 autosave used to re-send on the next chunk after a 409, turning one 43s generation
+// into 54 rejected PUTs. The stop is scoped to the refused payload, not the message id: a
+// 409 is not proof of ownership, so only a resend of the same bytes is dropped.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Module = {
+ saveStoredChatMessage: (message: Record<string, unknown>) => Promise<unknown>;
+ clearServerOwnedChatMessages: () => void;
+ syncStoredChatMessages: (
+ threadId: string,
+ messages: unknown[],
+ options?: { pruneMissing?: boolean; deletedMessageIds?: string[] },
+ ) => Promise<unknown>;
+};
+
+class FakeProtectedError extends Error {}
+
+function harness(options: { rejectIds?: Set<string>; failWith?: Error } = {}) {
+ const attempts: string[] = [];
+ const reject = options.rejectIds ?? new Set<string>();
+ const module = loadWithStubs<Module>(
+ new URL(
+ "../src/features/chat/utils/chat-history-storage.ts",
+ import.meta.url,
+ ),
+ {
+ "../api/chat-api": {
+ ChatMessageProtectedError: FakeProtectedError,
+ saveChatMessage: async (message: { id: string }) => {
+ attempts.push(message.id);
+ if (options.failWith) throw options.failWith;
+ if (reject.has(message.id)) throw new FakeProtectedError("409");
+ return message;
+ },
+ notifyChatHistoryUpdated: () => {},
+ syncChatMessages: async (
+ _threadId: string,
+ messages: unknown[],
+ ) => messages,
+ getChatThread: async () => ({ id: "t1" }),
+ saveChatThread: async () => {},
+ },
+ "../db": { DEXIE_DB_NAME: "test", db: {} },
+ "./chat-thread-tombstones": { isChatThreadDeleted: () => false },
+ "./thread-record-write-coordinator": {
+ ThreadRecordWriteCoordinator: class {
+ async settleCurrent() {}
+ async write(_id: string, fn: () => Promise<unknown>) {
+ return fn();
+ }
+ observe() {}
+ closeAdmission() {}
+ confirmFinalState() {}
+ hasPending() {
+ return false;
+ }
+ idsRequiringFence() {
+ return [];
+ }
+ },
+ },
+ },
+ );
+ return { module, attempts };
+}
+
+const message = (id: string, threadId = "t1") => ({
+ id,
+ threadId,
+ role: "assistant",
+ content: [],
+ createdAt: 1,
+});
+
+test("a rejected message is never sent again", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ for (let chunk = 0; chunk < 5; chunk += 1) {
+ await module.saveStoredChatMessage(message("m1"));
+ }
+
+ assert.deepEqual(
+ attempts,
+ ["m1"],
+ "the server owns this message; retrying can never succeed",
+ );
+});
+
+test("the rejection resolves rather than throwing, so the stream keeps following", async () => {
+ const { module } = harness({ rejectIds: new Set(["m1"]) });
+ const record = message("m1");
+ assert.deepEqual(await module.saveStoredChatMessage(record), record);
+});
+
+test("only the rejected id is blocked", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage(message("m1"));
+ await module.saveStoredChatMessage(message("m2"));
+ await module.saveStoredChatMessage(message("m2"));
+
+ assert.deepEqual(
+ attempts,
+ ["m1", "m2", "m2"],
+ "a client-owned message must still autosave every chunk",
+ );
+});
+
+test("the same id in another thread is unaffected", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage(message("m1", "t1"));
+ await module.saveStoredChatMessage(message("m1", "t2"));
+
+ assert.equal(attempts.length, 2, "the block is per thread, not per bare id");
+});
+
+test("clearing lets a reissued id save again", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage(message("m1"));
+ module.clearServerOwnedChatMessages();
+ await module.saveStoredChatMessage(message("m1"));
+
+ assert.equal(attempts.length, 2);
+});
+
+test("a later monotonic update is still sent after a stale-seq rejection", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage({ ...message("m1"), metadata: { generationSeq: 4 } });
+ await module.saveStoredChatMessage({ ...message("m1"), metadata: { generationSeq: 5 } });
+ await module.saveStoredChatMessage({
+ ...message("m1"),
+ metadata: { generationSeq: 6, generationSettled: true },
+ });
+
+ assert.deepEqual(
+ attempts,
+ ["m1", "m1", "m1"],
+ "each newer payload gets its own attempt; only a byte-identical resend is dropped",
+ );
+});
+
+test("growing streamed content is never mistaken for a resend", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ for (const text of ["He", "Hell", "Hello"]) {
+ await module.saveStoredChatMessage({
+ ...message("m1"),
+ content: [{ type: "text", text }],
+ });
+ }
+
+ assert.equal(attempts.length, 3, "the follower publishes a longer body each chunk");
+});
+
+test("key order does not decide whether two payloads are the same", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage({
+ id: "m1",
+ threadId: "t1",
+ role: "assistant",
+ content: [],
+ createdAt: 1,
+ });
+ await module.saveStoredChatMessage({
+ createdAt: 1,
+ content: [],
+ role: "assistant",
+ threadId: "t1",
+ id: "m1",
+ });
+
+ assert.deepEqual(attempts, ["m1"], "same fields, same payload");
+});
+
+test("deleting a thread frees ids cached under every other thread", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1", "m2"]) });
+
+ await module.saveStoredChatMessage(message("m1", "target"));
+ await module.saveStoredChatMessage(message("m2", "other"));
+ assert.deepEqual(attempts, ["m1", "m2"], "both are cached as refused");
+
+ module.clearServerOwnedChatMessages();
+ await module.saveStoredChatMessage(message("m1", "target"));
+ await module.saveStoredChatMessage(message("m2", "other"));
+
+ assert.deepEqual(
+ attempts,
+ ["m1", "m2", "m1", "m2"],
+ "the delete can free an id cached under any thread, so every entry goes",
+ );
+});
+
+test("pruning messages frees their ids too", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage(message("m1", "target"));
+ await module.syncStoredChatMessages("other", [], {
+ pruneMissing: true,
+ deletedMessageIds: ["m1"],
+ });
+ await module.saveStoredChatMessage(message("m1", "target"));
+
+ assert.deepEqual(attempts, ["m1", "m1"], "the id was freed, so retry it");
+});
+
+test("an ordinary sync does not clear the cache", async () => {
+ const { module, attempts } = harness({ rejectIds: new Set(["m1"]) });
+
+ await module.saveStoredChatMessage(message("m1", "target"));
+ await module.syncStoredChatMessages("target", [], { pruneMissing: false });
+ await module.saveStoredChatMessage(message("m1", "target"));
+
+ assert.deepEqual(attempts, ["m1"], "nothing was deleted, so nothing was freed");
+});
+
+test("the cache is bounded, so a long session cannot grow without limit", async () => {
+ const ids = Array.from({ length: 40 }, (_, index) => `m${index}`);
+ const { module, attempts } = harness({ rejectIds: new Set(ids) });
+
+ for (const id of ids) {
+ await module.saveStoredChatMessage(message(id));
+ }
+ assert.equal(attempts.length, 40, "each is refused once");
+
+ // Per id, not by re-walking: a bounded cache walked in insertion order misses every
+ // lookup by construction, measuring the walk rather than the bound.
+ await module.saveStoredChatMessage(message("m39"));
+ assert.equal(attempts.length, 40, "the newest entry is still suppressed");
+
+ await module.saveStoredChatMessage(message("m0"));
+ assert.equal(attempts.length, 41, "the oldest fell out of the cap and is sent again");
+});
+
+test("an ordinary failure still propagates", async () => {
+ const { module, attempts } = harness({ failWith: new Error("network down") });
+
+ await assert.rejects(
+ () => module.saveStoredChatMessage(message("m9")),
+ /network down/,
+ );
+ await assert.rejects(() => module.saveStoredChatMessage(message("m9")));
+ assert.deepEqual(attempts, ["m9", "m9"]);
+});
diff --git a/studio/frontend/tests/chat-thread-tombstone-clears-owned.test.ts b/studio/frontend/tests/chat-thread-tombstone-clears-owned.test.ts
new file mode 100644
index 00000000000..bf0e9ac0006
--- /dev/null
+++ b/studio/frontend/tests/chat-thread-tombstone-clears-owned.test.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Asserted at the source level: a future edit calling the tombstone helpers directly would
+// reintroduce the leak on whichever delete path a runtime test did not cover.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+const WRAPPERS = new Set(["forgetChatThread", "forgetChatThreads"]);
+const TOMBSTONES = new Set(["markChatThreadDeleted", "markChatThreadsDeleted"]);
+
+const MODULE_PATH = fileURLToPath(
+ new URL("../src/features/chat/utils/chat-history-storage.ts", import.meta.url),
+);
+
+function parseModule(): ts.SourceFile {
+ return ts.createSourceFile(
+ MODULE_PATH,
+ readFileSync(MODULE_PATH, "utf8"),
+ ts.ScriptTarget.ES2022,
+ true,
+ );
+}
+
+/** Names of functions calling `markChatThread(s)Deleted`, by enclosing declaration. */
+function tombstoneCallers(sf: ts.SourceFile): string[] {
+ const callers: string[] = [];
+ const visit = (node: ts.Node, enclosing: string | null): void => {
+ let scope = enclosing;
+ if (
+ (ts.isFunctionDeclaration(node) || ts.isMethodDeclaration(node)) &&
+ node.name &&
+ ts.isIdentifier(node.name)
+ ) {
+ scope = node.name.text;
+ }
+ if (
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ TOMBSTONES.has(node.expression.text)
+ ) {
+ const { line } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
+ callers.push(`${node.expression.text} at line ${line + 1} in ${scope ?? "<top level>"}`);
+ }
+ ts.forEachChild(node, (child) => visit(child, scope));
+ };
+ visit(sf, null);
+ return callers;
+}
+
+test("the tombstone helpers are only called from the wrappers that clear the map", () => {
+ const sf = parseModule();
+ const offenders = tombstoneCallers(sf).filter(
+ (entry) => ![...WRAPPERS].some((wrapper) => entry.endsWith(`in ${wrapper}`)),
+ );
+ assert.deepEqual(
+ offenders,
+ [],
+ "call forgetChatThread/forgetChatThreads instead, so server-owned markers are cleared too",
+ );
+});
+
+test("both wrappers exist and each clears the map", () => {
+ const text = readFileSync(MODULE_PATH, "utf8");
+ for (const wrapper of WRAPPERS) {
+ assert.match(
+ text,
+ new RegExp(`function ${wrapper}\\b`),
+ `${wrapper} must exist for the delete paths to use`,
+ );
+ }
+ const sf = parseModule();
+ const cleared: string[] = [];
+ const visit = (node: ts.Node, enclosing: string | null): void => {
+ let scope = enclosing;
+ if (ts.isFunctionDeclaration(node) && node.name) scope = node.name.text;
+ if (
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ node.expression.text === "clearServerOwnedChatMessages" &&
+ scope !== null
+ ) {
+ cleared.push(scope);
+ }
+ ts.forEachChild(node, (child) => visit(child, scope));
+ };
+ visit(sf, null);
+ for (const wrapper of WRAPPERS) {
+ assert.ok(
+ cleared.includes(wrapper),
+ `${wrapper} must call clearServerOwnedChatMessages`,
+ );
+ }
+});
+
+test("at least one real delete path is wired to a wrapper", () => {
+ const sf = parseModule();
+ const used: string[] = [];
+ const visit = (node: ts.Node): void => {
+ if (
+ ts.isCallExpression(node) &&
+ ts.isIdentifier(node.expression) &&
+ WRAPPERS.has(node.expression.text)
+ ) {
+ used.push(node.expression.text);
+ }
+ ts.forEachChild(node, visit);
+ };
+ visit(sf);
+ assert.ok(used.length >= 2, `expected the delete paths to use the wrappers, saw ${used}`);
+});