Repository navigation
Studio: stop the per-chunk autosave writing back messages the server owns - #9865
Merged
Merged
Conversation
…owns During a streamed reply the history adapter's autosave fires per chunk. When the message is server-managed it built the write out of fields it had just read back from the backend: content from existingMessage.content, metadata from existingMetadata, createdAt from existingMessage.createdAt. Attachments are always empty there, since only a user message carries them. So the request could not change anything, and the server answered 409 "server-managed generation messages cannot be edited" every time. Measured on a real session: one 43.6 s generation issued 265 PUTs of which 256 were rejected, a median 166 ms apart, plus 353 whole-thread GETs a median 339 ms apart. The GETs come from the ensureStoredChatThread inside saveStoredChatMessage, so returning before the call drops both. parentId is the one field not echoed back, so a reparent could in principle differ here. It is dropped either way today, because the server rejects the whole request. Skipping is behaviour-preserving rather than a new trade. The guard is a source test rather than a behavioural one: the call site is an inline closure in the history adapter with no seam to stub. It pins ordering rather than spelling, so a rename keeps working and moving the save above the guard does not.
Member
Author
|
@codex review |
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Aug 27, 2026
|
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". |
danielhanchen
added a commit
to umran666/unsloth
that referenced
this pull request
Sep 1, 2026
…nslothai#9984) Regenerate reloads through startRun({ parentId }), which mints a new assistant message and leaves the user turn alone, so history.append is never called twice for one user turn on that path. Reusing an existing row's id there does not remove a duplicate, and it breaks the thread when one exists: - The repository keeps the id it generated, so the assistant that follows is appended with parentId set to an id no row was written under. chat_messages .parent_id has no foreign key, so that lands silently, and a dangling parent makes the whole thread unimportable on the next load rather than just that turn. - The lookup matches on content and attachments, so two user branches that legitimately say the same thing under one parent collapse into one. - It reads the whole thread on every first user save, which is the per-message cost unslothai#9865 removed a few lines below. Tests. test_chat_message_identity.py covers genuine repeat sends on flat and branched threads, the reported stop-then-regenerate sequence with a large attachment, import and single-message delete, legacy threads with a NULL or empty parent_id, and a randomised invariant over 60 seeds that no sequence of writes leaves a parent dangling or loses a message. Text repeats throughout, so any content-keyed write fails it. chat-user-turn-identity.test.ts guards the three frontend sites the same way the neighbouring adapter tests do.
danielhanchen
added a commit
that referenced
this pull request
Sep 2, 2026
* fix(studio): reuse user message id on regenerate append (#9984) * Keep the runtime's message id on append, and test the tree invariant (#9984) Regenerate reloads through startRun({ parentId }), which mints a new assistant message and leaves the user turn alone, so history.append is never called twice for one user turn on that path. Reusing an existing row's id there does not remove a duplicate, and it breaks the thread when one exists: - The repository keeps the id it generated, so the assistant that follows is appended with parentId set to an id no row was written under. chat_messages .parent_id has no foreign key, so that lands silently, and a dangling parent makes the whole thread unimportable on the next load rather than just that turn. - The lookup matches on content and attachments, so two user branches that legitimately say the same thing under one parent collapse into one. - It reads the whole thread on every first user save, which is the per-message cost #9865 removed a few lines below. Tests. test_chat_message_identity.py covers genuine repeat sends on flat and branched threads, the reported stop-then-regenerate sequence with a large attachment, import and single-message delete, legacy threads with a NULL or empty parent_id, and a randomised invariant over 60 seeds that no sequence of writes leaves a parent dangling or loses a message. Text repeats throughout, so any content-keyed write fails it. chat-user-turn-identity.test.ts guards the three frontend sites the same way the neighbouring adapter tests do. * Cut the comments in the new chat identity tests * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Make the identity tests fail for a renamed dedupe, and fix the parent chain - The repeated-send test parented u2 to an a1 it never inserted. parent_id has no foreign key so the write succeeded, leaving the test asserting on a thread with a dangling parent. Insert the assistant turn and assert all three rows. - The frontend guards banned two identifiers, so an inlined JSON.stringify comparison under any other name passed them. Neither pruneOutboundHistory nor the load block is exported, so they still read source, but they now assert structure: the abandoned-turn guard's continue runs straight into surviving.push, and msgs is assigned once per branch and never rewritten. Injecting a renamed dedupe fails 3 of the 5. - Renamed the regenerate tests to say what they cover. They exercise studio_db with the rows a regenerate writes, not MessageRuntime.reload itself. * Tighten the comments in the chat identity tests * Close three holes in the chat identity guards - The outbound slice started after the input was built, so a filter folded into const history = [...messages] sat above every assertion. Slice the whole function and pin that line. - The load check only rejected rebinding msgs and the literal msgs.filter, so narrowing snapshot.messages before the assignment, or splicing msgs after it, went through. Cover both names and the in-place removers. msgs.sort stays allowed: reordering keeps the set. - The regenerate helper said the runtime path was guarded in the frontend test. It is not. That test checks shape, not behaviour, and chat-adapter.ts cannot be imported by the node runner, so nothing here drives reload end to end. Say that instead. Each hole was confirmed by injecting the exact shape and watching the suite turn red. * Pin the outbound prune loop body instead of matching its shape An early `if (sameUserTurn(...)) continue` above the refusal check left the regex matching and all five tests green while dropping repeated user turns. That is the third spelling a pattern let through, so the loop body is now compared whole, whitespace-insensitively. There is no shape that passes an exact match, and a deliberate refactor has to update the string. Also reject `msgs.length = 0` on load, which the in-place list missed. Injected all five shapes raised so far and each fails: early continue, a filter folded into `const history`, `snapshot.messages = snapshot.messages.filter`, `msgs.splice`, and `msgs.length = 0`. Baseline stays green. * Seed the thread from the #9984 report as a fixture The reporter's row dump, id for id: two user rows under cOfdER0 with identical content and attachments, 26.12 hours apart, each with its own replies. That is the shape the bug actually leaves behind, so it is worth pinning even though nothing here fixes it yet. The third test is the one that matters for whoever does fix it. Four assistant rows hang off the duplicate pair, so any repair that merges the two user rows on content strands them, which is the failure the reverted guards produced. * Apply the repo ruff-format kwarg spacing to the new fixture * Final comment pass on the chat identity tests * Make the frontend guards survive a refactor for PR #10064 The pinned loop body failed on any edit at all, including a variable rename or a reformat, which is a tax on anyone touching pruneOutboundHistory later. Count the ways a turn can be dropped instead. Inside the loop that is a continue, a surviving.pop, or a conditional push, and the abandoned-turn guard already owns exactly one of the first two. A second of any is a dedupe under whatever name. The input line is still pinned, since a filter folded into const history never touches the loop. Checked both directions by injection. Still red for an early continue, a filter on const history, an extra pop, a conditional push, a snapshot.messages filter, msgs.splice and msgs.length. Now green for a variable rename, a reformat and an added statement, all three of which the pin rejected. * Close two more gaps in the frontend guards for PR #10064 - The push check only rejected an inline wrapper. A block form, if (...) { surviving.push(message); }, kept the counts at one each and passed. Compare brace depth against the loop body as well, so nesting is caught, and keep the line-start match, since an inline wrapper does not change depth. - The load slice stopped at const hasParentIds, leaving out both branches that build the repository. A filter on the map or on fromArray was invisible. Extend the slice through the reconstruction. Injected shapes, all red: early continue, filter on const history, extra pop, inline conditional push, block conditional push, filter in the reconstruction map, filter on fromArray, snapshot.messages filter, msgs.splice, msgs.length. Green for a rename, a reformat and an added statement. Merged main to clear the pre-commit.ci conflict: the branch was 21 commits behind, so the hook reformatted 1011 files repo-wide and could not push. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Say what the frontend guards actually prove for PR #10064 Four rounds of review found seven ways past these assertions, and each finding was correct. Source matching has no closed set of patterns, so a fifth pattern buys one round. The defect is not the assertions, which do catch the shape the reverted change had. It is that the names and the header claimed a guarantee they cannot give. State the scope in the header, name the known ways past it, and point at the backend suite, which runs the real studio_db and covers the behaviour where the damage lands. Renamed three tests that read as proofs of behaviour. Proving the negative needs pruneOutboundHistory and the load reconstruction extracted and called directly. That is a production change and belongs in its own PR, not in a tests-only one. * Final comment pass on the chat identity tests * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
During a streamed reply the chat history adapter autosaves per chunk. When the message is server-managed, that autosave builds a write out of fields it has just read back from the backend, so the request cannot change anything, and the server answers
409 server-managed generation messages cannot be editedevery time.What the traffic looks like
From a real session, one generation lasting 43.6 s:
PUT /api/chat/threads/{id}/messages/{id}GET /api/chat/threads/{id}(whole thread)Median cadence 166 ms for the PUTs and 339 ms for the GETs. All of it against the same backend the model is saturating.
Why the write can never do anything
At the call site, when
preserveServerManagedis true:contentwasexistingMessage.contentmetadatawasexistingMetadatacreatedAtwasexistingMessage.createdAtattachmentsis empty, because only a user message carries them and this branch is a server-managed generationEvery one of those came from the backend on the point read a few lines above. The write is the client handing the server its own record back, for a message the server refuses to let it edit.
The change
Return before the save when
preserveServerManagedis true.That drops the whole-thread GET as well as the PUT, because
saveStoredChatMessagecallsensureStoredChatThreadbefore it saves, and that is what issues the read.Three things follow from the early return and are cleaned up with it:
contentno longer needs thepreserveServerManaged ? existingMessage!.content : contentternary, themetadataternary collapses toincomingMetadata, and the comment about echoing the backend's stored metadata verbatim is removed because it now describes code that is gone.parentIdis the one field not echoed back, so a reparent could in principle differ here. It is dropped either way today: the server rejects the whole request, so that update has never landed on this path. Skipping is behaviour-preserving rather than a new trade.Test
tests/server-managed-autosave-write.test.ts, three assertions: the guard exists, it precedessaveStoredChatMessage, and it returns rather than only skipping fields.It is a source guard rather than a behavioural one because the call site is an inline closure inside the history adapter with no seam to stub. It pins ordering rather than spelling, so renaming either symbol keeps working, while moving the save above the guard does not.
Mutation checked: with the guard removed, 2 of the 3 fail.
Verification
tsc --noEmitcleaneslinton the changed file reports the same 10 problems asmaindoes on the same file, so nothing newtests/remend-complete-markdown.test.tsand they fail identically on unmodifiedmain, so they are inherited rather than caused here.What this does not claim
This does not claim to fix the reported flinching. It removes the mechanism that most plausibly causes it, and the reporter's video shows a one-frame layout excursion that returns to within 0.02% rather than a text rewind, which is consistent with a lagging snapshot landing for a frame. But nobody has reproduced the flinch end to end and shown it gone, and the video and the server log are different recordings, so no individual flinch has been matched to an individual read.
What is measured and not in doubt is the traffic: 256 rejected writes and 353 whole-thread reads during one answer, all of it avoidable.