Skip to content

Studio: reuse one database connection per thread for durable chat generation runs - #11525

Merged
danielhanchen merged 10 commits into
mainfrom
perf/durable-run-connection-reuse
Sep 22, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
perf/durable-run-connection-reuse

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Durable chat generations were spending nearly all of their database time opening databases rather than using them.

storage/chat_generation_runs_db.py opens a fresh sqlite3 connection for every call and closes it again. On this path the work is not what costs: the whole BEGIN IMMEDIATE / INSERT / progress UPDATE / COMMIT of an event flush measures 0.018 ms on an open connection, while get_connection() plus close() measures 0.49 ms. Every one of append_events, get_run, list_events and touch_progress pays that independently.

That adds up because of how often the streaming path calls them. The producer flushes up to ten times a second (_EVENT_BATCH_SECONDS = 0.1), and the SSE delivery loop in routes/chat_generation_runs.py pays wait_for_events plus a get_run snapshot on every turn, per attached tab. One generation with one tab open was opening and tearing down roughly 30 to 50 connections per second.

This keeps one connection per thread per account and hands it back to a cache instead of closing it.

Measured

Same machine, back to back, two runs each, medians. Absolute numbers move with machine load, the ratios held.

call before after
list_events, cursor at tail 0.405 ms 0.004 ms
get_run 0.411 ms 0.010 ms
one SSE delivery iteration 1.31 ms 0.43 ms
append_events, single event 0.557 ms 0.04 ms
append_events, 16 event batch 0.682 ms 0.20 ms

It also removes a cliff that only managed accounts hit. Closing the last connection to a WAL database checkpoints it, which is what #9934 fixed for the owner by holding a keeper open in main.py. A pooled connection keeps the database open on its own, so this path no longer depends on the keeper being there: with the keeper absent, append_events was 1.87 ms and is now 0.20 ms.

How it stays correct

  • Keyed on the acting account, not the resolved path. test_a_durable_run_poll_resolves_the_account_root_once and test_warm_owner_connections_do_not_resolve_database_again pin that a warm connect resolves the account root zero times, and studio_db_path() is exactly that resolution. current_account_id() is a context variable read and costs nothing.
  • Paired with the identity of _schema_ready, which is how the suite already isolates storage modules per test: conftest's _isolate_studio_home rebinds that attribute for every test. An account id alone cannot see a home that moved underneath it; the object identity can.
  • A nested _connect() on one thread gets its own connection. Sharing one would put two callers in a single transaction, where BEGIN IMMEDIATE raises and one caller's rollback would discard the other's work.
  • A handle left mid transaction is rolled back before reuse, so it cannot hand its caller's work to the next borrower.
  • Closing the WAL keeper drops the pool. Closing the keeper is meant to leave the database checkpointed and its -wal gone (a lot of writes to studio.db #9934), and any other open connection silently prevents that. studio_db.on_wal_keeper_closed is a small additive hook for this; existing callers are unaffected.

_Borrowed exists so that this is a local change rather than a rewrite of fourteen call sites: every caller already pairs _connect() with close() in a finally, and honouring that contract while keeping the handle open is what makes reuse contained to this module.

Known limitation

These connections keep sqlite's default check_same_thread, so only the thread that opened one may close it. A connection parked on an idle worker thread is marked stale and closed by that thread on its next borrow rather than immediately. Every caller that needs the file released at once (shutdown, account retirement, the tests) does so from a thread that has just been using this module, which is the thread whose connection is closed synchronously.

Tests

studio/backend/tests/test_chat_generation_runs_pool.py, 10 tests: reuse on one thread, a returned handle still being usable, nested borrows getting separate handles, rollback before reuse, two accounts never sharing a handle, an account switch not writing to the previous database, per thread handles, both invalidation hooks, and append_events still persisting through a reused connection.

Disabling the reuse turns 5 of the 10 red. The other 5 assert invariants that must hold either way.

Wider run, 2,989 selected tests across chat generation, accounts, storage, tool approvals and the lease sweeper: 2,797 passed with 192 failures, against 2,787 passed with the same 192 failures on main without this change. Identical failure count, plus the 10 new tests. The 192 are environmental on this host, mostly sqlite-vec not being importable. Ruff clean, test_formatter_fixed_point green.

Two things this went through before landing here, both caught by running the same suites on main first: an earlier version keyed the cache on the resolved path, which quietly undid the zero-resolution guarantee those two tests exist to protect, and an earlier version let a pooled connection outlive the WAL keeper, which weakened the #9934 guarantee. Both are fixed rather than worked around in the tests.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 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-09-22T15:16:57.700757Z ef21658 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

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

This comment was marked as resolved.

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: fdcf825648

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

ℹ️ 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 +119 to +121
for entry in entries:
if entry["busy"]:
continue

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 Wait for busy handles before renaming account roots

The new registry still explicitly skips an entry that is busy when account retirement invalidates the pool, but routes/accounts.py proceeds directly from close_wal_keeper_for to renaming the account roots. A cancelled producer can still be committing its terminal event, or an SSE worker can be reading, so on Windows that live SQLite handle can make the rename fail and leave deletion returning 409; the skipped borrower must be awaited or otherwise quiesced before retirement proceeds.

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.

Real gap, but it predates this branch and this branch does not widen it, so I am leaving it out rather than folding a retirement redesign into a connection reuse change. On main every call opens a connection, works, and closes it, so a rename racing an in-flight call meets an open handle in exactly the same way; the busy window is the duration of one query either way and the pool does not lengthen it. What the pool did add was idle handles, which main never had, and those are the ones now closed synchronously in _discard_all_pooled. Quiescing in-flight workers before routes/accounts.py renames the roots is worth doing, but it is a change to the retirement sequence rather than to this cache, and it needs its own handling for a worker that never becomes idle. Happy to open it separately.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1735a20033

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

@danielhanchen
danielhanchen merged commit d4a402b into main Sep 22, 2026
3 of 48 checks passed
@danielhanchen
danielhanchen deleted the perf/durable-run-connection-reuse branch September 22, 2026 15:15
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: ef2165842f

ℹ️ 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
…thai#11610)

* Inject the schema fault where get_progress gets its connection

Since unslothai#11525 a warm thread reuses its pooled connection without calling
get_connection. _seed() pools one, so the fault the no-such-column test
wrapped around get_connection was never reached when the test ran on its
own, and it passed only when an earlier test left the pool unusable.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…eration runs (unslothai#11525)

* Studio: reuse one database connection per thread for durable chat generation runs

* Trim the connection reuse comments to the facts that change behaviour

* Release pooled connections on every thread before an account is retired

* Take the pool lock across the borrow so invalidation cannot close a handle in use

* Never pool a connection whose lease migration has not completed

* Do not pool a handle prepared across a concurrent pool invalidation

* Hold pooled connections weakly so a short-lived thread does not leak its handle

* Prune dead pool references on insert and unregister

* Discard a pooled handle whose rollback failed instead of parking it

* Trim the connection pool comments after convergence
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…thai#11610)

* Inject the schema fault where get_progress gets its connection

Since unslothai#11525 a warm thread reuses its pooled connection without calling
get_connection. _seed() pools one, so the fault the no-such-column test
wrapped around get_connection was never reached when the test ran on its
own, and it passed only when an earlier test left the pool unusable.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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