Skip to content

Studio: take common SQLite reads off the event loop thread - #9234

Merged
oobabooga merged 18 commits into
unslothai:mainfrom
oobabooga:worktree-studio-sqlite-stall-serving
Aug 19, 2026
Merged

oobabooga merged 18 commits into
unslothai:mainfrom
oobabooga:worktree-studio-sqlite-stall-serving

Conversation

@oobabooga

@oobabooga oobabooga commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #9008.

Problem

SQLite uses a process-global VFS mutex across Studio's database connections. If a file operation stalls while an SQLite call is running on the event loop, Studio remains alive but stops accepting requests, including /api/liveness. busy_timeout does not help with this mutex.

Changes

Move common SQLite reads off the event loop:

  • Run auth credential lookups in the threadpool. This is the one every authenticated request pays.
  • Convert the four read-only auth, MCP and provider handlers from async def to def, allowing FastAPI to dispatch them to its threadpool: auth_status, list_api_keys, list_mcp_servers and list_provider_configs.
  • Run idle-unload settings reads in worker threads.
  • Run the MCP server-list read that every chat pays in a worker thread, along with the cache-only token-count path.
  • Run the saved-provider row lookup in the chat proxy in a worker thread.

The reads remain at the same points in each flow, preserving the existing race checks and settings re-reads.

Scope

This is a mitigation, not a complete fix for #9008. Requests that require stalled storage will still wait, and every read that a later decision depends on stays on the event loop, along with ChatGPT OAuth, startup and remote-code consent. Those fire on logins, settings edits, OAuth flows and startup rather than on polling or ordinary chat.

A read stays on the loop when a later step depends on it and a momentarily stale answer would persist or authorize something. Being await-free is what makes those sequences atomic:

  • login clears its rate-limit admission check before verify_password reaches _record_login_failure, so the bucket lock guards each call but not the sequence.
  • refresh consumes a token and inserts its replacement, while logout can delete every token in between without rotating the credential generation.
  • import_mcp_servers builds seen_urls before inserting into a table whose url has no uniqueness constraint.
  • update_provider_config and migrate_provider_api_key read a row and then save a credential that credential_secrets does not foreign-key to it.
  • The post-probe MCP re-read is the guard for the cache_tools write right after it, so awaiting it would let an edit invalidate the cache in between and be overwritten by the stale probe result.
  • _resolve_openai_cloud_client reads the provider row for the base URL and then reads the saved key, and the container routes need both to see one provider.

Where a read does move to a worker and a later step still depends on an earlier answer, that
answer is taken again immediately before the effect. Both idle-unload timers do this: _is_idle /
tracker.is_idle count the requests parked on the unload gate, so the loop re-asks them after the
settings reads and right before the teardown rather than trusting the answer it took before.

A read whose staleness cannot outlive the response does move to a worker. cached_mcp_tools on the
token-count path is the one case: it reads the server list and the tool cache, so it can straddle an
edit's write and its cache invalidation, but the only consumer is the background context-usage
recount, which redraws a bar the next recount corrects.

For the sequences above, a worker makes each of these reachable: a burst of guesses passes admission together, a logout leaves behind the refresh token that landed after it, two imports duplicate a server row, an update racing a delete saves a credential for a provider that is gone, a renamed MCP server keeps serving the old endpoint's tools until a restart, and a container call pairs the old base URL with the new key.

Verification

With SQLite's VFS mutex held in a running backend:

probe before after
/api/auth/status timeout timeout
/api/liveness afterward timeout 200 in 1.5 ms
listen queue growing empty

Twenty deterministic regression tests assert which thread each affected read runs on, in both directions, and two more drive a request onto the unload gate from inside the settings read to prove neither timer frees a model out from under it. The MCP, auth, provider, credential, keepwarm, health, inference and route suites pass; ruff and the import-hoist gate are clean.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 18, 2026
@oobabooga

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: 0a47321f96

ℹ️ 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".

config = providers_db.get_provider(payload.provider_id)
# Off the event loop thread: every chat routed to a saved provider reads it, and a
# stalled read stops the loop returning to accept(). See auth/authentication.py.
config = await asyncio.to_thread(providers_db.get_provider, payload.provider_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Resolve the saved provider target and credential atomically

When a saved-provider chat overlaps PUT /api/providers/{provider_id} that changes both base_url and encrypted_api_key, this await can return the old provider row, allow the await-free update handler to install the new URL and key, and then resume before resolve_provider_api_key_or_400 at line 12640 reads the replacement key. The request consequently sends the new credential to the old endpoint, which can disclose it if that endpoint is no longer trusted; read the routing metadata and credential as one coordinated snapshot or serialize this resolution with provider mutations.

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.

This window predates the PR. The routing metadata is read here and the credential is re-read from storage at resolve_provider_api_key_or_400, and between those two points main already has nine awaits inside _proxy_to_external_provider (12412, 12428, 12459, 12513, 12516, 12550, 12551, 12620, 12622; the same nine at 12414..12624 on head). An update that changes base_url and encrypted_api_key could always land in one of them, so the added await sits before the window rather than opening or widening it.

update_provider_config is also async def again as of a257a2f, so it is no longer the await-free threadpool handler described here. That does not change the verdict either way, since the nine intervening awaits are what allow the interleave.

Leaving it: reading the routing metadata and the credential as one snapshot changes the proxy's own contract and is not behavior this PR moves, so it belongs in its own change against main rather than here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 66311d2: saved provider routing is revalidated under the per-provider mutation guard before the credential is read, so an overlapping edit returns a retryable conflict instead of pairing an old target with a new key.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 18, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 18, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@oobabooga

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: 5d1d619ce1

ℹ️ 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 thread studio/backend/routes/inference.py Outdated
_mcp_tools, _mcp_complete = cached_mcp_tools()

# cached_mcp_tools reads SQLite, so keep it off the event loop.
_mcp_tools, _mcp_complete = await asyncio.to_thread(cached_mcp_tools)

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 Serialize cached MCP reads with cache invalidation

When token counting overlaps an MCP edit that changes the URL, headers, or OAuth settings, this worker can observe the newly committed server row after update_server() but read the old _tool_cache entry before invalidate_tool_cache() runs. cached_mcp_tools() then reports the stale schemas as complete, even though the completion path will invalidate and re-probe the new endpoint, so /chat/count_tokens can return an incorrect count instead of declining with 503. Keep the server snapshot and cache read coordinated with the mutation's database-write/cache-invalidation sequence.

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.

The mechanism holds: update_server and invalidate_tool_cache are adjacent statements on the loop with no await between them, so only a worker can observe the gap, and the SQLite write releases the GIL wide enough for one to land there. That part is right, and it is new here.

Rejecting on consequence. cached_mcp_tools feeds nothing that persists or authorizes: /chat/count_tokens is the background context-usage recount behind refresh-context-usage.ts, it renders the context bar and the response-details figure, and the next recount overwrites it. The handler already 503s whenever a generation is running, and its own comment puts the price of over-refusing at a redraw. So the worst case here is one context bar computed from the previous tool schemas for a fraction of a second, with nothing written, cached or routed on it.

That is the line the other six items fell on the far side of: each of those let an inconsistent read reach a write or a routing decision whose effect stayed (a duplicate row, an orphaned secret, a session outliving logout, a tool cache poisoned until restart, a key sent to the old base URL). Moving this read back would cost the count path a SQLite read on the loop on every recount to buy a transient display value. The scope section is reworded to say that is what governs, rather than read count alone.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Fixed in 66311d2: token counting now holds an async snapshot guard across the worker row/cache read, while MCP update and delete hold the same guard across commit and invalidation.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 5d1d619ce1

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 9e72ca7196

ℹ️ 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".

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026

@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: 8f7e3c1dce

ℹ️ 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".

# Re-read settings: the save can outlive a settings change.
ttl = get_auto_unload_idle_seconds()
if ttl <= 0 or not _is_idle(ttl) or _user_pinned(backend):
ttl = await asyncio.to_thread(get_auto_unload_idle_seconds)

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 Prevent stale worker reads from repopulating the settings cache

When a settings update overlaps this off-loop reread, _cached_setting() can fetch the old SQLite value, the update can then commit and call _invalidate(), and the worker can finally write that old value back into _cache for up to two seconds. Consequently, disabling idle unload, enabling the API-only pin, or applying the residency veto during a tick may still let this final guard unload the model; the media worker reads have the same race. Coordinate cache fill with invalidation (for example, with a generation check) before relying on these rereads as the pre-teardown decision.

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.

The race in _cached_setting is real, but it is not this branch's and this branch does not widen it.

The invalidator already ran off the loop before this PR: update_openai_auto_switch in routes/settings.py is a sync def, so FastAPI has always dispatched it to the threadpool, and routes/settings.py is not in this diff at all. _cached_setting is also byte-identical at the merge base, including the part that matters: it drops _cache_lock for the get_app_setting call and re-takes it to store, so an _invalidate landing in between was always losable. Two different threads, with the GIL released across the SQLite read, so the loop-thread reader on main could lose the same way a worker can now.

On the guard itself: the ttl my re-check uses is the same value the pre-existing guard above it already used, so it neither introduces nor deepens the staleness. What it adds is an activity re-check, and _is_idle reads in-memory counters under a threading.Lock, never _cached_setting.

Not deferring it silently: coordinating the fill with the invalidation, a generation counter on the cache, is a genuine fix and it belongs in its own change against main, where it also covers every other caller of these settings rather than the two timers.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 5183552aae

ℹ️ 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

Confirmed this hits the path in studio/backend/auth/authentication.py where the credential lookup still runs on the loop thread, which is what turns an SQLite stall into a total outage including liveness. Backend CI is red on the head commit, could you take a look and I will get this reviewed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 28aa9491e8

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 162dd500d6

ℹ️ 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".

@oobabooga

Copy link
Copy Markdown
Member Author

This mitigates the Studio-wide outage in #9008 by moving common SQLite reads off the event loop, so a stalled read no longer blocks /api/liveness or unrelated requests. State-changing read/write sequences remain serialized, with revalidation around provider routing, MCP cache snapshots, and idle unloads. Focused regression coverage passes. The failing Core and CPU jobs reproduce on the base commit, while the remaining failures occur in unrelated end-to-end checks.

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.

3 participants