fix: prevent invalid UUIDs in chat message saves - #715
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
ngoiyaeric seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account. You have signed the CLA already but the status is still pending? Let us recheck it. |
|
Warning Review limit reached
Next review available in: 38 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (3)
WalkthroughChat persistence now validates UUIDs, normalizes legacy message IDs, handles duplicate or invalid IDs, and isolates fallback insert failures. Both database and server chat actions regenerate invalid message IDs before storage. ChangesChat UUID persistence
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant ChatAction
participant saveChat
participant Database
ChatAction->>saveChat: provide messages with IDs
saveChat->>saveChat: validate and normalize message UUIDs
saveChat->>Database: bulk upsert messages
Database-->>saveChat: success or bulk error
saveChat->>Database: isolate failures with per-message upserts
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
| if (messagesToInsert.length > 0) { | ||
| try { | ||
| await tx.insert(messages).values(messagesToInsert).onConflictDoUpdate({ target: messages.id, set: { content: sql`EXCLUDED.content`, role: sql`EXCLUDED.role` } }); | ||
| } catch (dbError) { |
There was a problem hiding this comment.
Catching the failed bulk statement inside this outer db.transaction does not make the transaction usable again. This app uses Drizzle’s postgres-js driver (lib/db/index.ts); its transaction adapter calls client.begin, and postgres-js marks a query failure as an uncaught transaction error unless it is isolated in tx.transaction(...) / a savepoint. PostgreSQL also leaves the transaction aborted after the failed insert, so every per-message insert below will fail with 25P02, and the outer transaction rolls back.
As a result, the new path cannot save the good messages when any bulk insert error occurs, despite the stated fallback behavior. Put each attempt in a savepoint (for example, await tx.transaction(async (nestedTx) => ...)) or perform the retry in a fresh transaction after rolling back the bulk attempt; add coverage for a batch containing one constraint-invalid row and one valid row.
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@lib/actions/chat-db.ts`:
- Around line 197-215: After the bulk insert failure in the messages insertion
block, wrap each per-message retry inside a nested tx.transaction(...) savepoint
so a failed statement does not leave the parent transaction aborted. Preserve
the existing individual error handling and continue processing remaining
messages, using the retry logic around each messages insert.
- Around line 24-46: The normalizeMessageId function should use the shared
generateUUID() helper for both missing and unsalvageable IDs instead of
crypto.randomUUID(). Replace those fallback calls and ensure the helper is
imported from its existing module, matching the usage in lib/actions/chat.ts.
In `@lib/utils/index.ts`:
- Around line 24-38: Align UUID_REGEX and isValidUUID with the documented v4
contract: enforce version 4 and the RFC variant bits, and support the documented
brace-wrapped form, or revise the comments to accurately describe the accepted
format. Ensure the function’s documentation and implementation consistently
specify the same UUID formats.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
Run ID: 6b3af7e1-4dae-4a0d-8748-92772dcce0eb
📒 Files selected for processing (3)
lib/actions/chat-db.tslib/actions/chat.tslib/utils/index.ts
📜 Review details
🔇 Additional comments (2)
lib/actions/chat.ts (1)
22-22: LGTM!Also applies to: 212-219
lib/actions/chat-db.ts (1)
229-248: LGTM!
8d33d17 to
8f2fa81
Compare
- Add isValidUUID() validation to lib/utils/index.ts - Replace suffix-based deduplication (-mxb7wz style) with crypto.randomUUID() in saveChat - Add normalizeMessageId() that strips invalid suffixes and falls back to fresh UUID - Add UUID validation in saveChat wrapper (lib/actions/chat.ts) before sending to DB - Add graceful fallback from bulk insert to individual inserts on DB error - Add createMessage() UUID validation and regeneration Fixes PostgreSQL error: invalid input syntax for type uuid when groupeId is reused across multiple messages (response + related + followup).
8f2fa81 to
ebf373b
Compare
Problem
When saving chat messages to the database, the
messagestable'sidcolumn (typeuuid) was receiving invalid values like4ccab2ce-f948-4a7b-bec6-103d5125687c-mxb7wz. These are base UUIDs with random suffixes appended by the deduplication logic.Error:
Root Cause
In
lib/actions/chat-db.ts, thesaveChatfunction handles duplicate message IDs (from thegroupeIdpattern inapp/actions.tsx) by appending a random base62 suffix:This produces strings like
4ccab2ce-...-mxb7wzwhich are not valid UUIDs.Solution
Added
isValidUUID()inlib/utils/index.ts— validates UUID v4 format using a regex.Added
normalizeMessageId()inlib/actions/chat-db.ts— strips invalid suffixes (e.g.-mxb7wz) from existing IDs, and falls back tocrypto.randomUUID()if the ID cannot be salvaged.Replaced suffix-based deduplication with
crypto.randomUUID()— when a duplicate ID is detected, a completely new UUID is generated instead of appending a suffix.Added pre-insert validation in
lib/actions/chat.ts— thesaveChatwrapper now validates every message ID before sending to the DB, regenerating invalid ones.Added graceful bulk-to-individual fallback — if a bulk insert fails, the code falls back to inserting messages one-by-one with per-message error handling, so one bad message doesn't break the entire chat save.
Files Changed
lib/utils/index.tsisValidUUID()exportlib/actions/chat-db.tsnormalizeMessageId(), replaced suffix logic withcrypto.randomUUID(), added validation + fallbacklib/actions/chat.tsTesting
Verified that:
4ccab2ce-f948-4a7b-bec6-103d5125687c-mxb7wznormalizes to4ccab2ce-f948-4a7b-bec6-103d5125687c(valid UUID)crypto.randomUUID()replacementsgen_random_uuid()default)Summary by CodeRabbit