fix: restore message snapshot when tagging fails mid-pass
Problem
tagMessages() mutates message parts in place (e.g. §N§ text prefixing) after each DB write. If it throws mid-pass (DB error, etc.), the emitted messages array keeps the partial mutations — the LLM silently receives a prompt with partial tag prefixes that don't correspond to persisted state.
Fix
Snapshot { info, parts } (structuredClone) immediately before tagMessages(); on the tagging-failure catch path, restore via messages.splice(0, messages.length, ...snapshot). The existing taggingSucceeded gate and the documented no-outer-transaction design of tagMessages() are untouched — this only rolls back in-memory mutations, not durable DB semantics.
Tests
- mid-pass failure: tagger throws on the 2nd message after the 1st was already prefixed → asserts no part contains a
§N§prefix and both messages match their pre-tag text - happy path: successful pass still persists
source_contentsand replays dropped statuses (snapshot/restore is a no-op on success)
/codesmith with what you need. Autofix is disabled.
Greptile Summary
This PR guards against partial in-memory corruption when tagMessages() throws mid-walk by taking a structuredClone snapshot of {info, parts} immediately before the call and splicing the snapshot back on the catch path. The existing taggingSucceeded gate and no-outer-transaction design of tagMessages are left intact.
snapshotMessagesForTaggingclones every message'sinfoandpartsbefore tagging begins; on failure themessagesarray contents are restored so no stray§N§prefixes reach the LLM.- Two new integration tests cover the rollback path (tagger forced to throw on the 2nd
assignTag, asserts all text reverts to pre-tag content) and the happy path (source_contents and dropped-status replay still work correctly after the snapshot code was added).
Confidence Score: 4/5
Safe to merge; the fix correctly restores the message array on the failure path and is well-tested, with two minor robustness items worth a follow-up.
The snapshot/restore logic is sound and the taggingSucceeded gate prevents downstream stages from running on stale data. Two items are worth noting: structuredClone is called outside the try-catch so a DataCloneError from a non-cloneable part would bubble up as an unhandled transform failure, and the ...preTagSnapshot spread into splice has a theoretical argument-count ceiling. Neither is likely to trigger in practice given JSON-like parts and bounded message windows.
packages/plugin/src/hooks/magic-context/transform.ts — specifically the placement of snapshotMessagesForTagging relative to the try-catch and the splice restore pattern.
Important Files Changed
| Filename | Overview |
|---|---|
| packages/plugin/src/hooks/magic-context/transform.ts | Adds snapshotMessagesForTagging helper and a messages.splice restore on the tagging catch path; snapshot is taken outside the try-catch (structuredClone failure would be unhandled) and the spread-into-splice pattern has a theoretical argument-count ceiling. |
| packages/plugin/src/hooks/magic-context/transform.test.ts | Adds two new integration tests: mid-pass rollback (tagger throws on 2nd assignTag, asserts no §N§ prefixes survive) and happy-path regression (source_contents persisted, dropped status replayed correctly after snapshot code was added). |
Sequence Diagram
sequenceDiagram
participant T as transform()
participant S as snapshotMessagesForTagging()
participant TM as tagMessages()
participant DB as ContextDatabase
T->>S: "structuredClone({info, parts}) for each message"
S-->>T: preTagSnapshot[]
T->>TM: tagMessages(sessionId, messages, tagger, db)
loop per message part
TM->>DB: tagger.assignTag() SAVEPOINT
DB-->>TM: tag number
TM->>TM: prependTag mutates part.text in place
end
alt tagging succeeds
TM-->>T: TagMessagesResult
T->>T: "taggingSucceeded = true"
Note over T: downstream stages run normally
else tagMessages throws mid-walk
TM--xT: Error
Note over T: messages[0] already has §1§ prefix
T->>T: restore via splice
Note over T: in-memory array restored to pre-tag state
T->>T: tagger.cleanup(sessionId)
Note over T: taggingSucceeded stays false
end
Reviews (1): Last reviewed commit: "plugin: restore message snapshot when ta..." | Re-trigger Greptile
Greptile also left 2 inline comments on this PR.
Summary by cubic
Restores the pre-tag message snapshot when tagMessages() fails mid-pass, preventing partial §N§ prefixes from leaking into prompts. Keeps LLM input consistent with persisted state.
- Bug Fixes
- Take a deep snapshot of
{ info, parts }before tagging and splice it back on failure. - Keep
taggingSucceededgating and DB semantics unchanged; only in-memory mutations are rolled back. - Add integration tests for mid-pass rollback and the happy path (persisting
source_contentsand replaying dropped status).
- Take a deep snapshot of
Written for commit ef0f13b554e0cd6b6ef2ff854f13f57c5ed77c8c. Summary will update on new commits.
Thanks for this — the failure mode it guards against is real.
Our one concern is the hot path: structuredClone of the entire messages array on every transform pass is real per-turn overhead (the transform runs on every request, and the array can be large in long sessions) to protect against a rare mid-pass tagging failure. We're sensitive to hot-path allocation cost here.
Could you rework it so the happy path stays allocation-free — e.g. clone only on the failure path (catch → restore from a snapshot taken lazily), or capture a cheap restore token rather than a full deep clone up front? A version that adds no per-pass cost when tagging succeeds we'd be glad to merge. Happy to discuss the approach if helpful.
Thanks for this — the failure mode you identified is real and important: if tagMessages() throws mid-walk, the partially §N§-prefixed array can reach the model. We want that closed.
We're going a different route than the per-pass structuredClone snapshot, though. The transform runs on the hot path on every LLM call, and cloning the full message array each pass to guard a rare failure adds overhead we'd rather not pay on the 99.99% success path. Instead the direction we've settled on is:
- Build the managed array in private/local state and assign
output.messagesonly on success — so a mid-transform throw never leaves a half-mutated array in the first place (no snapshot needed). - On genuine unrecoverable failure, fall back to replaying the last-known-good cached m[0]/m[1] (boundary-validated) + a bounded tail-trim, rather than passing raw/partial history through.
That work folds into a larger transform/cache refactor we have queued, so I'm closing this PR rather than merging the clone approach — but you surfaced the exact bug it needs to handle, and that shaped the design. Thank you.