Skip to content

Studio: keep users signed in when auth.db is busy - #14151

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
Etherll:fix/inline-auth-db-locked-29f2f996
Oct 19, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
Etherll:fix/inline-auth-db-locked-29f2f996

Conversation

@Etherll

@Etherll Etherll commented Oct 18, 2026 •

Copy link
Copy Markdown
Collaborator

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 (#9945, #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 Stop one slow SQLite writer from becoming a stream of Studio log errors #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.
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.

Under heavy disk IO (a large GGUF download on Colab), POST /api/auth/refresh
waited out the 5 s busy timeout on the event loop, returned 500 "database is
locked", and the frontend then cleared a refresh token that was still valid.

- auth.db uses synchronous=NORMAL when it is in WAL and keeps one WAL keeper
  connection for the server's lifetime, matching studio.db (unslothai#9945, unslothai#9996).
- /api/auth/refresh runs off the event loop and rotates the refresh token in
  one BEGIN IMMEDIATE transaction. A busy database answers 503 with
  Retry-After (exposed via CORS) and leaves the old token valid.
- An API-key request whose last_used_at touch hits a busy auth.db is still
  accepted instead of failing with 500.
- The frontend clears tokens only on a 401 from refresh, retries 503/429 a
  bounded number of times, and keeps the session (and route guards) on any
  other failure.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 18, 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-10-19T09:18:08.304926Z 82e81e7 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.

…nds auth.db busy

The change-password form and the desktop app's managed-account startup still
read refreshSession()'s false as a rejected token and cleared both tokens, so a
busy auth.db could still sign the user out there. Both now use the refresh
outcome: a rejected refresh clears the session as before, while an unanswered
one keeps it. The form asks the user to try again, and the forced desktop
startup probe releases the startup screen without opening the login page.
@danielhanchen

danielhanchen commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Update after the latest run:

danielhanchen added a commit that referenced this pull request Oct 18, 2026
## Summary

`(Python 3.13, l-r)` fails on main at `6069a27a`, and on PRs based on it
such as #14151:

```
studio/backend/tests/test_log_budget.py::test_every_classified_path_is_in_a_scenario
AssertionError: these paths are classified in loggers/handlers.py but no scenario in tests/log_budget/session.py polls them, so their log volume is unmeasured:
    /api/inference/images/prompt-upsampler/status
```

#14137 (FLUX.3 prompt upsampling) added
`/api/inference/images/prompt-upsampler/status` to
`_QUIET_SUCCESS_PATHS` in `loggers/handlers.py`, with the note "Polled
by the Images page while the FLUX.3 prompt upsampler downloads". It did
not add the path to either log-budget scenario. The guard is right to
fail: every classified poll needs a cadence so the idle and busy
envelopes stay honest. The product is fine.

## Change

`studio/backend/tests/log_budget/session.py` adds the path to
`BUSY_POLLS` at `(1.0, "declared")`.

The cadence comes from `usePromptUpsamplerStatus` in
`studio/frontend/src/features/images/prompt-enhance-panel.tsx`:
- It reads the status once when the panel becomes active.
- After that it reads every 1000 ms only while `download.downloading` is
true.

It is therefore busy-only, at the same 1 s as the other
download-progress polls. `tests/studio/playwright_declared_polls.py`
reads the same `ALL_POLLS`, so the browser check knows the path too.

## Testing

- `studio/backend/tests/test_log_budget.py`: 8 passed. On main without
this change, `test_every_classified_path_is_in_a_scenario` fails with
the error above.
- `test_log_signal_floor.py` and `test_research_runs_hardening.py`,
which also import the scenario module: 328 passed.
danielhanchen added a commit that referenced this pull request Oct 19, 2026
…upsampler tests (#14169)

## Summary

`(Python 3.13, a-k)` failed three of #14137's new FLUX.3 prompt
upsampler tests on #14151's run (base `def3451e`), on two different
xdist workers:

```
tests/test_flux3_prompt_upsampler.py::test_generated_only_penalties_follow_the_server[True]
tests/test_flux3_prompt_upsampler.py::test_generated_only_penalties_follow_the_server[False]
tests/test_flux3_prompt_upsampler.py::test_stop_during_server_start_cancels_the_start
core.inference.flux3_prompt_upsampler.UpsamplerUnavailableError: The image model no longer holds the GPU.
```

On their own the tests pass on main (93 passed, serially and with `-n
4`). They fail only after another test has run in the same process.
#14151 does not touch either file, so any PR whose worker draws this
order will hit it.

## Cause

`FluxPromptUpsampler.generate` starts the sidecar only while
`_image_model_owns_gpu()`, which reads `gpu_arbiter.current_owner()`
(image model or nobody). That arbiter is process-wide, and the upsampler
tests never pinned it.

I ran each `tests/test_[a-k]*` file that touches the arbiter in front of
`test_flux3_prompt_upsampler.py` in one process. Only
`test_gpu_selection.py` reproduces the failures, and it gives the same
three IDs. Tracing `gpu_arbiter._owner` around each test points at one
test:
`TestRouteErrors::test_inference_route_returns_400_for_invalid_gpu_ids`
(`None -> 'chat'`). It drives the real `/load` route, which claims the
GPU for CHAT through `acquire_for_request` before the stubbed backend
refuses `gpu_ids = [99]`. Nothing puts the arbiter back afterwards.

So the tests are what is wrong here: one leaks global state, the other
depends on it.

A failed chat load leaving CHAT claimed with nothing loaded is a
separate product question, which this PR does not change. I could not
find a failure path in `routes/inference.py` that calls
`release_chat_gpu_claim()`. It may be worth a look on its own.

## Change

Test only:
- **`test_gpu_selection.py`:** `TestRouteErrors.setUp` saves the
arbiter's module state (`_owner`, `_owner_epoch`, `_owner_account`,
`_prior_account`) and restores it with `addCleanup`. The route tests
therefore leave the arbiter as they found it.
- **`test_flux3_prompt_upsampler.py`:** the autouse `_clean` fixture
pins `gpu_arbiter._owner` to `None`, the fresh-start state those tests
assume. The tests about a different owner already set it themselves and
still do.

## Testing

`tests/test_gpu_selection.py tests/test_flux3_prompt_upsampler.py` in
one process, in that order:

| change | result |
|---|---|
| neither (main) | 3 failed, 194 passed: the three IDs above |
| only the upsampler pin | 197 passed |
| only the `TestRouteErrors` restore | 197 passed |
| both (this PR) | 197 passed |

`test_gpu_selection.py`, `test_flux3_prompt_upsampler.py` and
`test_gpu_arbiter.py` together with `-n 4` give 218 passed.
@danielhanchen danielhanchen self-assigned this Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@danielhanchen

Copy link
Copy Markdown
Member

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: e103b3c7b0

ℹ️ 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 pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 19, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 82e81e72ff

ℹ️ 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 8cf09fe into unslothai:main Oct 19, 2026
@Etherll
Etherll deleted the fix/inline-auth-db-locked-29f2f996 branch October 20, 2026 02:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants