Skip to content

Studio: test that a chat message keeps its identity (#9984) - #10064

Merged
danielhanchen merged 20 commits into
unslothai:mainfrom
umran666:fix-9984-dedup-regenerate-user-messages
Sep 2, 2026
Merged

danielhanchen merged 20 commits into
unslothai:mainfrom
umran666:fix-9984-dedup-regenerate-user-messages

Conversation

@umran666

@umran666 umran666 commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Refs #9984. Not a fix for it, so no closing keyword: see below.

This PR started out deduplicating user turns on regenerate. That turned out to be aimed at a mechanism Studio does not have, and the guards it added lost real messages, so all of them were removed and what remains is the test suite.

Why the original approach came out

Studio builds its runtime with useLocalRuntime. In @assistant-ui/core 0.1.17, MessageRuntime.reload() calls startRun({ parentId }), and startRun creates an assistant message. history.append has exactly two call sites in the core: one for the user turn on a composer send, one for the assistant in performRoundtrip. Regenerate never re-appends the user turn, so the guards sat where a duplicate would be absorbed rather than where one is created.

The guards were also keyed on content, which cannot tell a copy the app made from a message the user genuinely sent twice. Reproduced against the head at the time:

  • upsert_chat_message collapsed a second identical send. Flat threads store parent_id NULL throughout, so every root user turn shared one bucket.
  • It also rewrote the row id in place, leaving the next assistant parented to a row nothing wrote. chat_messages.parent_id has no foreign key, so that lands silently, and the file's own comment notes a dangling parent makes the whole thread unimportable.
  • sync_chat_messages dropped payload rows and stranded their children. That path is also thread import and single message delete, not just regenerate.
  • pruneOutboundHistory compared text only, so two turns with different documents collapsed and one turn's attachments never reached the model.

What is here now

Tests only, no production change.

  • studio/backend/tests/test_chat_message_identity.py: genuine repeat sends on flat and branched threads, edit-resend siblings, the rows a regenerate writes, 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. Every operation reuses the same body text, so a content keyed write fails it.
  • The thread from the [Bug] Unsloth Studio duplicates the preceding user message (and its attachments) every time a response is regenerated, inflating context and token count #9984 report is seeded id for id as a fixture. Four assistant rows hang off the duplicate pair, which is why any repair has to key on identity rather than content.
  • studio/frontend/tests/chat-user-turn-identity.test.ts: guards the append, load and outbound prune sites. Neither function is exported and chat-adapter.ts will not import under node --test, so these read source, counting the ways a turn can be dropped rather than pinning the text. Verified by injection in both directions.
  • Two fixes to the tests added earlier in this PR, including one that parented u2 to an a1 it never inserted and so asserted on a thread with a dangling parent.

On #9984 itself

Leaving it open. The reporter's own row dump puts the two duplicate rows 26.12 hours apart in different sessions, with the second parented back to the fork point rather than the end of the branch, which is the shape edit and resend produces normally. Whether there is a defect at all turns on one unanswered question: are the two rows byte identical. If they are, edit-resend is ruled out and there is something to find. If they differ at all, the second row is expected behaviour.

Thanks to @umran666 for the original patch and to @Iory1998 for the database rows, which are what settled the mechanism.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the duplicate user rows under one parent_id in studio_db.py upsert_chat_message, so this is worth fixing, but the dedupe keys on message content rather than identity, and in flat threads where parent_id is NULL two genuinely separate turns with the same text would collapse into one, while pruneOutboundHistory compares text only and ignores differing attachments. Could you narrow this to reusing the existing user message id at the regenerate append site instead of the four content-hash passes, and confirm repeated identical sends still persist separately?

@Iory1998

Iory1998 commented Sep 1, 2026

Copy link
Copy Markdown

Following up with what I think pins the trigger, and it may explain the "confirmed but couldn't reproduce" split in the PRs.

The sequence that produces the duplicate:

Send a user message with a large document attachment.
Let generation start, then Stop mid-response.
Hit Regenerate (repeat 2–3×).
The chat_messages row for that single logical user turn multiplies — identical content, identical attachments, same parent_id (the SaKf868 / oHXbD51 pair in the example above).

I should have been more precise in my description. Apologies. But the bug is real, and there was instances where the same user message was duplicated with attachments 3 times in a row. I just deleted that conversations as I thought the mix-up was from my side.

@umran666
umran666 force-pushed the fix-9984-dedup-regenerate-user-messages branch from f3e4f93 to d4b73a2 Compare September 1, 2026 03:59
@umran666

umran666 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review @danielhanchen! Completely agree, broad content hashing across the serializer and database risked collapsing legitimate identical sends in flat or multi-turn chats.

I've updated the PR with a surgical fix:

  1. Reverted all content-hash passes from pruneOutboundHistory, history.load, and studio_db.py (both upsert and batch sync remain pure identity-based).
  2. Narrowed deduplication directly to history.append in runtime-provider.tsx: reuses the existing user message ID only when re-appending under the exact same parentId during a regenerate/retry cycle.
  3. Added regression tests in test_chat_history_storage.py verifying that repeated identical user sends across turns (and in flat threads where parentId is None) persist separately as distinct messages.

umran666 and others added 2 commits September 1, 2026 09:30
…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

Copy link
Copy Markdown
Member

Thanks for narrowing this down, and for dropping the four content-hash passes. The remaining change still has to come out, and I have pushed that plus a test suite to your branch (685d3f9).

Why the append-site id reuse cannot stay

Studio builds its runtime with useLocalRuntime (runtime-provider.tsx:2283), and in assistant-ui 0.12.28 MessageRuntime.reload() calls startRun({ parentId }). That mints a new assistant message and leaves the user turn alone. ThreadHistoryAdapter.append is called for a user turn exactly once, from LocalThreadRuntimeCore.append. So regenerate never re-appends the user message, and the lookup added at the append site is not sitting where a duplicate is created.

Where it does bite:

  1. It breaks the thread when a duplicate does exist. The repository keeps the id it generated. The assistant that follows is appended with parentId set to that id, and no row was written under it. chat_messages.parent_id has no foreign key, so this lands silently, and _reseat_protected_messages only ever fires under prune_missing and only for managed_ids, so nothing repairs it. The comment already in studio_db.py:3714 puts it well: a dangling parent makes the whole thread unimportable on the next load, not just that turn. Nothing reads the id back either, since chat-history-storage.ts:1046 discards the response.
  2. It collapses branches that are not duplicates. The match is on content plus attachments, so two user branches that legitimately say the same thing under one parent become one.
  3. It reads the whole thread on every first user save. That is the per-message cost Studio: stop the per-chunk autosave writing back messages the server owns #9865 removed, and the comment about it is about fifty lines below the new lookup.

What I pushed

  • Reverted the history.append block. studio/frontend/src/features/chat/ and studio/backend/storage/studio_db.py are now byte-identical to main.
  • studio/backend/tests/test_chat_message_identity.py: genuine repeat sends on flat and branched threads, the stop-then-regenerate sequence with a large attachment, thread import and single-message delete (both also go through sync_chat_messages), legacy threads with a NULL or empty parent_id, and a randomised invariant over 60 seeds asserting that no sequence of writes leaves a parent dangling or loses a message. Every operation reuses the same body text, so a content-keyed write fails it on both counts.
  • studio/frontend/tests/chat-user-turn-identity.test.ts: guards the three frontend sites, in the style of the neighbouring cancelled-turn-history-prune.test.ts.

Verification: 131 backend tests pass, 6280 frontend tests pass, npm run typecheck clean, ruff clean. The new tests are load-bearing, not decoration: run them against the earlier version of this branch and 65 of 75 backend cases and all 5 frontend cases fail.

On the root cause

I could not find the path that writes the second row. Regenerate is ruled out above. I also ruled out the prompt queue (thread.tsx:3642 guards re-dispatch explicitly), the compare panes (shared-composer.tsx appendMessage and append are in mutually exclusive branches), and the Deep Research pre-persist (chat-adapter.ts:4311 reuses userMessage.id, so the upsert is idempotent).

@Iory1998 the studio.db rows in your report are the best evidence anyone has. If you still have a thread where it happened, SELECT id, parent_id, role, created_at FROM chat_messages WHERE thread_id = ? ordered by created_at, plus the metadata_json of the two user rows, would likely pin it. The generationRunId on the surrounding assistant rows would tell us which run each turn belonged to, which is the piece I am missing.

I would rather leave the duplicate in place for now than ship a guard that loses messages, so my suggestion is to land this as the test suite plus the revert, and open the root cause separately once we can reproduce it.

Not applicable here, for the record: this is chat history storage, so there is no GPU or hardware path involved, and the frontend now matches main exactly, so there is no new browser surface across WebView2, WKWebView or WebKitGTK.

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

chatgpt-codex-connector Bot commented Sep 1, 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-01T09:13:31.077641Z 87ed00d New commits
ℹ️ 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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

… 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.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@Iory1998

Iory1998 commented Sep 1, 2026 •

Copy link
Copy Markdown

@danielhanchen
It's stupid of me not the have taken a screenshot of the dups. Below is what you asked compiled by Deepseek. I am not a coder, so I had to rely on the agent to find the dup and compile it below:

Draft reply to post in PR #10064

Thanks for the deep dive and for landing the revert + test suite. That's the right call, and I agree we should not ship a content-hash guard that could drop legitimate sends. Here's everything I can give you from the one thread I still have where it happened, plus an observation I think is the piece you were missing.

1. The rows you asked for

Thread id __LOCALID_KQtciuT (rowid 317).

SELECT id, parent_id, role, created_at FROM chat_messages WHERE thread_id = ? ORDER BY created_at

id parent_id role created_at
4dwSP7r NULL user 1787854341631
Nmi02kB 4dwSP7r assistant 1787854341640
1GW3S79 Nmi02kB user 1787856918464
d7YROpZ 1GW3S79 assistant 1787856918469
zLNf9Wp d7YROpZ user 1787858909474
cOfdER0 zLNf9Wp assistant 1787858909480
oHXbD51 cOfdER0 user 1787861739724
EenXxCU oHXbD51 assistant 1787861739732
MAVhZII oHXbD51 assistant 1787862065697
SaKf868 cOfdER0 user 1787955784827
i59wGIe SaKf868 assistant 1787955784827
toVAdjZ SaKf868 assistant 1788232805365

metadata_json of the two user rows (oHXbD51, SaKf868): both NULL. User rows store no metadata_json; the generationRunId lives on the assistant rows.

2. generationRunId on the surrounding assistant rows (from metadata_json)

assistant id parent (user) generationRunId generationStatus notes
EenXxCU oHXbD51 a4db6515-3df6-4280-a7a5-d7db2847cfef failed incomplete.reason: interrupted
MAVhZII oHXbD51 36852791-fd47-492b-9aee-39d5c5c3fcf0 failed incomplete.reason: interrupted
i59wGIe SaKf868 acaf5bad-cd4b-4a15-9693-f99b0a73f2ca failed incomplete.reason: interrupted
toVAdjZ SaKf868 (completed; serverTimings present, cache_n 0, prompt_n 158936) completed final settled response

chat_generation_runs mapping (run id → user_message_id → assistant_message_id → status):

run id user assistant status
618f48ab-68d9-4f06-b33a-1a121442d39b 4dwSP7r Nmi02kB completed
c21e4567-bc50-416b-a611-45123b6d8db3 1GW3S79 d7YROpZ completed
686b8bcd-dcd5-44fb-a508-ea6a8fc3bc5a zLNf9Wp cOfdER0 completed
a4db6515-3df6-4280-a7a5-d7db2847cfef oHXbD51 EenXxCU failed
36852791-fd47-492b-9aee-39d5c5c3fcf0 oHXbD51 MAVhZII failed
acaf5bad-cd4b-4a15-9693-f99b0a73f2ca SaKf868 i59wGIe failed

3. The observation I think is the missing lead

oHXbD51 and SaKf868 are two [user] rows with the same parent_id = cOfdER0 and identical content/attachments (content omitted for privacy; happy to share redacted snippets to confirm identity).

The timing is the interesting part:

  • oHXbD51 created_at = 1787861739724. Both of its generations (a4db6515, 36852791) are generationStatus: failed, incomplete.reason: interrupted — so this user turn was Stopped/cancelled mid-generation and left with no completed assistant message.
  • SaKf868 created_at = 1787955784827 — ~26.1 h later (94,045,103 ms). Same parent_id, same content, driving its own runs (acaf5bad failed → i59wGIe, then the completed toVAdjZ).

So the duplicate is not a same-minute in-session regenerate cycle. That's consistent with your finding that the regenerate path (startRun({ parentId }), which mints a new assistant and leaves the user row alone) doesn't create a second user row.

It looks like a later session (re)persisting the earlier interrupted user turn: on a subsequent load, the app re-created the same user message against the original parent_id (cOfdER0) but minted a new message id (SaKf868) instead of reusing the existing oHXbD51 row.

4. Hypothesis and how I'd pin it

Strongest candidate is the idempotency of the user-turn upsert/append when re-seating an interrupted turn on a fresh load — it should reuse the existing row's id when one already exists under (thread_id, parent_id), keyed on identity, not content (to keep legitimately-identical sends across turns/branches separate, as you noted).

Times/symptoms that would confirm it: a generation with a large attachment → Stop it (leaving it interrupted, no assistant) → close and reopen the conversation → the app re-creates the same user turn under the same parent with a new id. If you instrument upsert_chat_message / the append site to log whether it hit an existing (thread_id, parent_id) user row vs minted a fresh id on reseat, that should reproduce it cleanly.

5. Happy to provide more

  • Redacted content/attachment lengths or hashes (not the text) of oHXbD51 and SaKf868 to prove they are byte-identical, if useful.
  • The full row dump for any other thread if you want a second data point (this is the one where I saw repeats of the same user turn up to 3x).

No DB file is attached for privacy; the tables above are the complete structural picture. Happy to run any query you want against the thread if it helps pin the write path.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 2831d76c8f

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

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

Copy link
Copy Markdown
Member

@Iory1998 this is exactly what was needed, thank you. No need to apologise for using an agent to pull it, the structure is what matters and it holds up.

I checked the one number everything turns on. 1787955784827 - 1787861739724 = 94,045,103 ms, which is 26.12 hours: oHXbD51 on 2026-08-27 20:15:39Z and SaKf868 on 2026-08-28 22:23:04Z. Different days, different sessions. So the duplicate is definitely not an in-session regenerate cycle, which lines up with MessageRuntime.reload() calling startRun({ parentId }) and never re-appending the user turn.

The part of your dump I had not considered

SaKf868 is parented to cOfdER0, and cOfdER0 is not the end of the branch. By the time it was written, the branch had run on to oHXbD51 -> EenXxCU / MAVhZII. A plain new send 26 hours later would parent to the last message in the thread, not back to the fork point.

Landing on the fork point means the tree was re-seated where oHXbD51 sits, and the thing in Studio that builds a user sibling under a turn's own parent is edit-and-resend. DefaultEditComposerRuntimeCore.handleSend calls append({ parentId, sourceId }) with no id, so LocalThreadRuntimeCore.append mints a fresh one. That produces precisely your shape: same parent, new id, attachments cloned along.

The one thing that would settle it

Please do send the hashes you offered. That is the discriminator, and I do not want to guess at it.

  • If oHXbD51 and SaKf868 are byte-identical, edit-resend is ruled out. Studio guards it at thread.tsx:8258 with if (newText === originalText) { composer().cancel(); return; }, so an edit that changes nothing never sends.
  • If they differ at all, even by trailing whitespace or one character, that guard passes and the second row is edit-and-resend working as designed. Not a bug, and no fix should go in.

Worth knowing about that guard either way: it compares aui.message().getCopyText(), and upstream getThreadMessageText is message.content.filter((part) => part.type === "text"). Attachments live on message.attachments, not in the text parts, so the comparison cannot see them. That is a real gap, though it is the opposite of your bug: it means an edit that changes only the attachments gets cancelled rather than duplicated.

Content length plus a sha256 of the content JSON for the two rows is enough. No text needed.

One correction to the draft you pasted: it suggests reusing an existing row's id under (thread_id, parent_id) on reseat. That is the guard this PR just removed, and it cannot stay. Two user rows under one parent with the same text is the normal, correct shape for a branch, and collapsing them loses a real turn and strands its replies. Whatever the fix turns out to be, it has to key on the identity of the turn being re-seated, not on what it says.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@danielhanchen danielhanchen changed the title fix(studio): deduplicate user message turns on regenerate to prevent context bloat (#9984) Studio: test that a chat message keeps its identity (#9984) Sep 1, 2026
@danielhanchen

Copy link
Copy Markdown
Member

Pushed 199ef05 and retitled the PR.

The frontend guards no longer punish a refactor

The previous version pinned the whole pruneOutboundHistory loop body against an expected string. That caught everything, including things it should not have: a variable rename, a reformat, or an added log line all failed it, which is a tax on whoever touches that function next for unrelated reasons.

It now counts the ways a turn can be dropped instead. Inside that loop there are three: a continue, a surviving.pop(), or making the push conditional. The abandoned-turn guard already owns exactly one of the first two, so a second of any of them is a dedupe under whatever name it is given. The input line stays pinned separately, since a filter folded into const history = [...messages] never touches the loop at all.

Checked both directions by injecting real code rather than by reading:

injected before now
early continue above the refusal check red red
filter folded into const history red red
extra surviving.pop() red red
conditional surviving.push red red
snapshot.messages = snapshot.messages.filter(...) red red
msgs.splice(...) red red
msgs.length = 0 red red
variable rename red green
reformat a one-line if into a block red green
add an unrelated statement red green

Title and closing keyword

The title said this deduplicates user turns on regenerate, and the body opened with Fixes #9984. Neither is true any more: the PR changes zero production files, so merging it would have auto-closed an open bug with no behaviour change behind it. Retitled, and the keyword is now a plain Refs, so #9984 stays open until someone actually fixes it.

Credit stays with @umran666 for the original patch and the two backend tests, and with @Iory1998 for the row dump.

134 backend tests, 6279 frontend tests, tsc clean, ruff clean, and the repo's own ruff-format hook applied.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
- 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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown
Member

Stopping the review loop here and flagging a decision rather than pushing another patch.

The pattern

Four rounds running, the frontend guards have been shown to have another hole, and each time the finding was correct. Verified by injecting the exact shape, not by reading:

round bypass result
1 banned identifier names only passed
2 early continue above the refusal check passed
3 block-form if (...) { surviving.push(...) } passed
3 filter in the reconstruction below the slice passed
4 history.splice(0, history.length, ...) after the copy passed
4 const dedupedMsgs = dedupeUserTurns(msgs) feeding both branches passed
4 payload.id = ... before saveStoredChatMessage(payload) passed

Each was patched and the next round found another. That is not bad luck. A source-text assertion has an unbounded evasion space, because there are unlimited ways to write "drop a message" in text, and no finite set of patterns closes it.

Why I am not patching again

A fifth pattern buys one round. The remedy suggested in all three of this round's items is the correct one: extract the pure logic and test it behaviourally.

That needs a production change, and it is not small. pruneOutboundHistory reaches isAbandonedAssistantTurn, isAnthropicRefusalMessage, assistantTurnCarriesPayload and toOpenAIMessages, so extracting it means moving a meaningful slice of chat-adapter.ts into an importable module. The load reconstruction lives inside useStudioRuntimeAdapters and cannot be called without rendering the hook.

Refactoring a hot path to make a test possible is a reasonable thing to do, but it is a maintainer call, and it is the opposite of what this PR currently is. So it goes to a human rather than into this branch.

What is unaffected

The backend suite in test_chat_message_identity.py is behavioural. It runs the real studio_db, and its randomised invariant over 60 seeds is what actually catches the data loss the reverted guards caused: a dangling parent or a vanished message, at the layer where it does the damage. None of the findings above touch it.

Where this leaves the PR

Tests only, no production change, correctly titled, and Refs #9984 rather than a closing keyword, so the issue stays open.

#9984 itself still turns on one unanswered question: whether the reporter's two rows are byte identical. Identical means edit and resend is ruled out and there is a defect to find. Any difference means the second row is expected behaviour. The rows are 26.12 hours apart in different sessions, with the second parented back to the fork point, which is the shape edit and resend produces.

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.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 1, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@danielhanchen
danielhanchen merged commit 9ea157e into unslothai:main Sep 2, 2026
35 of 36 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants