Repository navigation
Stop one slow SQLite writer from becoming a stream of Studio log errors - #9996
Conversation
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.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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.
|
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 fixes1. A non-busy 2. 3. 4. The server's own 409 wording was being replaced with a generic string. VerificationBackend, All 57 pass on the full matrix, run on real runners rather than emulated:
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, Backend suite: 806 passing with one failure, CompatibilityExisting installs already carry the unscoped trigger, so the migration drops it before creating the scoped one rather than relying on |
…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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…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.
…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.
…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.
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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.
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
## 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.  --------- Co-authored-by: Daniel Han <[email protected]>
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:
PUT /api/chat/threads/{t}/messages/{m}returning 409ChatMessageProtectedError, each with a full tracebackresearch.supervisor_iteration_failed->sqlite3.OperationalError: database is lockedPUT /api/settings/personalization, 36944 msGET /api/inference/audio/gallery/{id}/file, 21351 msGET /api/settings/download-transport, 3352 msTwo 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)instudio_db.get_connectionplus the supervisor'sawait 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 secondPUT /api/settings/personalizationcompletes.PRAGMA synchronouswas never set anywhere in the backend. Under WAL, sqlite still defaults toFULL, 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. Settingsynchronous=NORMALis 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_nextopenedBEGIN IMMEDIATEbefore knowing whether any row was claimable, atpoll_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 existingrow is Nonebranch already handles the row vanishing.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_lossa few lines above it. A non-transientOperationalErrorstill falls through to the traceback.chat_attachment_inventory_dirty_updatefiredAFTER UPDATEon any column. A generation status change touches onlymetadata_json(fromchat_generation_runs_dbandresearch_runs_db, which have no attachments to invalidate), and that marked the inventory dirty, leaving the next chat autosave toDELETEand re-hash every attachment in every thread insideBEGIN IMMEDIATE. Scoped toUPDATE OF attachments_json, content_json, the two columns_rebuild_chat_attachment_inventoryactually reads. Dropped and recreated rather thanIF NOT EXISTS, since existing installs already carry the unscoped trigger.The 409 storm
log_and_http_errorlogged at error withexc_inforegardless 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.
saveChatMessagenever inspectedresponse.status, so a 409 surfaced as an anonymousError, 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.saveChatMessagenow throws a typedChatMessageProtectedError, andsaveStoredChatMessagerecords 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, withclearServerOwnedChatMessagesto forget a thread. An ordinary transient failure still propagates to the caller that retries it.The existing
preserveServerManagedpre-check inruntime-provider.tsxalready 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 markingserverManaged. This makes the server's actual 409 authoritative.Slow capability reads
cached_xet_healthis documented as the path that must never load Unsloth Zoo, but it took_load_lock, the same lock_load_optionalholds acrossimport unsloth_zooand 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 onGET /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 forimport unsloth_zoothe first time, via theram_gatepath. I tried hoisting that load into the startup warm and reverted it:test_startup_defers_torch.pypins 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 syncdef, 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 withasyncio.to_threadand returns aFileResponserather 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_90ais Hopper and the GPU is Blackwell, and_C_mxfp8.cpython-310cannot 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 plussynchronous=NORMAL;claim_nextreturningNonewithout 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 withoutexc_infowhile 5xx keeps it; andclaim_nextstill 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 -bclean;biome checkidentical 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-hub1.29.0, and reproduce identically at the merge base.