Repository navigation
studio: render a chat send without waiting on persistence - #8136
Conversation
Sending the first message in a new chat cleared the composer, then left the thread blank for a second or more before anything appeared. assistant-ui's LocalThreadRuntimeCore.append awaits the thread-list item's initialize promise before adding the message to its repository, and the composer has already emptied by then. The Studio adapter's initialize wrote the thread row first, so the whole stall sat between the composer clearing and the first paint. createStudioDbAdapter.initialize now returns the thread id straight away and registers the row write through trackStoredChatThreadRecord. The user message and the assistant placeholder render in microtasks. The model run still waits for persistence through the existing history-append gate, so a failed write cannot leave an orphan run. ensureStoredChatThread awaits any in-flight row write, which keeps the guarantee at one choke point instead of asking every initialize caller to remember it. Without that, the prompt queue's model correction in thread.tsx silently dropped its patch: updateStoredChatThread returned undefined for a row that had not landed yet, and the thread persisted with the live global model rather than the model captured for the queued run. Three round trips also left the send path: - ensureThreadRecord answers "does this thread exist" with getStoredChatThread instead of listing every thread, so it no longer scales with how many chats exist - the history append reads the thread and the message together, and looks the message up by id rather than fetching the whole thread history - listStoredChatThreads re-reads after the legacy import only when that import actually created threads, tracked by legacyChatImportGeneration Handlers in routes/chat_history.py are sync defs so Starlette runs studio.db's blocking sqlite in its threadpool. As async defs they ran it on the event loop, where a thread listing serialised behind model loads and status probes. test_route_handlers_are_sync guards the conversion, and the tests that drove those handlers through asyncio.run now call them directly. Thread keyed GeneratedImageOverlayProvider on the app's activeThreadId, which flips from "default" to the thread id the moment the first message persists. That remounted the whole message tree and replayed the user bubble's animate-in classes just as the response started. It now keys on assistant-ui's threadListItem.id, which is stable across that transition and still changes on a real thread switch. Verified with ruff, 237 backend tests, 900 frontend tests, tsc, and biome. GPU checks were not run: none of this touches a model path.
Deleting a thread now waits for a row write that initialize() started, so an in-flight upsert cannot land after the DELETE and resurrect an empty thread that nothing later cleans up. Overlapping initializations chain in trackStoredChatThreadRecord instead of replacing the tracked promise. Waiting on only the newest upsert let a slower one finish afterwards and overwrite a modelId a queued run had already corrected. backfillLegacyThreadFields bumps the listing generation when it restores a container binding. Only the row-creation branch bumped it, so listStoredChatThreads skipped its re-read and returned the pre-backfill record, and the OpenAI container cleanup in openai-code-exec-section could miss a thread still bound to a deleted container.
…on on commit awaitStoredChatThreadRecord read the tracked entry once, so a creator registered while it was already waiting was missed and a delete could still beat that upsert. It drains until the entry stops changing, reporting the last outcome so a thread nobody wrote is still the failure case. backfillLegacyThreadFields bumps the generation after the patch commits rather than before. A listing that captured the bumped value while the request was in flight read the old row, then skipped its re-read because the generation never moved again.
ThreadDocumentsBar treated a resolved initialize() as proof the thread was persisted. Since initialize() now returns before the row write, a failed thread POST no longer reached the catch: the bar reported success, indexed documents against a thread id that was never created, and left the user without the error toast. Awaiting the tracked creation restores the previous behaviour for this consumer while the message path keeps rendering immediately.
A transient failure in the row write left the chat permanently broken. initialize() had already resolved, so assistant-ui cached the remote id and never asked the adapter for the row again, and ensureStoredChatThread can only read or import an existing row. Every later message write then returned 404 until the user abandoned the chat. trackStoredChatThreadRecord takes a creator rather than a promise and keeps it when the write rejects. ensureStoredChatThread re-runs it once the reads confirm the row is genuinely absent, which restores the retry that rejecting from initialize() used to provide.
Waiting on the tracked write was not enough. After a failed row write the tracked promise is already gone and assistant-ui returns its cached initialize() result, so a retried attachment resolved immediately and indexed documents under a thread id with no chat row. The bar now goes through ensureStoredChatThread, which reads the row and re-runs a failed creator before reporting success, so the failure reaches the existing catch and its toast. Temporary chats are exempt: they never persist a row, so isThreadIncognito skips the check.
Only per-id deletion waited for a tracked row write, so clear-all could race one. The DELETE finished first and the POST recreated the thread, and because the inventory clearStoredChats builds comes from a listing taken before that POST landed, the thread was never tombstoned either and survived the clear outright. The drain runs before that listing so a freshly written row is both visible and removed, and it discards failed creators so a later retry cannot recreate what the user just cleared.
|
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". |
ensureStoredChatThread awaits awaitStoredChatThreadRecord before its reads, and that rethrows a rejected row write. The retryFailedThreadRecord branch further down never runs for a caller that was already waiting when the write failed, so a recoverable write surfaced to it as a rejection instead. updateStoredChatThread is the visible one: a rename or an archive over a row write that had just failed rejected rather than retrying the creator and applying. The next call did recover, because the failed creator stays registered, but only after the first one had already thrown. Waiting on the tracked write is still correct, adopting its failure is not: the reads below already decide whether the row exists, and retryFailedThreadRecord re-runs the creator when it does not.
Deleting a thread and clearing history both wait for a tracked row write so an in-flight upsert cannot land afterwards and resurrect what was just removed. Neither wait had a bound, and authFetch sets no timeout or AbortSignal, so a request the backend never answers blocked both for as long as the browser took to give up. Before the drain existed there was nothing to wait on, so this is reachable only on this branch: a wedged POST /api/chat/threads left the user unable to delete that chat or to clear history at all. Both paths now give up after 5s and proceed. That is safe: deleteStoredChatThreads tombstones the ids, so a row landing late is masked from every read and removed by the next delete.
|
Went through this one carefully and pushed two fixes to the branch. Both are on the 1.
|
retryFailedThreadRecord consumed the stored creator before starting its retry, so a second caller arriving in that window found no creator, reported the row absent and returned without waiting. updateStoredChatThread then dropped its patch and saveStoredChatMessage raced its PUT against the retrying POST. It now falls through to the pending write when the creator is already claimed. That retry also swallowed its own failure. Returning undefined reads as no row to update, which is how the prompt queue permanently clears shouldCorrectPersistedModel and leaves the thread carrying the live checkpoint instead of the one captured for the queued run. The failure propagates now. A write that outruns the bounded wait still commits, and a local tombstone only hides the row here while the backend keeps serving it. deleteLateThreadRecords issues a second delete once such a write settles, for both the per-id path and clear-all.
…l stable A write in flight when history was cleared still ran its rejection handler afterwards, which recorded its creator again after the map had been emptied. The uncommitted thread was in neither inventory so it got no tombstone either, and the next ensureStoredChatThread consumed that creator and recreated a thread the user had cleared. Creators now carry the clear epoch they were registered under and only record themselves while it still matches. deleteLateThreadRecords also snapshotted the tracked promise once, so a creator chained on after that snapshot was missed and the follow-up DELETE could run before the newer write committed. It waits through awaitStoredChatThreadRecord instead, which drains until the entry stops changing.
…t point imports Overlapping initializations with mixed outcomes each recorded a retry creator, including the ones whose sibling had already persisted the row. Nothing cleared them on success, so if that row was later removed without this tab taking a tombstone, the next autosave consumed a stale creator and recreated a deleted chat. A resolved tracked write now drops them. importLegacyThread also creates a backend row without moving legacyChatImportGeneration, so a listing that read before a point-lookup import could skip its re-read and, once the import hint was set, drop the legacy copy too, returning a list missing the recovered thread.
…ion across a clear The point-import generation bump lands only when the POST promise resolves, not when its commit becomes visible to other requests, so a listing holding a stale first read could compare an unmoved generation and skip its re-read. With the import hint set it then drops the legacy copy too, returning a list missing the recovered thread. Listings now await imports already in flight. ThreadDocumentsBar also kept waiting through a clear that had given up on its thread POST. The follow-up delete then raced the upload, and upload_thread_document does not check that the chat row exists, so documents stayed indexed after a reported successful clear. The bar captures the clear boundary and abandons materialization when it moves.
…eanup The late-cleanup list was snapshotted before the drain, so a chat initialized while the drain was running, whose write also outlived the deadline, was in neither that list nor the backend inventory the clear builds. It took no tombstone and no follow-up delete, and reappeared after a successful clear. The list is now the union of the pre-drain ids and whatever is still pending when the drain gives up.
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ba0f6e0600
ℹ️ 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".
| } catch (error) { | ||
| // A backend tombstone is an answer, not an indeterminate transport failure: indexing | ||
| // against it would leave documents under a thread that can never come back. | ||
| if (error instanceof ChatThreadDeletedError) { | ||
| throw error; | ||
| } | ||
| return; |
There was a problem hiding this comment.
Reject definitive thread-creation failures before upload
When the background thread creation fails with a definitive non-410 HTTP response—such as 404 Project not found after its project is concurrently deleted—ensureStoredChatThread rejects with a generic error and this catch treats it as an indeterminate transport failure. The upload then proceeds even though upload_thread_document does not validate the chat thread, leaving a RAG document indexed under a thread ID that has no chat row. Only genuinely ambiguous transport failures should be allowed through; known HTTP failures should block the upload.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Leaving this one. The 410 case was worth separating because the retry produces a typed error that says the thread is definitively gone. A generic non-410 failure does not carry that, so telling definitive from indeterminate here means classifying HTTP status through saveChatThread into a second error type, and the window it buys is a project deleted between a first send and the document upload attached to it, with orphaned rag_sources rows as the cost rather than lost user content. That is not worth another error class in this path, and the current shape is the one the bar deliberately settled on in ba5b088: a failure that is not proof the row is missing lets the upload through. Happy to revisit if there is a path where the orphaned rows matter beyond the row count, or if a definitive-failure signal shows up in the API layer for another reason.
… clear fence bound for PR unslothai#8136
|
Ran the review loop over four rounds today and pushed six commits. Everything Codex raised is RoundsRound one had 19 un-reacted items, all but two of them describing the design d24aa9b replaced:
Four of these are worth calling out because they are not independent findings. The propagation regression. 7b74fda made a failed row write rethrow, with the comment Two follow-ups came from that restore. The document bar's catch had been swallowing the The clear retry then produced its own. Retrying the same VerificationTwo Playwright browsers' worth of assertion is not enough for promise plumbing, so the ordering Alongside that: 23 checks on the schema and old installs, driving one studio.db from a Staging CI on an owned repo, so the org queue keeps its slots: Backend, Frontend, Startup profile, What stops this from convergingThe branch no longer merges. Once that merge is in, the loop is otherwise clean: no un-reacted items, fixcheck OK, and every 👍 Still open, unchangedTombstones are never pruned server-side. Partial-clear reporting still calls legacy-only threads failed when the backend clear fails but |
|
Codex Review: Didn't find any major issues. You're on a roll. 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. 🚀 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". |
What
Sending the first message in a new chat cleared the composer, then left the thread blank for a
second or more before anything appeared. This makes the message render immediately and fixes the
defects found along that path.
Why the send stalled
LocalThreadRuntimeCore.appendin assistant-ui awaits the thread-list item's initialize promisebefore adding the message to its repository, and
BaseComposerRuntimeCore.sendhas alreadyemptied the composer by then.
createStudioDbAdapter.initializewrote the thread row beforeresolving, so every round trip it made sat between the composer clearing and the first paint.
Fixed
The send blocked the first paint.
initializenow returns the thread id straight away andregisters the row write through
trackStoredChatThreadRecord. The user message and the assistantplaceholder render in microtasks. The model run still waits for persistence through the existing
history-append gate, so a failed write cannot leave an orphan run.
The user message flashed when the response started.
ThreadkeyedGeneratedImageOverlayProvideron the app'sactiveThreadId, which flips from"default"to thethread id the moment the first message persists. That remounted the whole message tree and
replayed the user bubble's
animate-inclasses. It keys on assistant-ui'sthreadListItem.idnow, stable across that transition and still changing on a real thread switch.
The prompt queue's model correction was silently dropped.
thread.tsxcorrects a freshthread's
modelIdto the model captured for the queued run. With the row write no longercomplete at that point,
updateStoredChatThreadreturnedundefinedand the patch never applied,so the thread persisted with the live global model instead.
ensureStoredChatThreadnow awaitsany in-flight row write, which keeps the guarantee at one choke point rather than asking every
initializecaller to remember it.ensureThreadRecordlisted every thread to answer an existence question, twice per callthrough
listStoredChatThreads. It uses agetStoredChatThreadpoint lookup, so first-send costno longer scales with how many chats exist.
The history append made five round trips to write one message. It called
ensureStoredChatThreadon a recordgetStoredChatThreadhad already resolved, and fetched theentire thread history to find one message's
createdAt. It now reads the thread and the messagetogether and looks the message up by id.
listStoredChatThreadslisted threads twice on every call, the second read covering threadsthe legacy Dexie import might have added.
legacyChatImportGenerationtracks whether that importactually created any, so the re-read happens only when it did.
routes/chat_history.pyran blocking sqlite on the event loop. The handlers wereasync defcalling synchronous studio.db functions, so a thread listing serialised behind model loads and
status probes. They are sync defs now and run in Starlette's threadpool, matching
save_thread_messageandreplace_thread_messagesin the same file.Verification
Manually tested end to end in the desktop UI: new chat, first send, streaming response, prompt
queue, thread switching, and reload.
ruff checkandscripts/run_ruff_format.pyclean. 237 backend tests covering chat historyroutes, attachments, research runs, parallel slots, and logging middleware. 900 frontend tests.
tsc -bclean.biome checkreports the same diagnostics as the base commit on all three changedfrontend files.
test_route_handlers_are_syncguards the threadpool conversion, and the tests that drove thosehandlers through
asyncio.runcall them directly now.GPU checks were not run: nothing here touches a model path.