Skip to content

Resolve messaging schema conflicts and finalize messaging data model#44

Closed
lheutchy wants to merge 0 commit intodevfrom
feature/POLY-38-resolve-messaging-schema-and-finalize-data-model
Closed

Resolve messaging schema conflicts and finalize messaging data model#44
lheutchy wants to merge 0 commit intodevfrom
feature/POLY-38-resolve-messaging-schema-and-finalize-data-model

Conversation

@lheutchy
Copy link
Copy Markdown
Collaborator

@lheutchy lheutchy commented Feb 21, 2026

Linked Issues

Closes #38
Linear: POLY-38 (e.g., POLY-123)

Summary

Resolved merge conflicts from cherry-picking 13ec9d7 into feature/POLY-38-resolve-messaging-schema-and-finalize-data-model and established a single messaging model.

Changes

  • Resolved conflicts in:
    • backend/convex/schema.ts
    • backend/convex/messages.ts
  • Kept the secure HEAD messaging implementation (auth + participant access control + read receipts).
  • Added useful WIP schema fields while preserving existing behavior:
    • conversations.participantIds
    • conversations.lastMessageId
    • messages.type
  • Kept read tracking as timestamp-based (readAt) instead of boolean.
  • Kept identity fields (buyerId, sellerId, senderId, recipientId) as auth subject strings.
  • Updated tests/fixtures to match schema requirements.

How to Test

Steps to verify locally:

  • npm run lint
  • npm run typecheck
  • npm test
  • Manual flow:
    1. npm run dev:backend (in terminal A)
    2. npm run dev (in terminal B)
    3. Verify the change: <describe expected behavior/screens>

Checklist

  • Tests added/updated (if applicable)
  • Lint/tests pass locally (npm run lint)
  • Docs updated (README/ADR/changelog if needed)
  • Follows conventional commit format
  • No merge conflicts with dev

Screenshots / Demos

N/A

Summary by CodeRabbit

  • Chores
    • Added message-type support so messages now carry a type (defaults to "text") for more consistent handling.
    • Added explicit participant lists and conversation metadata to improve conversation consistency and backfill/normalization capabilities.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 21, 2026

Warning

Rate limit exceeded

@jaydonkc has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 18 minutes and 18 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e92e77f and 29155c4.

📒 Files selected for processing (1)
  • backend/convex/messages.ts
📝 Walkthrough

Walkthrough

Added a nullable type field to messages and participantIds + lastMessageId to conversations. Message sending now accepts an optional type (defaults to "text") and persists it; conversation creation ensures participantIds. Tests updated to include these fields and a backfill mutation was added.

Changes

Cohort / File(s) Summary
Schema
backend/convex/schema.ts
Add messages.type: v.optional(v.string()); add conversations.participantIds: v.optional(v.array(v.string())) and conversations.lastMessageId: v.optional(v.id('messages')); update by_listing_buyer_seller index to include sellerId.
Messaging Logic
backend/convex/messages.ts
sendMessage accepts optional type (defaults to 'text'); internalSendMessage signature now includes type and persists it; conversation creation flows (debugCreateConversationID, getOrCreateConversation) populate participantIds; added backfillMessagingFields mutation.
Tests & Utilities
backend/convex/__tests__/messages.test.ts, backend/convex/__tests__/testUtils.ts
Updated test fixtures to include type: 'text' on messages and participantIds: [buyerId, sellerId] on conversations to match schema changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • PR #26: Overlapping changes to Convex messaging schema and backend mutations (messages.ts, schema.ts).
  • PR #39: Related messaging and conversation updates adding type and participantIds across backend and tests.

Poem

🐰 Hopping through the code at night,
I tuck a type on messages tight.
Conversations now know who’s there,
IDs listed with tender care.
A tiny rabbit, system bright 🥕📨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR changes (schema updates, message type fields, participant IDs) do not align with issue #38's objective of documenting S3 storage configuration. Clarify the correct linked issue or update the PR to include S3 documentation as described in issue #38.
Out of Scope Changes check ⚠️ Warning All code changes (schema fields, message mutations, test updates) relate to the messaging data model, but the linked issue #38 is about S3 documentation. Verify the correct issue is linked; the messaging changes appear to be for a different issue (likely POLY-38 schema work).
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: resolving messaging schema conflicts and finalizing the messaging data model.
Description check ✅ Passed The description covers linked issues, summary of changes, testing instructions, and a checklist, aligning with the template structure.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/POLY-38-resolve-messaging-schema-and-finalize-data-model

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 and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
backend/convex/messages.ts (1)

119-123: ⚠️ Potential issue | 🟡 Minor

Debug conversation creation uses users document IDs instead of auth subject strings.

Line 121/122 take v.id('users'), but conversation participant identity checks compare against auth identity.subject. This can create debug conversations that participants can’t access.

Proposed fix
 export const debugCreateConversationID = internalMutation({
   args: {
     listingId: v.id('listings'),
-    buyerId: v.id('users'),
-    sellerId: v.id('users'),
+    buyerId: v.string(),
+    sellerId: v.string(),
   },

Also applies to: 127-131

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/convex/messages.ts` around lines 119 - 123, The args schema in
backend/convex/messages.ts incorrectly uses v.id('users') for buyerId and
sellerId (and the duplicate block at the later lines), but conversation
participant checks compare against auth identity.subject strings; change those
arg validators to accept the auth subject string (e.g., v.string()) and update
any debug conversation creation call sites to pass identity.subject for
buyerId/sellerId instead of user document IDs so the stored participant
identifiers match identity.subject checks.
🧹 Nitpick comments (1)
backend/convex/messages.ts (1)

56-67: Constrain type to a known set before persisting.

Line 67 defaults correctly, but currently any arbitrary string passes through and is stored (Line 110). Add a strict allowlist (or validator union) to prevent data drift.

Proposed tightening
 export const sendMessage = action({
   args: {
     conversationId: v.id('conversations'),
     body: v.string(),
     type: v.optional(v.string()),
   },
   handler: async (ctx, args): Promise<{ messageId: string }> => {
@@
-    const type = args.type ?? 'text';
+    const type = args.type ?? 'text';
+    const allowedTypes = new Set(['text']);
+    if (!allowedTypes.has(type)) {
+      throw new ConvexError('Invalid message type');
+    }
@@
     const result = await ctx.runMutation(internal.messages.internalSendMessage, {
@@
-      type: type,
+      type,
     });

Also applies to: 110-110

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/convex/messages.ts` around lines 56 - 67, The handler currently
accepts any args.type string and persists it; add a strict allowlist (e.g. const
ALLOWED_MESSAGE_TYPES = ['text','image','system',...] ) and validate args.type
against that before defaulting to 'text' and before saving, throwing a
ConvexError on invalid types; update the type schema/validator (where
v.optional(v.string()) is declared) to a union or enforce the same allowlist
there so only permitted types are accepted and stored (reference: handler,
args.type, ConvexError).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/convex/messages.ts`:
- Around line 285-305: The backfill currently loads entire conversations and
messages collections with ctx.db.query(...).collect() and patches them all at
once (variables: conversations, messages, conversationPatches, messagePatches,
ctx.db.patch), which is unbounded; change it to a bounded, rerunnable batching
loop: query each collection in fixed-size pages (e.g., limit N, use a
cursor/offset or last-id pagination) and process/patch only that page, commit
counts per page, and repeat until no more results; ensure each patch remains
idempotent by checking the same conditions (participantIds missing/invalid or
message.type missing) before patching so the job can be safely retried.

---

Outside diff comments:
In `@backend/convex/messages.ts`:
- Around line 119-123: The args schema in backend/convex/messages.ts incorrectly
uses v.id('users') for buyerId and sellerId (and the duplicate block at the
later lines), but conversation participant checks compare against auth
identity.subject strings; change those arg validators to accept the auth subject
string (e.g., v.string()) and update any debug conversation creation call sites
to pass identity.subject for buyerId/sellerId instead of user document IDs so
the stored participant identifiers match identity.subject checks.

---

Nitpick comments:
In `@backend/convex/messages.ts`:
- Around line 56-67: The handler currently accepts any args.type string and
persists it; add a strict allowlist (e.g. const ALLOWED_MESSAGE_TYPES =
['text','image','system',...] ) and validate args.type against that before
defaulting to 'text' and before saving, throwing a ConvexError on invalid types;
update the type schema/validator (where v.optional(v.string()) is declared) to a
union or enforce the same allowlist there so only permitted types are accepted
and stored (reference: handler, args.type, ConvexError).

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5105e27 and e92e77f.

📒 Files selected for processing (2)
  • backend/convex/messages.ts
  • backend/convex/schema.ts

Comment thread backend/convex/messages.ts
@jaydonkc
Copy link
Copy Markdown
Collaborator

jaydonkc commented Mar 2, 2026

Created clean companion branch jaydon/clean-pr-44.

Feedback:

  • Messaging schema direction is good, but rollout must be backward-compatible.
  • Ensure required-field migrations/backfills are in place before strict schema enforcement.
  • Keep tests covering legacy data shapes during migration window.

@jaydonkc jaydonkc closed this Mar 3, 2026
@jaydonkc jaydonkc force-pushed the feature/POLY-38-resolve-messaging-schema-and-finalize-data-model branch from 29155c4 to 792754d Compare March 3, 2026 02:14
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