Skip to content

Studio: server deadlocks with every thread blocked in sqlite3.connect() / close() and stops accepting connections #9008

Closed

Description

@sif332

Summary

After a few minutes of normal operation, unsloth studio stops responding entirely. The process stays alive and the listening socket stays open, but nothing is ever accepted or answered — curl http://127.0.0.1:8888/ on the same machine hangs until it times out. The process consumes 0 CPU; it is a deadlock, not a slowdown.

A py-spy dump shows six threads blocked inside SQLite connection open/close, spread across three different database files. Because one of them is the uvicorn server thread itself, the event loop can never return to accept(), so the outage is total rather than a slow endpoint.

This is reproducible enough to be a real availability problem: 7 of the server logs on this machine end with Timed out waiting for uvicorn server thread to stop, and 3 more end mid-request with no shutdown at all. Only a kill -9 recovers it.

Environment

unsloth 2026.8.18
unsloth_zoo 2026.8.12
Python 3.13.11
OS Ubuntu 24.04.3 LTS, kernel 6.17.0-20-generic
GPU RTX 4090, driver 590.48.01
torch 2.11.0+cu130
uvicorn / starlette / fastapi / anyio 0.52.1 / 1.6.0 / 0.141.1 / 4.13.0
Command unsloth studio -H 0.0.0.0 -p 8888

Observed behaviour

Server started at 21:15:03 and served the UI normally for 35 seconds. The last two log lines are at 21:15:38, then the log is silent forever. State 16 minutes later:

$ curl -m 10 http://127.0.0.1:8888/
curl: (28) Operation timed out after 10002 ms with 0 bytes received

$ ss -tlnp | grep 8888
LISTEN 17  2048  0.0.0.0:8888  0.0.0.0:*  users:(("unsloth",pid=3055214,fd=8))
         ^^ 17 completed connections queued, never accepted

# CPU consumed over a 5-second sample: 0 jiffies
# 75 OS threads: 74 in futex_do_wait, 1 in poll_schedule_timeout
# RAM free: 40 GB — not OOM.  GPU: 358 MiB — no model loaded.

Client sockets pile up in CLOSE-WAIT with the HTTP request still unread in the receive buffer:

CLOSE-WAIT 925  0  127.0.0.1:8888  127.0.0.1:43162
CLOSE-WAIT 1047 0  127.0.0.1:8888  127.0.0.1:59574
CLOSE-WAIT 929  0  127.0.0.1:8888  127.0.0.1:52116

The last request logged before the freeze was a cached-model delete:

21:15:37.681  POST   /api/hub/delete-impact              200
21:15:38.583  Deleted 1 file(s) for unsloth/Qwen3.8-27B-GGUF variant IQ4_NL: 15580.8 MB freed
21:15:38.583  DELETE /api/hub/delete-cached              200
21:15:38.698  GET    /api/inference/status               200   <-- last line ever written

I can't prove the delete is the trigger — it's simply the last distinctive thing that happened.

py-spy dump (the important part)

py-spy dump --pid 3055214, all threads reported idle:

Thread "Thread-1 (_run)"          <-- the uvicorn server thread
    get_connection            (studio/backend/auth/storage.py:274)
    get_user_and_secret       (studio/backend/auth/storage.py:673)
    _get_current_credential   (studio/backend/auth/authentication.py:282)
    get_current_subject       (studio/backend/auth/authentication.py:157)

Thread "asyncio_0" / "asyncio_2" / "asyncio_3"     (three threads, identical stack)
    get_connection            (studio/backend/storage/studio_db.py:1004)
    get_app_setting           (studio/backend/storage/studio_db.py:3521)
    _stored_cache_home        (studio/backend/utils/hf_cache_settings.py:115)
    get_hf_cache_paths        (studio/backend/utils/hf_cache_settings.py:153)

Thread "asyncio_1"
    get_app_setting           (studio/backend/storage/studio_db.py:3528)   <-- conn.close()
    _stored_cache_home        (studio/backend/utils/hf_cache_settings.py:115)
    get_hf_cache_paths        (studio/backend/utils/hf_cache_settings.py:153)
    _scope_spellings          (studio/backend/hub/utils/download_manifest.py:213)

Thread "asyncio_4"
    get_connection            (studio/backend/storage/studio_db.py:1004)
    claim_next                (studio/backend/storage/research_runs_db.py:684)

Thread "rag-folder-sync"
    get_connection            (studio/backend/storage/rag_db.py:298)
    reconcile_retired_scopes  (studio/backend/core/rag/folder_sync.py:719)
    _worker                   (studio/backend/core/rag/folder_sync.py:1740)

Thread "MainThread"           (the typer CLI, just Event.wait(timeout=1) — healthy)

The blocked source lines are all sqlite3 entry/exit points:

studio_db.py:1004   conn = sqlite3.connect(str(db_path), timeout = busy_timeout_seconds)
studio_db.py:3528   conn.close()
auth/storage.py:274 conn = sqlite3.connect(DB_PATH)
rag_db.py:298       conn = sqlite3.connect(str(db_path))

Analysis

Three observations that I think matter, in order of usefulness:

1. It spans three separate database files. studio.db, the auth DB and rag_db are different files, so this is not one database's write lock being held. sqlite3.connect() should not block on a busy lock at all — busy_timeout governs statement execution, not sqlite3_open_v2 — yet threads sat there for 16+ minutes at 0% CPU. That points below the application layer: a process-global mutex taken during open/close, or GIL starvation caused by a thread that stopped returning while holding it. Whichever it is, busy_timeout cannot rescue it, and two of the three call sites don't pass a timeout anyway.

2. Auth DB access runs on the uvicorn server thread. get_current_subject → _get_current_credential → get_user_and_secret → sqlite3.connect() executes synchronously on Thread-1 (_run). That is what turns a storage stall into a complete outage: the event loop never gets back to accept(), so even endpoints that touch no database — /api/health included — become unreachable. Any external health check therefore cannot distinguish "DB is wedged" from "process is gone". Moving that lookup off the loop thread would at least downgrade this failure from total outage to failing auth.

3. get_app_setting() opens and closes a fresh connection per call, on a hot path. get_hf_cache_paths() → _stored_cache_home() → get_app_setting() runs on ordinary hub endpoints, and each call is a full sqlite3.connect() / close() cycle. Four of the six blocked threads are on exactly this path. Caching the resolved cache paths, or reusing a connection, would cut the exposure window dramatically regardless of the underlying cause.

Recurrence

This is not a one-off. On this machine:

  • 7 server logs end with Timed out waiting for uvicorn server thread to stop — i.e. the uvicorn thread was already wedged when shutdown was attempted.
  • 3 more end mid-request with no shutdown sequence at all, the same signature as above.

Workaround

kill -9 and restart — SIGINT does not work, since the shutdown path itself waits on the wedged uvicorn thread. Because the process stays alive and the port stays open, Restart=always under a process supervisor does not help either; recovering automatically needs an external HTTP health probe with a timeout.

What would help

Even without a root cause for the mutex stall, any of these would turn a hard outage into a degraded one:

  • Get the auth DB lookup off the uvicorn event loop thread (point 2), so the server keeps accepting connections and /api/health keeps answering.
  • Cache get_hf_cache_paths() / _stored_cache_home() instead of hitting SQLite per request (point 3).
  • Consider a shared connection or a small pool per DB rather than connect-per-call, so open/close contention is bounded.

Happy to run further diagnostics — the machine reproduces this regularly and py-spy is installed on it.

Activity

  1. oobabooga commented on Aug 17, 2026

    @oobabooga
    Member

    Thanks for the detailed report. I tried to reproduce this against unmodified Studio 2026.8.18 using CPython 3.13.11 and matching reported web-stack versions. A concurrent HTTP stress run completed more than 66,000 requests, and a direct stress run completed 355,000 calls through the implicated database paths without a stall. I therefore have not reproduced the spontaneous freeze yet.

    Could you capture a native stack during the next freeze, before killing the process?

    studio_pid=<PID>
    py-spy dump --native --pid "$studio_pid" > /tmp/unsloth-9008-native.txt

    The existing dump shows the Python call sites, but the native frames should reveal what the threads are actually waiting on. Please attach that output and let us know whether cached-model deletion immediately preceded the freeze, or whether it also happens without a deletion. That should give us a focused next step.

  2. lastlich commented on Aug 17, 2026

    @lastlich

    I'm also on 2026.8.18 / Python 3.13.11 and hit the exact same freeze (py-spy stacks match yours
    line-for-line: auth/storage.py:274, studio_db.py:1004/3528, rag_db.py:298, authentication.py:282,
    get_hf_cache_paths, research_runs_db.py:684, folder_sync.py:719). A few extra observations from
    local debugging that may narrow it down:

    1. No OS-level file lock. While the process is fully wedged, a separate process can
      sqlite3.connect() and query all three DB files (auth.db, studio.db, rag.db) instantly.
      If a POSIX/fcntl lock were stuck on a -wal/-shm file it would block the external probe
      too. So the deadlock is inside the process (threading-level / libsqlite3 / GIL), not on disk.

    2. Not GIL starvation. At two separate dumps (hours apart) every thread is in
      TASK_INTERRUPTIBLE on a futex, none runnable, and py-spy reports no thread holding the GIL.
      No thread is spinning; they are all waiting.

    3. The freeze is permanent, not tied to the triggering stream. It started ~2 min after a
      very long SSE request (500k-context llama-server, 100k+ token prefill) began, and it stayed
      wedged for hours after that stream finished. Whatever lock is involved is never released;
      the long stream looks like a catalyst, not the ongoing cause.

    4. Plain write-lock contention is ruled out. Controlled repro: thread A holds
      BEGIN IMMEDIATE (RESERVED lock) for 60s while thread B runs sqlite3.connect +
      PRAGMA journal_mode=WAL + a SELECT — all complete in 0.0s (WAL readers don't block on a
      RESERVED lock). So it's not SQLITE_BUSY / busy_timeout behavior.

    5. check_same_thread is never overridden anywhere in the studio backend (all
      sqlite3.connect() calls use the default True). Worth auditing the paths that hand a
      connection across threads (e.g. the auth credential_generation_guard opens on one thread
      and commits/closes after a yield, and get_app_setting is a connect-per-call hot path).

    6. rag_db.py calls enable_load_extension(True) to load the sqlite_vec C extension —
      the freeze also parks threads in rag_db.py:298. If the deadlock is in a process-global
      sqlite/lock, this is another consumer that participates.

    Repro suggestions

    • py-spy only shows Python frames, so we couldn't see where inside sqlite3.connect it blocks
      (the likely process-global serialized-mode mutex in libsqlite3, or the _sqlite3 C module's
      connection registry). Two cheap upgrades:
      • Launch with PYTHONFAULTHANDLER=1 and faulthandler.register(SIGUSR1, chain=False) so a
        kill -USR1 <pid> dumps C-level frames for every thread (py-spy can't).
      • Reproduce under strace -f -e futex (or attach gdb) to see which futex each thread
        waits on and who owns it.
    • Given the freeze parks threads across three unrelated DB files simultaneously, I'd check the
      _sqlite3 C module (Python 3.13) for a module-global mutex taken on connect/close, and test
      whether opening/closing a connection from a different thread than the one that created it
      (with check_same_thread defaulting to True but the owner thread being wedged) can leave
      that mutex held.

    Happy to provide logs/py-spy dumps/thread stacks from my system if useful.

  3. oobabooga commented on Aug 19, 2026

    @oobabooga
    Member

    The dumps point to SQLite's process-wide VFS mutex (SQLITE_MUTEX_STATIC_VFS1). SQLite takes it around VFS open/close and WAL operations, so one file operation that never returns can block every database in the process. That also explains why busy_timeout has no effect here.

    I can reproduce the same stuck stacks by holding that mutex in an otherwise idle backend, and everything starts moving again as soon as I release it. So this is not the GIL.

    The remaining question is which filesystem call is getting stuck. While SQLite holds this mutex, it can be in open, close, fstat, stat, fcntl, ftruncate, or unlink somewhere under ~/.unsloth/studio/**. If it freezes again, this should identify the thread that owns the mutex; its backtrace should show the syscall:

    gdb -p <PID> -batch -nx \
      -ex 'set $m = (pthread_mutex_t *)((void*(*)(int))sqlite3_mutex_alloc)(11)' \
      -ex 'printf "owner_tid=%d\n", $m->__data.__owner' \
      -ex 'thread apply all bt 20'

    Could you also share the output of findmnt -T ~/.unsloth/studio? A network, FUSE, or encrypted mount there would give us a likely place to look next.

    #9234 mitigates the outage but does not fix this underlying stall. It keeps /api/liveness responding so a supervisor can restart the process. I'll leave this issue open while we track down the filesystem call.

  4. lastlich commented on Aug 19, 2026

    @lastlich

    Thanks for the analysis and mitigation, I did some more digging based on your findings and figured out that the stall was due to BTRFS chunk exhaustion on my system. So not really a Unsloth issue, but not stalling API on filystem IO stall for SQLite seem like a good idea anyways 👍 Here is a summary (AI) of the findings and mitigation on my machine:

    Status: root cause mitigated; wedge not reproduced under stress after filesystem remediation.

    Root cause hypothesis (confirmed by remediation)

    The SQLITE_MUTEX_STATIC_VFS1 stall traced to btrfs metadata-allocation exhaustion, not studio logic:

    • ~/.unsloth/studio sits on a LUKS-encrypted btrfs volume (/home, subvol @home) that was 100% chunk-allocated (device unallocated: 1.00 MiB), with metadata DUP at 84.7% used and autodefrag active (a btrfs kernel default — mere omission from fstab does not disable it; explicit noautodefrag is required).
    • With zero unallocated chunks, any metadata-heavy VFS op (open/close/fstat/ftruncate/unlink — exactly the syscalls named in the issue) can stall inside find_free_extent/do_chunk_alloc waiting on chunk reclamation. The stall is in-kernel lock contention, not disk I/O — consistent with the SSD appearing idle while frozen.
    • Historical bees dedup (on-demand, not running) compounds it: shared extents → backref amplification + COW on every SQLite write.

    Remediation applied

    1. Freed ~310 GiB of stale HF cache; ran targeted balance btrfs balance start -dusage=50 /home → unallocated: 1.00 MiB → 387 GiB.
    2. Removed autodefrag from fstab (noautodefrag), verified in /proc/mounts.

    Stress verification

    Sustained SQLite write pressure against the studio while a 500k-context generation ran:

    • 6,828 consecutive POST /api/auth/api-keys (~6-7/s for 30+ min) — each an auth.db INSERT + fsync via the same process-wide VFS path.
    • Studio /api/health responded 200 in ~2-4 ms the entire time. Zero freezes. Pre-fix, this workload class produced the exact deadlocked stacks from the issue.
    • the VFS1 mutex did not stall despite simultaneous WAL traffic + generation + memory pressure.

    Conclusion

    The wedge was caused by the filesystem state, not a defect in studio's SQLite usage. Keep #9234's liveness mitigation as defense-in-depth; if a freeze ever recurs, the gdb capture protocol (mutex type 11, owner_tid + thread apply all bt) is still armed, and wchan inspection of the frozen process is the cheap first check.

    Environment / setup notes

    • OS: Kubuntu 26.04, kernel default btrfs mount options on /home (subvol @home, LUKS).
    • Pre-fix btrfs state: allocated 2.94 TiB / 2.94 TiB, unallocated 1.00 MiB, metadata DUP 23 GiB / 19.48 GiB used (84.68%), statfs 95 %.
    • Post-fix btrfs state: allocated 2.56 TiB, unallocated 387 GiB, metadata 19.15 GiB used (83.28 %), statfs ~85 %.
  5. oobabooga commented on Aug 23, 2026

    @oobabooga
    Member

    I’m closing this as resolved. The evidence points to a host filesystem stall rather than a Studio defect, and #9234 adds the actionable mitigation on the Unsloth side. No further actionable Studio changes have been identified. @sif332, if this keeps happening, please let us know and we can reopen the issue.

  6. MakGulati commented on Aug 24, 2026

    @MakGulati

    Studio still deadlocks in SQLite VFS mutex path on ext4 despite #9234 mitigation — reproducible via HF cache inventory scan

    Summary

    We are seeing the same apparent SQLite/VFS deadlock described in this issue, but on ext4, and it remains reproducible on Unsloth 2026.8.19, which already contains the mitigation from #9234.

    The most reliable trigger we have found is opening Studio's "Select model" dropdown. This invokes the HF cache inventory path:

    GET /api/hub/gguf-variants / GET /api/hub/cached-gguf
    → cache_inventory.list_cached_gguf_response
    → local_inventory.py:_scan_hf_cache
    

    Server logs show the "Cached model scan" line immediately before the latest wedge.

    Once wedged, the process is genuinely deadlocked rather than merely slow: the process shows 0 CPU ticks over a 5-second interval, and Python threads are blocked in the same SQLite connection/VFS paths seen in this issue.

    Environment

    • Unsloth: 2026.8.19
    • Studio bundles the same Unsloth package/version
    • Filesystem: ext4
    • Studio: take common SQLite reads off the event loop thread #9234 mitigation: confirmed present in the installed source
    • Relevant source: main.py:1604 (/api/liveness and watchdog handling)
    • No administrator/root access on the machine
    • ptrace_scope=2, so py-spy/gdb cannot attach even to our own-user Studio process without elevated privileges

    Reproduction

    1. Start Unsloth Studio normally.
    2. Open Select model.
    3. The model picker requests the cached GGUF/model inventory.
    4. This enters:
    /api/hub/gguf-variants
    /api/hub/cached-gguf
        ↓
    cache_inventory.list_cached_gguf_response
        ↓
    local_inventory._scan_hf_cache
    
    1. Studio wedges within seconds.

    The latest reproduction was preceded by the server log:

    23:28:49 — Cached model scan
    

    followed by the deadlock.

    Stack evidence

    Our faulthandler dump is remarkably similar to the stacks reported in this issue.

    auth DB

    Our dump:

    auth/storage.py:274 get_connection
    

    This issue:

    auth/storage.py:274 get_connection
    

    Identical line-for-line.

    studio DB

    Our dump includes:

    studio_db.py:1034 / 3743
    get_connection / get_app_setting
    

    This issue includes the same call family:

    studio_db.py:1004 / 3528
    

    The line numbers shifted with the version, but the code path is the same.

    RAG DB

    Our dump:

    rag_db.py:313 get_connection
        ↓
    folder_sync.py:reconcile_retired_scopes
    

    This issue:

    rag_db.py:298 get_connection
    

    Again, the same database connection path.

    HF cache inventory path

    Our dump additionally shows:

    local_inventory.py:_scan_hf_cache
        ↓
    download_manifest.py:has_cancel_marker
        ↓
    hf_cache_settings.py:get_hf_cache_paths
        ↓
    studio_db.py:get_app_setting
    

    This is particularly interesting because the HF cache scan itself is the reproducible trigger for our issue.

    What we have ruled out

    We initially suspected filesystem pressure, since this issue was associated with btrfs chunk exhaustion.

    We freed approximately 60.7 GB of unused Hugging Face model caches, reducing disk usage from approximately 97% to 93%. The issue still reproduces.

    We also reduced the RAG folder-sync interval from 30 seconds to 30 minutes, because no RAG folders are configured and the worker was unnecessarily touching rag.db.

    Neither mitigation prevents the deadlock.

    We also inspected the HF cache after the cleanup:

    • no broken symlinks found
    • no dangling filesystem references found
    • Qwen3.8-27B cache structure is intact
    • other remaining model caches appear structurally valid

    There was one suspicious log message immediately before one reproduction:

    Recovered HF cache repo unsloth/Qwen3.8-27B-GGUF hidden by a dangling ref
    

    We do not currently know whether this is causal or merely a symptom of the cache inventory/reconciliation process, so we are not claiming cache corruption as the root cause.

    Relationship to #9234

    We confirmed that #9234 is already present in our installed 2026.8.19 source. The /api/liveness implementation contains the watchdog/grace-period handling described by that mitigation.

    Despite that mitigation, the underlying SQLite/VFS deadlock remains reproducible.

    This suggests that the remaining problematic SQLite operation may still be occurring on a path that can block on the process-global VFS mutex, or that the HF-cache inventory path is exposing a related VFS-level stall not covered by the mitigation.

    Current limitation

    We cannot obtain the native-level evidence needed to identify exactly which syscall is holding the VFS1 mutex.

    py-spy was tested directly and fails with Permission Denied when attaching to the Studio process, including a process running as our own user. This is consistent with the machine's ptrace_scope=2.

    Therefore, without administrator access, we are limited to the Python-level faulthandler dumps generated from inside the process.

    Conclusion

    At this point, our evidence strongly suggests that this is the same underlying SQLite/VFS mutex deadlock described in this issue, but with a different environmental trigger:

    Select model
        ↓
    HF cache inventory (_scan_hf_cache)
        ↓
    SQLite/cache-settings access + filesystem metadata operations
        ↓
    VFS-level stall
        ↓
    process-global SQLite VFS mutex contention
        ↓
    auth.db / studio.db / rag.db connections block
        ↓
    Studio becomes completely unresponsive
    

    The key differences from this issue:

    The Python-level stack signatures remain extremely close to those reported here.

    Could you advise whether there is another known VFS/filesystem trigger for this mutex deadlock on ext4, or whether there is a recommended way to capture the native mutex-owner/syscall information without root access?

    We can provide the full faulthandler wedge dump and the relevant server logs if useful.

  7. danielhanchen commented on Aug 28, 2026

    @danielhanchen
    Member

    Auth reads moved off the event loop, but /api/auth/login and the cached GGUF inventory scan still open SQLite on it, so the stall you reported is still reachable.

  8. MakGulati commented on Sep 4, 2026

    @MakGulati

    Auth reads moved off the event loop, but /api/auth/login and the cached GGUF inventory scan still open SQLite on it, so the stall you reported is still reachable.

    I don't understand entirely. Is it fixed in the recent PRs or not still pending bug?

  9. danielhanchen commented on Oct 11, 2026

    @danielhanchen
    Member

    Fixed! Sorry on the delay. Some Python builds bundle SQLite 3.51.0 or 3.51.1, which can deadlock when two threads open or close the same database at once, and once that happens every database in Studio hangs. #10069 guarded studio.db, and #13307 now puts the login and RAG databases behind the same guard, so the freeze can no longer happen on those SQLite versions.
    To update: Unsloth Desktop will have an update banner. For Studio, use unsloth studio update. For Docker, use docker exec <container> unsloth-studio-update. Reopen if it still happens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions