Repository navigation
Studio: take common SQLite reads off the event loop thread - #9234
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| _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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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: Didn't find any major issues. Can't wait for the next one! 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 |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
Codex Review: Didn't find any major issues. Hooray! 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". |
|
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. |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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: Didn't find any major issues. Hooray! 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". |
|
This mitigates the Studio-wide outage in #9008 by moving common SQLite reads off the event loop, so a stalled read no longer blocks |
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_timeoutdoes not help with this mutex.Changes
Move common SQLite reads off the event loop:
async deftodef, allowing FastAPI to dispatch them to its threadpool:auth_status,list_api_keys,list_mcp_serversandlist_provider_configs.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:
loginclears its rate-limit admission check beforeverify_passwordreaches_record_login_failure, so the bucket lock guards each call but not the sequence.refreshconsumes a token and inserts its replacement, whilelogoutcan delete every token in between without rotating the credential generation.import_mcp_serversbuildsseen_urlsbefore inserting into a table whoseurlhas no uniqueness constraint.update_provider_configandmigrate_provider_api_keyread a row and then save a credential thatcredential_secretsdoes not foreign-key to it.cache_toolswrite 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_clientreads 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_idlecount the requests parked on the unload gate, so the loop re-asks them after thesettings 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_toolson thetoken-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:
/api/auth/status/api/livenessafterwardTwenty 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.