Skip to content

Studio: stop the per-chunk autosave writing back messages the server owns - #9865

Merged
danielhanchen merged 2 commits into
mainfrom
fix/server-managed-autosave
Aug 27, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
fix/server-managed-autosave

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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 edited every time.

What the traffic looks like

From a real session, one generation lasting 43.6 s:

count
PUT /api/chat/threads/{id}/messages/{id} 265, of which 256 rejected 409
GET /api/chat/threads/{id} (whole thread) 353

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 preserveServerManaged is true:

  • content was existingMessage.content
  • metadata was existingMetadata
  • createdAt was existingMessage.createdAt
  • attachments is empty, because only a user message carries them and this branch is a server-managed generation

Every 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 preserveServerManaged is true.

That drops the whole-thread GET as well as the PUT, because saveStoredChatMessage calls ensureStoredChatThread before it saves, and that is what issues the read.

Three things follow from the early return and are cleaned up with it: content no longer needs the preserveServerManaged ? existingMessage!.content : content ternary, the metadata ternary collapses to incomingMetadata, and the comment about echoing the backend's stored metadata verbatim is removed because it now describes code that is gone.

parentId is 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 precedes saveStoredChatMessage, 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 --noEmit clean
  • eslint on the changed file reports the same 10 problems as main does on the same file, so nothing new
  • Full frontend suite: 5798 pass, 3 fail. The 3 are tests/remend-complete-markdown.test.ts and they fail identically on unmodified main, 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.

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a5ec58d1ce

ℹ️ 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
danielhanchen merged commit 1af6d66 into main Aug 27, 2026
4 of 39 checks passed
@danielhanchen
danielhanchen deleted the fix/server-managed-autosave branch August 27, 2026 13:57
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>
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