Skip to content

fix: prevent invalid UUIDs in chat message saves - #715

Merged
ngoiyaeric merged 1 commit into
mainfrom
fix/uuid-validation-chat-save
Jul 10, 2026
Merged

fix: prevent invalid UUIDs in chat message saves#715
ngoiyaeric merged 1 commit into
mainfrom
fix/uuid-validation-chat-save

Conversation

@ngoiyaeric

@ngoiyaeric ngoiyaeric commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

Problem

When saving chat messages to the database, the messages table's id column (type uuid) was receiving invalid values like 4ccab2ce-f948-4a7b-bec6-103d5125687c-mxb7wz. These are base UUIDs with random suffixes appended by the deduplication logic.

Error:

invalid input syntax for type uuid: "4ccab2ce-f948-4a7b-bec6-103d5125687c-mxb7wz"

Root Cause

In lib/actions/chat-db.ts, the saveChat function handles duplicate message IDs (from the groupeId pattern in app/actions.tsx) by appending a random base62 suffix:

while (seenIds.has(id)) {
  id = `${id}-${Math.random().toString(36).substring(2, 8)}`;
}

This produces strings like 4ccab2ce-...-mxb7wz which are not valid UUIDs.

Solution

  1. Added isValidUUID() in lib/utils/index.ts — validates UUID v4 format using a regex.

  2. Added normalizeMessageId() in lib/actions/chat-db.ts — strips invalid suffixes (e.g. -mxb7wz) from existing IDs, and falls back to crypto.randomUUID() if the ID cannot be salvaged.

  3. Replaced suffix-based deduplication with crypto.randomUUID() — when a duplicate ID is detected, a completely new UUID is generated instead of appending a suffix.

  4. Added pre-insert validation in lib/actions/chat.ts — the saveChat wrapper now validates every message ID before sending to the DB, regenerating invalid ones.

  5. 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

File Change
lib/utils/index.ts Added isValidUUID() export
lib/actions/chat-db.ts Added normalizeMessageId(), replaced suffix logic with crypto.randomUUID(), added validation + fallback
lib/actions/chat.ts Added UUID validation before sending messages to DB

Testing

Verified that:

  • 4ccab2ce-f948-4a7b-bec6-103d5125687c-mxb7wz normalizes to 4ccab2ce-f948-4a7b-bec6-103d5125687c (valid UUID)
  • Duplicate IDs get unique crypto.randomUUID() replacements
  • All generated IDs pass UUID validation
  • Schema requires no changes (already uses gen_random_uuid() default)

Summary by CodeRabbit

  • Bug Fixes
    • Improved chat and message saving reliability when IDs are missing, malformed, or from legacy formats.
    • Prevented duplicate or invalid messages from interrupting chat saves.
    • Added fallback handling so individual message errors do not block the rest of a chat from being saved.
    • Improved validation of message and chat identifiers before storage.

@qodo-code-review

Copy link
Copy Markdown
Contributor

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@vercel

vercel Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
qcx Ready Ready Preview, Comment Jul 10, 2026 12:49pm

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.


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.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@ngoiyaeric, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 38 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f5e2e92a-d75f-470d-9006-53b2b37d56f2

📥 Commits

Reviewing files that changed from the base of the PR and between 8d33d17 and ebf373b.

📒 Files selected for processing (3)
  • lib/actions/chat-db.ts
  • lib/actions/chat.ts
  • lib/utils/index.ts

Walkthrough

Chat 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.

Changes

Chat UUID persistence

Layer / File(s) Summary
UUID validation contract
lib/utils/index.ts, lib/actions/chat.ts
Adds exported UUID v4 validation and imports the UUID helpers for chat message persistence.
Chat database normalization and fallback persistence
lib/actions/chat-db.ts
Normalizes and deduplicates message IDs, warns on invalid chat IDs, skips unrecoverable messages, validates created messages, and falls back to isolated upserts after bulk failure.
Server chat action UUID enforcement
lib/actions/chat.ts
Regenerates invalid message IDs before saving chat messages.

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
Loading

Possibly related PRs

  • QueueLab/QCX#505: Both changes modify chat/message persistence and saveChat upsert behavior.

Poem

A rabbit hopped through IDs at night,
Turning crooked UUIDs right.
Bulk rows danced, then one by one,
Failed little inserts still got done.
With fresh IDs in every stack,
Chat messages safely made it back.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main fix: preventing invalid UUIDs during chat message saves.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/uuid-validation-chat-save

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@charliecreates charliecreates Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking data-integrity issue in the new bulk-insert fallback.

Comment thread lib/actions/chat-db.ts
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) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between fdec5be and 8d33d17.

📒 Files selected for processing (3)
  • lib/actions/chat-db.ts
  • lib/actions/chat.ts
  • lib/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!

Comment thread lib/actions/chat-db.ts
Comment thread lib/actions/chat-db.ts
Comment thread lib/utils/index.ts
- 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).
@ngoiyaeric
ngoiyaeric force-pushed the fix/uuid-validation-chat-save branch from 8f2fa81 to ebf373b Compare July 10, 2026 12:47
@ngoiyaeric
ngoiyaeric merged commit 53c6dc5 into main Jul 10, 2026
5 of 6 checks passed
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.

2 participants