Repository navigation
Studio: test that a chat message keeps its identity (#9984) - #10064
danielhanchen merged 20 commits into
Conversation
|
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? |
|
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. 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. |
f3e4f93 to
d4b73a2
Compare
|
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:
|
…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.
|
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 stayStudio builds its runtime with Where it does bite:
What I pushed
Verification: 131 backend tests pass, 6280 frontend tests pass, On the root causeI could not find the path that writes the second row. Regenerate is ruled out above. I also ruled out the prompt queue ( @Iory1998 the 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 |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
… 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 Draft reply to post in PR #10064Thanks 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 forThread id
2.
|
| 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:
oHXbD51created_at = 1787861739724. Both of its generations (a4db6515,36852791) aregenerationStatus: failed,incomplete.reason: interrupted— so this user turn was Stopped/cancelled mid-generation and left with no completed assistant message.SaKf868created_at = 1787955784827 — ~26.1 h later (94,045,103 ms). Sameparent_id, same content, driving its own runs (acaf5badfailed →i59wGIe, then the completedtoVAdjZ).
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
oHXbD51andSaKf868to 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.
|
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". |
|
@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. The part of your dump I had not considered
Landing on the fork point means the tree was re-seated where The one thing that would settle itPlease do send the hashes you offered. That is the discriminator, and I do not want to guess at it.
Worth knowing about that guard either way: it compares 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 |
|
Pushed 199ef05 and retitled the PR. The frontend guards no longer punish a refactorThe previous version pinned the whole It now counts the ways a turn can be dropped instead. Inside that loop there are three: a Checked both directions by injecting real code rather than by reading:
Title and closing keywordThe title said this deduplicates user turns on regenerate, and the body opened with 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, |
- 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.
|
Stopping the review loop here and flagging a decision rather than pushing another patch. The patternFour 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:
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 againA 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. 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 unaffectedThe backend suite in Where this leaves the PRTests only, no production change, correctly titled, and #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.
|
You have reached your Codex usage limits for security reviews. Please try again later. |
|
You have reached your Codex usage limits for security reviews. Please try again later. |
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/core0.1.17,MessageRuntime.reload()callsstartRun({ parentId }), andstartRuncreates an assistant message.history.appendhas exactly two call sites in the core: one for the user turn on a composer send, one for the assistant inperformRoundtrip. 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_messagecollapsed a second identical send. Flat threads storeparent_idNULL throughout, so every root user turn shared one bucket.chat_messages.parent_idhas no foreign key, so that lands silently, and the file's own comment notes a dangling parent makes the whole thread unimportable.sync_chat_messagesdropped payload rows and stranded their children. That path is also thread import and single message delete, not just regenerate.pruneOutboundHistorycompared 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 emptyparent_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.studio/frontend/tests/chat-user-turn-identity.test.ts: guards the append, load and outbound prune sites. Neither function is exported andchat-adapter.tswill not import undernode --test, so these read source, counting the ways a turn can be dropped rather than pinning the text. Verified by injection in both directions.u2to ana1it 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.