Skip to content

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

Merged
danielhanchen merged 11 commits into
mainfrom
fix/studio-log-errors
Aug 30, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
fix/studio-log-errors

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What prompted this

A Studio session on Colab produced 60 error-level events in four minutes, plus four requests slow enough to look like hangs. Aggregating the log gives the whole set:

count signature
54 PUT /api/chat/threads/{t}/messages/{m} returning 409 ChatMessageProtectedError, each with a full traceback
6 research.supervisor_iteration_failed -> sqlite3.OperationalError: database is locked
1 PUT /api/settings/personalization, 36944 ms
1 GET /api/inference/audio/gallery/{id}/file, 21351 ms
1 GET /api/settings/download-transport, 3352 ms

Two of these turn out to be one event seen from opposite sides.

The 37 second write and the lock spam are the same bug

The six lock errors land at 02:29:35, :41, :48, :54, 02:30:00 and 02:30:06, and nowhere else in the session. The cadence is arithmetic, not noise: sqlite3.connect(timeout=5.0) in studio_db.get_connection plus the supervisor's await asyncio.sleep(1) is exactly six seconds. Six consecutive cycles means one writer held studio.db's lock continuously for the whole window, and the last error is in the same second PUT /api/settings/personalization completes.

PRAGMA synchronous was never set anywhere in the backend. Under WAL, sqlite still defaults to FULL, which fsyncs on every commit while holding the writer lock. With a multi-GB GGUF download saturating the same disk, one commit blocked for 37 seconds. Setting synchronous=NORMAL is the documented safe pairing for WAL: it can lose the last transactions on host power loss, never corrupts the database, which is the right trade for a local UI's settings and chat history.

Three related changes fall out of that:

  • claim_next opened BEGIN IMMEDIATE before knowing whether any row was claimable, at poll_seconds=0.5. An idle Studio therefore took the writer lock twice a second for the life of the process. It now probes with a read first and only escalates when there is work. The probe is advisory; the existing row is None branch already handles the row vanishing.
  • The supervisor logged this with logger.exception, so a transient, expected contention outcome produced a full multi-line traceback. It now logs one warning line and backs off, mirroring _finish_after_lease_loss a few lines above it. A non-transient OperationalError still falls through to the traceback.
  • chat_attachment_inventory_dirty_update fired AFTER UPDATE on any column. A generation status change touches only metadata_json (from chat_generation_runs_db and research_runs_db, which have no attachments to invalidate), and that marked the inventory dirty, leaving the next chat autosave to DELETE and re-hash every attachment in every thread inside BEGIN IMMEDIATE. Scoped to UPDATE OF attachments_json, content_json, the two columns _rebuild_chat_attachment_inventory actually reads. Dropped and recreated rather than IF NOT EXISTS, since existing installs already carry the unscoped trigger.

The 409 storm

log_and_http_error logged at error with exc_info regardless of status code, so a 409 the caller is expected to handle was indistinguishable from a server fault. 4xx now logs a single warning line; 5xx keeps error plus traceback, which is where a stack is actually the only way to find the bug.

That alone silences the log, but the requests were still real. saveChatMessage never inspected response.status, so a 409 surfaced as an anonymous Error, and the per-chunk autosave re-sent the same message on the next chunk for the length of the generation. A 409 here is permanent, since the server owns the message, so backing off cannot help and only stopping will do.

saveChatMessage now throws a typed ChatMessageProtectedError, and saveStoredChatMessage records the id and skips subsequent saves for it. Handling it in the shared wrapper covers all three per-chunk callers at once. Scoped per thread so a reissued id elsewhere is unaffected, with clearServerOwnedChatMessages to forget a thread. An ordinary transient failure still propagates to the caller that retries it.

The existing preserveServerManaged pre-check in runtime-provider.tsx already documents this failure mode ("265 PUTs, 256 rejected"), but it is a heuristic guess ahead of the request rather than a reaction to the server's answer, and it is bypassed for messages the server protects without marking serverManaged. This makes the server's actual 409 authoritative.

Slow capability reads

cached_xet_health is documented as the path that must never load Unsloth Zoo, but it took _load_lock, the same lock _load_optional holds across import unsloth_zoo and the torch import behind it. So the one read guaranteed not to load Zoo blocked for as long as another thread spent loading it. That is the 509 ms on GET /api/studio/download-transport-capabilities. It now reads the memo without the lock: a dict lookup keyed by a plain string is atomic under the GIL, and the only writers publish a fully built module in a single assignment, so the worst outcome is correctly answering "not loaded yet".

Deliberately not changed

GET /api/settings/download-transport (3352 ms) is the request that pays for import unsloth_zoo the first time, via the ram_gate path. I tried hoisting that load into the startup warm and reverted it: test_startup_defers_torch.py pins the invariant explicitly, "the optional Hub/Xet integration must be loaded by a real download, not startup", and loading Zoo at boot would import torch on every host including the CPU-only ones those RAM caps exist to protect. The handler is a sync def, so it runs in the threadpool and never blocks the event loop, and the cost is once per process. Worth revisiting separately if the first-poll latency matters, but not by breaking that invariant.

GET /api/inference/audio/gallery/{id}/file (21351 ms) needs no change. The handler already offloads its ownership check with asyncio.to_thread and returns a FileResponse rather than bytes, and the API routes are not gzipped. The latency is the saturated disk and threadpool from the section above.

The torchao warnings in the same log are benign: _C_cutlass_90a is Hopper and the GPU is Blackwell, and _C_mxfp8.cpython-310 cannot load on Python 3.13. Both are optional extension probes that fall back cleanly.

Tests

New studio/backend/tests/test_studio_db_write_lock_contention.py, 5 tests: WAL plus synchronous=NORMAL; claim_next returning None without error while another connection holds the writer lock, which is the original failure reproduced exactly; a metadata-only update not dirtying the attachment inventory while an attachment change still does; 4xx logging without exc_info while 5xx keeps it; and claim_next still claiming real work, so the read-first probe is an optimisation and not a suppression.

New studio/frontend/tests/chat-save-server-managed-stop.test.ts, 6 tests: five chunks producing exactly one PUT; the rejection resolving rather than throwing so the recovery loop keeps following the stream; only the rejected id blocked; the same id in another thread unaffected; clearing letting a reissued id save again; and an ordinary failure still propagating and not being mistaken for server ownership.

Also green: 560 tests across the research, chat history, utils and logging suites; 505 across the changed areas (chat attachments, generation runs, personalization, download transport, xet fallback, warm); the full 5976-test frontend suite; tsc -b clean; biome check identical to baseline on the touched source files.

A full-suite branch-versus-baseline comparison is still running and I will follow up with the diff. The failures already present on this box are environmental, including four modules that will not import against this venv's huggingface-hub 1.29.0, and reproduce identically at the merge base.

A Colab session produced 60 error-level events in four minutes: 54 rejected chat
message saves and six "database is locked" tracebacks. Both were symptoms rather
than faults, and the same 37-second window explains the slow requests alongside
them.

studio.db never set PRAGMA synchronous, so WAL ran at the FULL default and every
commit fsynced while holding the writer lock. With a multi-GB GGUF download
saturating the same disk one commit blocked for 37s, which is the whole of
PUT /api/settings/personalization's 36944ms. Use NORMAL, the documented safe
pairing for WAL.

While that lock was held the research supervisor logged a full traceback every
six seconds -- exactly its 5s busy timeout plus its 1s retry sleep. It polls
claim_next twice a second forever and claim_next opened BEGIN IMMEDIATE before
knowing whether any row was claimable, so an idle Studio took the writer lock
2x/second for the life of the process. Probe with a read first, and treat losing
the race as the ordinary outcome it is: one warning line, not logger.exception.

The attachment-inventory UPDATE trigger fired on any column, so a generation
status change -- metadata_json only, from chat_generation_runs_db and
research_runs_db -- marked the inventory dirty and left the next chat autosave to
DELETE and re-hash every attachment in every thread inside BEGIN IMMEDIATE. Scope
it to the two columns the rebuild actually reads.

log_and_http_error logged at error with exc_info regardless of status, so a 409 a
caller is expected to handle was indistinguishable from a server fault. 4xx now
logs one warning line; 5xx keeps its traceback.

The 409s themselves came from the per-chunk autosave: saveChatMessage never
inspected response.status, so the rejection surfaced as an anonymous Error and
the next chunk re-sent it ~300ms later for the length of the generation. Throw a
typed ChatMessageProtectedError and have saveStoredChatMessage record the id and
stop, since retrying a message the server owns can never succeed. A transient
failure still propagates.

Finally, cached_xet_health took the same process-wide lock that _load_optional
holds across `import unsloth_zoo`, so the one capability path defined never to
load Zoo blocked for as long as another thread spent loading it -- the 509ms on
GET /api/studio/download-transport-capabilities. Read the memo without the lock;
a dict lookup keyed by a plain string is atomic under the GIL.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-30T10:34:58.338909Z 887b57e Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

Reviewing the change adversarially and simulating it across platforms turned up
four real problems in it.

The supervisor's new OperationalError branch re-raised anything that was not a
busy error. A sibling `except Exception` cannot catch a raise from its own
ladder, so that escaped the while loop and stopped the supervisor for the life
of the process -- worse than the log noise it was removing, and silent. Both
paths now sleep and continue; only the busy one is quietened, and a real fault
keeps the traceback it had before.

synchronous=NORMAL was applied unconditionally. It is only safe under WAL, and
`PRAGMA journal_mode=WAL` silently declines on filesystems without shared-memory
support -- network shares and some FUSE or container mounts, which Windows users
hit most often -- leaving the file on a rollback journal where NORMAL drops the
fsync that keeps it consistent. It now reads the journal mode actually in force
and leaves those installs on FULL, and is applied after the schema block so a
brand new database has already been switched to WAL.

The busy predicate existed twice, once here and once in api_usage_db. One
definition now, in the module that owns the contended file.

On the frontend, ChatMessageProtectedError replaced the server's own message
with a generic one. The autosave never shows it, but update-thread-message
rethrows it after rolling the UI back and the user sees that text, so the server's
detail is now carried through. The 409 body is read once, since a Response body
is single-use and letting parseJsonOrThrow read it again would raise a TypeError
that masked the conflict. clearServerOwnedChatMessages was also exported but
never called, so the per-thread map only ever grew; thread tombstoning now goes
through forgetChatThread/forgetChatThreads, with a source-level test so a future
direct call cannot quietly reintroduce the leak.

Tests: the contention suite covers the WAL gate across journal modes and
unreadable pragma answers, the trigger scope column by column, the upgrade path
from the unscoped trigger and the downgrade back to older Unsloth, claim_next
against every run status plus lease expiry and eight concurrent workers, the
busy predicate, and the supervisor ladder including the regression above. 57
cases, green on Linux x64 and arm64, macOS arm64 and Intel, Windows x64 and
arm64, and Python 3.10, 3.12 and 3.13.
@danielhanchen

Copy link
Copy Markdown
Member Author

Pushed a follow-up commit that fixes four things I found reviewing my own first pass, plus the test coverage that would have caught each of them.

What the follow-up fixes

1. A non-busy OperationalError could kill the research supervisor for the life of the process.
The first pass caught sqlite3.OperationalError, logged a warning if it looked like lock contention, and re-raised otherwise. A raise inside one except clause cannot be caught by a sibling except Exception on the same try, so anything that was not a busy error escaped the while loop and the supervisor never came back. That is strictly worse than the behaviour being fixed. Now both branches log and back off, differing only in level and whether a traceback is attached.

2. PRAGMA synchronous=NORMAL was applied unconditionally.
NORMAL is the documented, corruption-safe pairing for WAL, but it is not safe for a rollback journal, where the commit fsync is what makes the commit durable. PRAGMA journal_mode=WAL silently declines on filesystems without shared memory, which is a real case: network shares and some FUSE and container mounts, most often on Windows. The pragma is now applied only after reading back journal_mode and confirming WAL, and an unreadable or failing pragma keeps the safe default rather than raising.

3. clearServerOwnedChatMessages was dead code.
The server-owned message map is keyed by thread and nothing ever removed entries, so it only grew across a long session. Thread tombstoning is the point those ids stop mattering, so the two are now paired in forgetChatThread / forgetChatThreads, and all four delete call sites go through the wrappers.

4. The server's own 409 wording was being replaced with a generic string.
The autosave only needs to know "the server owns this, stop", but saveChatMessage has a second caller: a manual message edit rolls the UI back and rethrows, and that text is shown to the user. The typed error now carries the server's detail when there is one, and falls back to generic text only when the body is missing or unparseable. The body is read exactly once, since a Response body is single-use and a second read would throw a TypeError masking the real conflict.

Verification

Backend, studio/backend/tests/test_studio_db_write_lock_contention.py, 57 tests covering: the WAL gate across delete / truncate / persist / memory journal modes; unreadable and failing pragma answers; 16 concurrent openers; durability across a reopen; the trigger scope matrix including the fact that AFTER UPDATE OF fires on the SET list rather than on a changed value; upgrade from the old unscoped trigger and downgrade safety; claim_next across every run status, lease expiry, a missing thread claim, and 8 concurrent workers; the busy-error predicate; the supervisor error taxonomy including a direct regression test for item 1; and 4xx versus 5xx logging.

All 57 pass on the full matrix, run on real runners rather than emulated:

OS Arch Python
Windows Server 2025 x64 3.10, 3.12, 3.13
Windows 11 ARM64 3.12
macOS 14 arm64 3.12
macOS 15 Intel x64 3.12
Linux x64 3.10, 3.12, 3.13
Linux ARM64 3.12

That spans sqlite 3.45.1 and 3.49.1. There is no GPU or hardware dimension to test here: the changes are SQLite pragmas, one poll query, log levels and TypeScript, so nothing branches on device.

Frontend: 16 targeted tests across the three new files, the full suite at 5992 passing, tsc -b clean, and biome output byte-identical to the merge base. No new browser API is used, and the frontend targets ES2022, so class extends Error is native and instanceof ChatMessageProtectedError holds under the transpiled output. Vite's default modules target covers Chrome 87+, Firefox 78+, Safari 14+ and Edge 88+, which is unchanged by this PR.

Backend suite: 806 passing with one failure, test_detection_sets_still_resolve_under_their_old_names, which fails identically at the merge base and is unrelated to this branch.

Compatibility

Existing installs already carry the unscoped trigger, so the migration drops it before creating the scoped one rather than relying on CREATE TRIGGER IF NOT EXISTS, which would have silently kept the old one forever. In the other direction, an older Unsloth opening a database created by this version sees its own CREATE TRIGGER IF NOT EXISTS no-op against the scoped trigger, and the scoped trigger still fires for every real inventory input, so the older code path stays correct. synchronous is a per-connection pragma, so an older build simply opens at FULL again with no on-disk consequence.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added 2 commits August 30, 2026 07:55
…ssage id

A 409 from PUT /threads/{t}/messages/{id} is not proof that the server owns the
message for good. The route answers 409 for ChatMessageConflictError as well, so
a message id that collides with another thread was being cached as server-owned
and every later save returned locally without persisting, losing the message on
reload. And even a genuinely protected message can be refused transiently:
_safe_generation_assistant_update rejects an autosave whose generationSeq lost
the race to the producer while still permitting the later monotonic and terminal
writes, which are the ones carrying contextUsage, timings and response details.

Key the marker on a stable serialization of the payload instead. A byte-identical
resend is still dropped, which is what the 54-PUT storm was, and any payload the
client has moved on from is sent. The serialization sorts keys so two call sites
building the same record in different property order do not reopen the storm.

Also fix the test typecheck: tsconfig.test.json covers tests/, and the module
type declared the constructor as returning a bare Error, so threadId and
messageId did not exist on the narrowed type.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 31e5f8866c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1009 to +1014
const payload = stableStringify(message);
if (rejectedChatMessagePayloads.get(message.threadId)?.get(message.id) === payload) {
// This exact payload was just refused, so the server's copy is authoritative for it;
// returning the caller's record keeps the optimistic UI intact without another doomed
// round trip. Any payload the client has since moved on from falls through and is sent.
return message;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Cache permanent protection across changing chunks

When a permanently server-owned message bypasses the existing metadata pre-check, every streamed chunk changes its content or metadata, so this exact-payload comparison misses and every chunk still issues another rejected PUT and warning log. The newly added growing-content test explicitly confirms one request per changed chunk, which is fresh evidence that the original request storm remains for permanently protected rows; distinguish permanent ownership from stale-sequence or ID conflicts and suppress the permanent case by message identity.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not taking this one, because as written it undoes the previous round.

The remedy asked for here, suppressing the permanent case by message identity, is exactly what 3888657156 correctly objected to one round ago: a stale-generationSeq rejection is transient, and muting the id drops the terminal write that carries contextUsage, timings and response details. The growing-content test is not fresh evidence of a regression, it is the behaviour that item asked for. I cannot both suppress by identity and retry later monotonic updates without knowing which kind of 409 arrived, and the route gives the client no way to tell: chat_history.py:1347 maps ChatMessageConflictError and ChatMessageProtectedError onto the same status, and safe_curated_detail only redacts paths.

On reachability. The changing-payload case needs a row the server owns whose local copy lacks serverManaged, since runtime-provider.tsx:1963 short-circuits before any request when it is set. The storm actually observed was the run's user message, which the server protects but never marks, and whose payload does not change across chunks, so it does collapse to one request. I have no session showing the remaining combination, and this PR does not introduce it: before the change there was no suppression at all, so every case here is strictly better, not worse.

Distinguishing the two properly means a machine-readable code on the 409. Adding a sibling key changes the shape of detail for every existing client, and a header is not readable cross-origin because the CORS middleware sets no expose_headers. That is a protocol change worth doing on its own, with its own compatibility story, rather than folded into a contention fix.

DDL does not open a transaction under sqlite3's legacy transaction control, which
issues an implicit BEGIN only before INSERT, UPDATE, DELETE and REPLACE. The bare
DROP + CREATE pair therefore ran in autocommit, so two processes opening the same
studio.db with their own _schema_ready could interleave as drop/drop/create/create
and the second CREATE would raise "trigger already exists" out of get_connection,
failing to open the database at all.

Three guards, in order of how often they matter: skip the migration entirely once
sqlite_master shows the scoped trigger, so the common path takes no writer lock;
hold BEGIN IMMEDIATE across the drop and the create, so nobody observes the table
without its trigger; and keep IF NOT EXISTS on the create, so even a lost race
cannot raise.

Read the trigger SQL as row[0] rather than row["sql"], since _ensure_schema also
runs on connections whose row_factory is still the default tuple.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…hread's

A 409 on this route can also mean the message id already belongs to a different
thread. That rejection is recorded under the thread being written to, so deleting
the thread that actually owns the id frees it while the stale entry sits somewhere
else in the map. The next attempt carried the same bytes, so it was skipped as a
resend and returned success without persisting anything, and the message was gone
after a reload.

Clearing per thread cannot cover that, since the freed id may be cached under any
other thread. Deleting a thread is rare and user-driven, so the whole cache goes
and the cost is at most one extra request per protected message.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…hread goes

Deleting a single message calls syncStoredChatMessages with pruneMissing, and the
backend removes the row while the thread survives, so no tombstone runs and the
thread-deletion clear never fires. The id is free but the cross-thread collision
is still cached, so the identical payload was skipped as a resend and the message
stayed absent after a reload.

Clear on any sync that actually asked for deletions. Gated on pruneMissing or a
non-empty deletedMessageIds rather than on every sync, since an ordinary sync runs
constantly and clearing there would put the request storm straight back.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…cache

PUT /threads/{t}/messages/{id} answers 409 both for a protected message, where the
server owns the row and the autosave should stop, and for a thread-id collision,
where the id belongs to another thread and the caller has to see the failure.
Mapping every 409 to ChatMessageProtectedError meant saveStoredChatMessage
swallowed a collision and returned the unsaved record as though it had persisted,
so an append or a research startup carried on while the message was missing and
gone after a reload. Before this branch that path threw, so this was a regression
introduced here.

The kind now rides in an X-Unsloth-Conflict-Kind response header, set at all three
409 sites in chat_history.py and listed in the CORS expose_headers so a Studio on
tauri://localhost or a tunnel can read it; allow_headers governs the request side
only. detail stays a plain string, so no existing client changes. Anything without
the header, including an older backend, falls through to the ordinary error path,
which is what happened before the branch.

Bound the rejected-payload cache at 32 entries with least-recently-used eviction.
Each entry holds a whole serialized message, generated content included, and the
only clears are the delete paths, so a long-lived tab that never deleted anything
kept one copy of every long response for the session. A hit refreshes the entry's
age, or the message being resent right now would be the one aging out.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 607c30598e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

test_studio_evaluated_unions_do_not_grow counts studio files that evaluate PEP 604
unions on the declared 3.9 floor, and the two files touched by the conflict header
pushed it from 35 to 37. Written as Optional rather than fixed with a module-wide
`from __future__ import annotations`, which matches what utils.py already imports
and does not change annotation evaluation for the rest of either file.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 30, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: e3124a2943

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 887b57e334

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 2ea71d2 into main Aug 30, 2026
54 of 56 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-log-errors branch August 30, 2026 10:36
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 19, 2026
## Summary

On Google Colab during a large GGUF download, `POST /api/auth/refresh`
returned 500 `sqlite3.OperationalError: database is locked` after about
5 s (raised at `BEGIN IMMEDIATE` in `consume_refresh_token`), and
Unsloth Studio signed the user out even though the refresh token was
still valid.

There were four causes. auth.db kept SQLite's default `synchronous=FULL`
under WAL, so every commit fsyncs while holding the write lock. It also
had no long-lived connection, so the last close ran a checkpoint inside
the process-wide `sqlite_gate` lock. `/api/auth/refresh` was `async def`
and ran the blocking SQLite busy wait on the event loop, which stalled
the whole server. Finally, the frontend cleared both tokens on any
non-OK refresh response. studio.db already had `synchronous=NORMAL` and
a WAL keeper (unslothai#9945, unslothai#9996); auth.db now gets the same treatment, and a
busy auth.db no longer ends the session.

## Changes

- auth.db switches to `synchronous=NORMAL` when it is in WAL mode. The
lifespan holds one WAL keeper connection for the server's lifetime.
`is_busy_error` and `apply_wal_synchronous` move from `studio_db.py` to
`storage/sqlite_gate.py` so both databases share them, and the old names
in `studio_db` remain as aliases.
- `/api/auth/refresh` is now a sync route, so it runs off the event
loop. The new `rotate_refresh_token` deletes the old token and inserts
the new one in a single `BEGIN IMMEDIATE` transaction. A busy auth.db
rolls back and returns 503 with `Retry-After: 2`, and the old token
stays valid. `Retry-After` is added to the CORS exposed headers.
- If `validate_api_key_account` finds auth.db busy, it skips the
`last_used_at` update and validates read-only. The request no longer
fails with 500.
- The frontend clears tokens only when refresh returns 401. On 503 or
429 it retries up to 3 times within an 8 s budget, following
`Retry-After`. Any other failure keeps the session, and the route guard
counts a surviving refresh token as signed in. `refreshSessionOutcome()`
returns `ok`, `rejected` or `unavailable`, and `refreshSession()` still
returns a boolean.

Behavior notes:

- `test_config_mutations_on_event_loop.py` now lists `/refresh` among
the off-loop routes, because the rotation is atomic in storage and no
longer depends on the event loop for serialization.
- `synchronous=NORMAL` can lose the last commits on a power loss or OS
crash, but not on an application crash. This is the same trade-off as
unslothai#9996.
- In the desktop app, a refresh that gets no answer now returns the
original 401 instead of falling through to desktop auto-auth.

## Testing

Fault-injection A/B on a local Unsloth Studio, main `475a02ac18` vs this
branch:

- S1: another connection holds the auth.db write lock for 8 s.
- S2: `fdatasync` on `auth.db-wal` is delayed 7 s via `LD_PRELOAD`.
- S3: an API-key request is sent while the lock is held.

| Scenario | main | this branch |
|---|---|---|
| S1 refresh | 500 after 5060 ms, `/api/health` up to 4871 ms | 503 +
`Retry-After: 2` after ~5 s, `/api/health` max 230 ms; the same refresh
token returns 200 after release; a reused token still returns 401 |
| S2 refresh | 500 after 5047 ms, `/api/health` stalled 5258 ms | 200 in
13 ms |
| S2 fsyncs (3 refreshes, fault disarmed) | 18 WAL + 6 main-file fsyncs
| 0 auth.db fsyncs |
| S3 API-key request | 500 | 200 (`last_used_at` update skipped) |
| `PRAGMA synchronous` on auth.db | 2 (FULL) | 1 (NORMAL) |

A cross-origin (`tauri://localhost`) 503 exposes `Retry-After` via CORS.

Automated checks:

- New `studio/backend/tests/test_auth_db_lock_contention.py` plus
`test_config_mutations_on_event_loop.py` and
`test_studio_db_write_lock_contention.py`: 98 passed (`pytest -n 2`).
- Broader backend auth, account, credential, desktop, middleware,
API-key and studio_db test families: 1806 passed, 16 failed. The same 16
fail on clean main on this host (missing `av` module and sqlite-vec
extension).
- Frontend: new `tests/auth-refresh-transient.test.ts` 14/14. All 91
frontend test files that touch auth: 1073/1073. `npm run typecheck`
(tsc) is clean.

```bash
cd studio/backend
python -m pytest -n 2 tests/test_auth_db_lock_contention.py tests/test_config_mutations_on_event_loop.py tests/test_studio_db_write_lock_contention.py
```


## Before / after

The app loaded with an expired access token while another connection
held the auth.db write lock for 16 s (merge base `475a02ac1` vs head
`ae419121f`, each on its own fresh Studio install).

- Before: `/api/auth/refresh` answered 500, both tokens were cleared and
the page went to the login screen.
- After: `/api/auth/refresh` answered 503 twice (retried within the
budget), the refresh token was kept and the page stayed in the app.

![Before: signed out to the login screen. After: still in the
app.](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/14151/pr14151_auth_busy_before_after-836515eee83c.png)

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant