Skip to content

fix: race updating same record on concurrent message stream events#7493

Merged
diegolmello merged 1 commit into
developfrom
knowledgeable-bagel
Jul 15, 2026
Merged

fix: race updating same record on concurrent message stream events#7493
diegolmello merged 1 commit into
developfrom
knowledgeable-bagel

Conversation

@diegolmello

@diegolmello diegolmello commented Jul 13, 2026

Copy link
Copy Markdown
Member

Proposed changes

Concurrent stream-room-messages events for the same message id could throw Cannot update a record with pending changes (messages#…) / (threads#…).

WatermelonDB caches a record instance per id and prepareUpdate marks it with a pending state that is only cleared when the batch commits. updateMessage built its batch (calling prepareUpdate) outside db.write, and handleMessageReceived is a raw stream listener that is not serialized. When two events for the same id arrived close together, both grabbed the same cached record and the second prepareUpdate threw. The error was swallowed and logged as a warning, silently dropping that update.

The fix moves the reads, prepares and batch inside a single db.write so the WatermelonDB writer lock serializes concurrent updateMessage calls: the second call waits until the first commits (clearing the pending state) before preparing. Decryption stays outside the lock.

updateMessage is also converted to a plain async function, fixing a happy-path promise that never resolved (the previous new Promise never called resolve() after db.write, so the awaiting caller hung and the follow-up read never fired).

Issue(s)

https://rocketchat.atlassian.net/browse/NATIVE-1421

How to test or reproduce

Hard to reproduce by hand (a timing race between two stream events for the same message). Covered by an added regression test that fires two concurrent updateMessage calls for the same id and asserts no "pending changes" error is logged. The test's db.write mock serializes like the real writer lock, so it goes red on the old code and green on the fix.

TZ=UTC pnpm test --testPathPattern='subscriptions/room.test'

Screenshots

Types of changes

  • Bugfix (non-breaking change which fixes an issue)
  • Improvement (non-breaking change which improves a current function)
  • New feature (non-breaking change which adds functionality)
  • Documentation update (if none of the other choices apply)

Checklist

  • I have read the CONTRIBUTING doc
  • I have signed the CLA
  • Lint and unit tests pass locally with my changes
  • I have added tests that prove my fix is effective or that my feature works (if applicable)
  • I have added necessary documentation (if applicable)
  • Any dependent changes have been merged and published in downstream modules

Further comments

The same prepare-outside-writer pattern may exist in other onStreamData handlers that call prepare* before db.write; not swept in this PR.

Summary by CodeRabbit

  • Bug Fixes
    • Improved message update handling during concurrent operations.
    • Prevented erroneous “pending changes” errors when multiple updates are processed at the same time.
    • Ensured related message and thread updates are committed together for greater consistency.

@diegolmello diegolmello temporarily deployed to approve_e2e_testing July 13, 2026 13:45 — with GitHub Actions Inactive
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 35e8813e-6577-4f11-b13a-996e8a7e1fee

📥 Commits

Reviewing files that changed from the base of the PR and between 8dcd72b and cfa6b00.

📒 Files selected for processing (2)
  • app/lib/methods/subscriptions/room.test.ts
  • app/lib/methods/subscriptions/room.ts

Walkthrough

updateMessage now uses async control flow, while database write mocks serialize operations and a new test covers concurrent updates for the same message and thread.

Changes

Message update concurrency

Layer / File(s) Summary
Async updateMessage flow
app/lib/methods/subscriptions/room.ts
Refactors updateMessage to an async method while retaining message decryption, record preparation, and batch commit behavior.
Concurrent update coverage
app/lib/methods/subscriptions/room.test.ts
Serializes mocked writes, adds database lookup helpers, and verifies concurrent updates do not log a pending-changes error.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested labels: type: bug

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main fix: a race condition when concurrent message stream events update the same record.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


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.

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

🧹 Nitpick comments (1)
app/lib/methods/subscriptions/room.test.ts (1)

318-324: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Explicitly await concurrent sub.updateMessage calls rather than relying on setImmediate flushing.

The two sub.updateMessage calls are fired without await or .catch(), creating floating promises. While the mock setup does chain promises correctly (db.write → callback → db.batch → resolution), floating promises should still be handled explicitly. Replace the setImmediate workaround with await Promise.all([...]) to clearly express that both calls must complete before the test assertions run—this is cleaner and surfaces any rejections.

♻️ Proposed refactor: await both concurrent calls with Promise.all
-			// updateMessage's promise never resolves on the happy path, so fire both and flush the queues.
-			sub.updateMessage({ ...message });
-			sub.updateMessage({ ...message });
-			await Array.from({ length: 10 }).reduce<Promise<unknown>>(
-				chain => chain.then(() => new Promise(resolve => setImmediate(resolve))),
-				Promise.resolve()
-			);
+			await Promise.all([
+				sub.updateMessage({ ...message }),
+				sub.updateMessage({ ...message }),
+			]);
🤖 Prompt for 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.

In `@app/lib/methods/subscriptions/room.test.ts` around lines 318 - 324, In the
test around the concurrent sub.updateMessage calls, replace the unawaited
invocations and setImmediate queue-flushing reduce with Promise.all that awaits
both updateMessage promises concurrently. Preserve the existing two-call
behavior and ensure any rejection propagates before the assertions execute.

Source: Learnings

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

Nitpick comments:
In `@app/lib/methods/subscriptions/room.test.ts`:
- Around line 318-324: In the test around the concurrent sub.updateMessage
calls, replace the unawaited invocations and setImmediate queue-flushing reduce
with Promise.all that awaits both updateMessage promises concurrently. Preserve
the existing two-call behavior and ensure any rejection propagates before the
assertions execute.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: cf9ddc42-0957-4993-94ee-ecba312158ce

📥 Commits

Reviewing files that changed from the base of the PR and between 6e98b8b and 8dcd72b.

📒 Files selected for processing (2)
  • app/lib/methods/subscriptions/room.test.ts
  • app/lib/methods/subscriptions/room.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{js,ts,jsx,tsx}: Use descriptive names for functions, variables, and classes that clearly convey their purpose
Write comments that explain the 'why' behind code decisions, not the 'what'
Keep functions small and focused on a single responsibility
Use const by default, let when reassignment is needed, and avoid var
Prefer async/await over .then() chains for handling asynchronous operations
Use explicit error handling with try/catch blocks for async operations
Avoid deeply nested code; refactor complex logic into helper functions

Files:

  • app/lib/methods/subscriptions/room.ts
  • app/lib/methods/subscriptions/room.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use TypeScript for type safety; add explicit type annotations to function parameters and return types
Prefer interfaces over type aliases for defining object shapes in TypeScript
Use enums for sets of related constants rather than magic strings or numbers

**/*.{ts,tsx}: Use TypeScript in strict mode, with imports resolved from the app/ baseUrl
Follow the repository's TypeScript/React Native code style enforced by Prettier: tabs, single quotes, 130-character width, no trailing commas, omit arrow-function parens when possible, and keep brackets on the same line

Files:

  • app/lib/methods/subscriptions/room.ts
  • app/lib/methods/subscriptions/room.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Use the project's ESLint setup (@rocket.chat/eslint-config with React, React Native, TypeScript, and Jest plugins) for code quality and style compliance

Files:

  • app/lib/methods/subscriptions/room.ts
  • app/lib/methods/subscriptions/room.test.ts
🧠 Learnings (2)
📚 Learning: 2026-04-30T17:07:51.020Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7274
File: app/lib/services/voip/MediaCallEvents.ts:0-0
Timestamp: 2026-04-30T17:07:51.020Z
Learning: In this Rocket.Chat React Native codebase, the ESLint rule `no-void: error` is enforced. When you see a promise returned from an async call that is not awaited (a “floating promise”), do not silence it with the `void somePromise()` pattern. Instead, handle the promise explicitly by attaching `.catch(...)` (or otherwise awaiting/handling the error) so unhandled-rejection risks are addressed in a way that satisfies the existing ESLint configuration.

Applied to files:

  • app/lib/methods/subscriptions/room.ts
  • app/lib/methods/subscriptions/room.test.ts
📚 Learning: 2026-06-25T18:37:25.526Z
Learnt from: diegolmello
Repo: RocketChat/Rocket.Chat.ReactNative PR: 7434
File: app/views/ScreenLockConfigView.test.tsx:16-22
Timestamp: 2026-06-25T18:37:25.526Z
Learning: In Rocket.Chat ReactNative tests that mock selectors for `useAppSelector`, don’t require the mocked selector input to be typed as `IApplicationState` when the fixture only includes a partial Redux state slice (e.g., only `server` and `settings`). Requiring the full `IApplicationState` type in that scenario forces unsafe `as IApplicationState` casts and undermines type-safety. For these narrowly scoped selector-mock fixtures, use a less strict type (e.g., `any`) to keep the mock focused on the slice under test.

Applied to files:

  • app/lib/methods/subscriptions/room.test.ts
🔇 Additional comments (2)
app/lib/methods/subscriptions/room.ts (1)

268-284: LGTM!

Also applies to: 395-397

app/lib/methods/subscriptions/room.test.ts (1)

4-6: LGTM!

Also applies to: 92-92, 104-108

@github-actions

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown

iOS Build Available

Rocket.Chat 4.75.0.109347

Concurrent stream-room-messages events for the same message id could call
prepareUpdate on the same cached WatermelonDB record before either batch
committed, throwing 'Cannot update a record with pending changes'.

Move the reads, prepares and batch inside a single db.write so the writer
lock serializes concurrent updateMessage calls. Also converts updateMessage
to async, fixing a happy-path promise that never resolved.
@diegolmello diegolmello force-pushed the knowledgeable-bagel branch from 8dcd72b to cfa6b00 Compare July 15, 2026 13:27
@diegolmello diegolmello requested a deployment to approve_e2e_testing July 15, 2026 13:27 — with GitHub Actions Waiting
@diegolmello diegolmello merged commit 360cabc into develop Jul 15, 2026
4 of 6 checks passed
@diegolmello diegolmello deleted the knowledgeable-bagel branch July 15, 2026 13:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants