Skip to content

fix(db): move persistMessage lookups and prepares inside the writer lock - #7551

Open
OtavioStasiak wants to merge 1 commit into
developfrom
fix.db-writer-lock-persistMessage
Open

fix(db): move persistMessage lookups and prepares inside the writer lock#7551
OtavioStasiak wants to merge 1 commit into
developfrom
fix.db-writer-lock-persistMessage

Conversation

@OtavioStasiak

@OtavioStasiak OtavioStasiak commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

persistMessage looked up the message, thread and thread message and called prepareUpdate on each outside db.write, committing the batch in a separate write later. A concurrent writer touching any of those cached records during that window — an incoming message update in a busy room, for instance — left the prepared records stale, so the commit threw Cannot update a record with pending changes (reaching Bugsnag) and the finished download never attached to its message: the attachment stayed in a to-download state until the next sync, and the user had to tap it again.

The three lookups, the three prepareUpdate calls and the db.batch now all run inside a single db.write callback. The file and download work in downloadMediaFile stays outside the lock.

Because the lookups now happen under the lock, the if (batch.length) guard moved inside it and only wraps db.batch. A download for a message that no longer exists locally acquires the writer lock and does nothing, rather than skipping it — one no-op acquisition per completed download. There's a test pinning that no empty batch is committed.

persistMessage is now exported so the regression test can drive it directly; it was only reachable through downloadMediaFile's real file-download path. Its signature and its single caller are unchanged.

Adds one regression test: a concurrent writer races the record being updated and the batch must commit without a "pending changes" throw. It fails on the current code and passes with the fix.

Issue(s)

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

How to test or reproduce

  • TZ=UTC pnpm test app/lib/methods/handleMediaDownload.test.ts — all pass; revert handleMediaDownload.ts and the new test fails with Cannot update a record with pending changes
  • Tap an image, video or audio attachment in a room to download it — it renders as soon as the download finishes, with no second tap needed
  • Do the same in a busy room where messages keep arriving, so the download completes while other writes are in flight
  • Download an attachment from a message inside a thread, and from a thread parent — both the room view and the thread view show it
  • Download an attachment in an E2EE room, so the decrypt-file queue runs before the record is persisted
  • Reopen the room after each download to confirm the local title_link was saved, not just held in memory
  • Affects RoomView and the thread views, only through what the local DB holds for the attachment## 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

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability when multiple media downloads update the same message records concurrently.
    • Ensured message, thread, and attachment updates are saved together to prevent partial changes.
    • Prevented unnecessary database updates when matching records are unavailable.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

persistMessage is now exported and performs record lookup, update preparation, and batching inside one serialized database write transaction. Tests cover concurrent writers, attachment updates, prepared-record handling, and missing records.

Changes

Media persistence transaction

Layer / File(s) Summary
Transaction boundary
app/lib/methods/handleMediaDownload.ts
persistMessage is exported. Record lookup, update preparation, and conditional batching now run inside one database write transaction.
Concurrency and no-op validation
app/lib/methods/handleMediaDownload.test.ts
Mocks model serialized writes and prepared records. Tests validate concurrent updates, attachment persistence, batching, and the no-op path for missing records.

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

Possibly related PRs

Suggested labels: type: bug

Suggested reviewers: diegolmello

🚥 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 and concisely describes moving persistMessage lookups and preparation inside the database writer lock.
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.

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • NATIVE-1466: Request failed with status code 401

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.

Actionable comments posted: 1

🧹 Nitpick comments (2)
app/lib/methods/handleMediaDownload.ts (1)

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

Declare the exported result type.

Declare Promise<void> on persistMessage. This keeps the exported API contract explicit.

Proposed change
-export const persistMessage = async (messageId: string, uri: string, encryption: boolean, downloadUrl: string) => {
+export const persistMessage = async (
+	messageId: string,
+	uri: string,
+	encryption: boolean,
+	downloadUrl: string
+): Promise<void> => {

As per coding guidelines, add explicit type annotations to function parameters and return types.

🤖 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/handleMediaDownload.ts` at line 225, Update the exported
persistMessage function signature to explicitly declare a Promise<void> return
type, while preserving its existing parameter annotations and implementation
behavior.

Source: Coding guidelines

app/lib/methods/handleMediaDownload.test.ts (1)

7-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Type the test doubles.

mockDbBatch and makeRecord use any. makeRecord and deferred also infer their return types. Define minimal PreparedRecord and Deferred interfaces, then annotate these helper contracts.

This keeps the concurrency test checked when the mocked WatermelonDB record shape changes.

As per coding guidelines, use TypeScript for type safety, add explicit type annotations to function parameters and return types, and prefer interfaces for object shapes.

Also applies to: 158-180

🤖 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/handleMediaDownload.test.ts` around lines 7 - 29, Replace the
any-based test doubles with minimal PreparedRecord and Deferred interfaces, then
update mockDbBatch, makeRecord, and deferred with explicit parameter and
return-type annotations. Ensure the mocked database batch and record helpers use
these interfaces so changes to the WatermelonDB record shape remain
type-checked.

Source: Coding guidelines

🤖 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 `@app/lib/methods/handleMediaDownload.ts`:
- Around line 226-230: Update persistMessage and the getMessageById,
getThreadById, and getThreadMessageById lookup flow to use the captured db
instance inside db.write instead of database.active. Add a regression test that
switches the active database while the writer is queued and verifies records are
read from the captured database.

---

Nitpick comments:
In `@app/lib/methods/handleMediaDownload.test.ts`:
- Around line 7-29: Replace the any-based test doubles with minimal
PreparedRecord and Deferred interfaces, then update mockDbBatch, makeRecord, and
deferred with explicit parameter and return-type annotations. Ensure the mocked
database batch and record helpers use these interfaces so changes to the
WatermelonDB record shape remain type-checked.

In `@app/lib/methods/handleMediaDownload.ts`:
- Line 225: Update the exported persistMessage function signature to explicitly
declare a Promise<void> return type, while preserving its existing parameter
annotations and implementation behavior.
🪄 Autofix

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: CHILL

Plan: Pro Plus

Run ID: 87c843dc-98c1-40b6-a6be-ad443cf47a2d

📥 Commits

Reviewing files that changed from the base of the PR and between 576377d and 1b0c2c0.

📒 Files selected for processing (2)
  • app/lib/methods/handleMediaDownload.test.ts
  • app/lib/methods/handleMediaDownload.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: ESLint and Test / run-eslint-and-test
🧰 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/handleMediaDownload.ts
  • app/lib/methods/handleMediaDownload.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

Files:

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

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{js,jsx,ts,tsx}: Format JavaScript and TypeScript code with Oxfmt using the repository configuration: tabs, single quotes, 130-character width, no trailing commas, omitted arrow-function parentheses where possible, and same-line brackets.
Follow Oxlint rules configured in .oxlintrc.json, including the import, React, Jest, TypeScript, and React Native plugins.

Files:

  • app/lib/methods/handleMediaDownload.ts
  • app/lib/methods/handleMediaDownload.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/handleMediaDownload.ts
  • app/lib/methods/handleMediaDownload.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/handleMediaDownload.test.ts

Comment on lines 226 to +230
const db = database.active;
const batch: Model[] = [];
const messageRecord = await getMessageById(messageId);
if (messageRecord) {
batch.push(
messageRecord.prepareUpdate(m => {
m.attachments = mapAttachments({ attachments: m.attachments, uri, encryption, downloadUrl });
})
);
}
const threadRecord = await getThreadById(messageId);
if (threadRecord) {
batch.push(
threadRecord.prepareUpdate(m => {
m.attachments = mapAttachments({ attachments: m.attachments, uri, encryption, downloadUrl });
})
);
}
const threadMessageRecord = await getThreadMessageById(messageId);
if (threadMessageRecord) {
batch.push(
threadMessageRecord.prepareUpdate(m => {
m.attachments = mapAttachments({ attachments: m.attachments, uri, encryption, downloadUrl });
})
);
}
if (batch.length) {
await db.write(async () => {

await db.write(async () => {
const batch: Model[] = [];
const messageRecord = await getMessageById(messageId);

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find active-database transitions and their lifecycle context.
rg -n -C 5 --glob '*.{ts,tsx}' '\bsetActiveDB\s*\(' app

# Find persistence callers that can outlive a database switch.
rg -n -C 5 --glob '*.{ts,tsx}' '\bpersistMessage\s*\(' app

Repository: RocketChat/Rocket.Chat.ReactNative

Length of output: 3889


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== handleMediaDownload relevant sections =="
sed -n '1,280p' app/lib/methods/handleMediaDownload.ts | nl -ba | sed -n '1,280p'

echo "== database active implementation =="
sed -n '80,105p' app/lib/database/index.ts | nl -ba

echo "== package version hints for watermelon =="
rg -n '"watermelondb"' package.json pnpm-lock.yaml package-lock.json yarn.lock 2>/dev/null || true

echo "== imports of persistMessage and setImmediate usage =="
rg -n --glob '*.{ts,tsx}' 'persistMessage|setImmediate|setImmediate\(' app test 2>/dev/null || true

Repository: RocketChat/Rocket.Chat.ReactNative

Length of output: 256


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== handleMediaDownload relevant sections =="
sed -n '1,280p' app/lib/methods/handleMediaDownload.ts | awk '{printf "%6d\t%s\n", NR, $0}'

echo "== database active implementation =="
sed -n '80,105p' app/lib/database/index.ts | awk '{printf "%6d\t%s\n", NR, $0}'

echo "== package version hints for watermelon =="
for f in package.json pnpm-lock.yaml package-lock.json yarn.lock; do
  if [ -f "${f}" ]; then
    echo "--- ${f} ---"
    rg -n '"watermelondb"|watermelondb|`@nozbe/watermelondb`' "${f}" || true
  fi
done

echo "== imports/usages =="
rg -n --glob '*.{ts,tsx}' 'persistMessage|setImmediate\(' app test 2>/dev/null || true

Repository: RocketChat/Rocket.Chat.ReactNative

Length of output: 13455


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate database service implementations =="
fd -a 'Message|Thread|ThreadMessage' app/lib/database/services | sed 's#^\./##' | while read -r f; do
  echo "--- ${f} ---"
  rg -n -C 4 'export async function (getMessageById|getThreadById|getThreadMessageById)|collection|database.active|database' "$f" || true
done

echo "== full handleMediaDownload test relevant block =="
sed -n '140,235p' app/lib/methods/handleMediaDownload.test.ts | awk '{printf "%6d\t%s\n", NR, $0}'

Repository: RocketChat/Rocket.Chat.ReactNative

Length of output: 6026


🌐 Web query:

@nozbe/watermelondb 0.28.1-0 src Database index.js write batch database writer

💡 Result:

In WatermelonDB, the database.write() method and batch() function are central components for handling database modifications safely and efficiently [1][2]. The database.write() method ensures that operations are executed within a writer transaction [2]. This is critical for maintaining data consistency, as it guarantees that no other write operations occur concurrently [3]. When working inside a write block, you must use specific "prepare" methods (such as prepareUpdate, prepareCreate, prepareMarkAsDeleted, and prepareDestroyPermanently) rather than their asynchronous counterparts (like update() or create()) to prepare operations for a batch [1]. The batch() function, available on the Database instance or within an @writer method via this.batch(), accepts an array of these prepared operations [4][1]. By grouping these operations, WatermelonDB can execute them as a single transaction [5]. This is significantly more performant than executing individual write commands, as it reduces the overhead of database communication and transaction management [1][5]. Implementation details for batch include: - You must call batch() from inside an Action (a @writer method or a database.write() block) [4][1]. - It takes a list of prepared operations as arguments (or a single array) [1]. - Falsy values (null, undefined, false) passed to batch are ignored, allowing for conditional inclusion of operations [4][1]. - The method processes these operations by generating efficient SQL and notifying affected collections of the changes [4][5]. For example, using batching within a writer: await database.write(async => { await database.batch( record1.prepareUpdate(r => { r.title = 'New' }), collection.prepareCreate(r => { r.name = 'New' })) }) [1]

Citations:


🌐 Web query:

raw.githubusercontent.com/Nozbe/WatermelonDB/v0.28.1-0/src/Database/index.js lines 200 260

💡 Result:

In WatermelonDB version 0.28.1-0, the src/Database/index.js file handles the batch method, which is a core feature for executing multiple database operations efficiently [1][2][3]. The batch method allows developers to execute multiple record operations (such as prepareCreate, prepareUpdate, and prepareDestroyPermanently) in a single atomic transaction [4][5][6]. Based on the codebase patterns established in WatermelonDB [1][5][7], the batch method and its surrounding logic in src/Database/index.js generally adhere to these critical requirements: 1. Mandatory Action Wrapper: The batch method must be called from within a database.write() action [5][8][7]. This ensures that all batched operations are processed within a consistent, thread-safe environment [4][9]. 2. Synchronous Preparation: All operations passed to batch (like those returned by record.prepareUpdate()) must be prepared synchronously before the batch method is invoked [5][10][7]. Failing to do so—for example, by introducing asynchronous gaps between preparation and the batch call—will trigger warnings or errors in the library, as these records must be committed to the database in one atomic, synchronous step [10][7]. If you examine the specific code block spanning lines 200–260 of src/Database/index.js in this version, you will find the implementation of these batching mechanics, including the underlying calls to the database adapter that perform the actual writes and the logic that ensures the operations are valid and correctly ordered [1][8]. Using batch is the recommended way to perform bulk operations, as it significantly reduces the overhead of individual database transactions [4][9].

Citations:


🌐 Web query:

github.com Nozbe WatermelonDB v0.28.1-0 src Database index.js const _writeBatch

💡 Result:

In WatermelonDB, there is no identifier or variable named _writeBatch in the src/Database/index.js file [1]. Based on the WatermelonDB source code, the database batching functionality is implemented via the batch method within the Database class [1]. This method is designed to execute multiple prepared operations (created using prepareCreate, prepareUpdate, etc.) atomically within an Action or Writer context [1][2]. The term _writeBatch is frequently associated with Google Cloud Firestore's Node.js SDK, where it is used as an internal property within the Transaction class to manage a collection of write operations [3][4]. It is possible that confusion between these two libraries has occurred, as _writeBatch is a documented internal implementation detail in Firestore [3][5], but it does not exist in the WatermelonDB source code [1].

Citations:


🌐 Web query:

Nozbe WatermelonDB 0.28.1-0 "prepareUpdate" "Cannot update a record"

💡 Result:

The error "Cannot update a record with pending changes" in WatermelonDB occurs when you attempt to call prepareUpdate on a model that already has an uncommitted prepared state (either from a previous prepareUpdate, prepareCreate, or similar operation) [1][2][3]. In WatermelonDB, prepareUpdate marks a record with a pending flag (_preparedState) to ensure data consistency [2][3]. This flag must be cleared by passing the record into a database.batch operation synchronously within the same write transaction [3][4][5]. Common causes and solutions for this error include: 1. Stale Prepared States: If a batch operation fails midway (e.g., due to an error in one of the operations), records already prepared in that batch may remain stuck with the _preparedState flag [6][3]. Ensure that your batch operations are robust and that errors are handled so they do not leave the database in an inconsistent state [6][3]. 2. Asynchronous Mismatches: The prepareUpdate call must be followed by a synchronous execution of database.batch [4][5]. If you perform asynchronous work between preparing the update and executing the batch, or if you prepare an update but fail to include it in a batch, the record will remain locked [3][5]. Always call batch within the same @writer or database.write block as the preparation [4][7]. 3. Duplicate Operations: Attempting to prepare multiple updates for the same record within the same batch or across overlapping operations can trigger this error [6]. Verify that your code de-duplicates records before adding them to the batch, especially when processing sync data from a server [6]. 4. Developer Error/Debugging: If you suspect a record is stuck, it is often due to an error in the logic flow where the "prepare" phase is invoked but the "execute/batch" phase is skipped or fails [3]. In development, WatermelonDB may issue warnings if prepareUpdate is called but not followed by a synchronous batch [4][5]. If you are encountering this in the context of sync (where a remote operation might conflict with a local one), ensure your sync logic correctly checks whether a record already exists locally and handles the resolution (update vs. create) appropriately before calling the preparation methods [1][6].

Citations:


Use the captured database for persisted record lookups.

persistMessage queues a writer for db, but getMessageById, getThreadById, and getThreadMessageById read database.active inside db.write. If another operation switches the active database before the callback runs, db.batch can receive records prepared from a different database. Pass the captured db into these helpers, or query its collections directly, and add a regression test that switches databases while the queued writer is pending.

🤖 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/handleMediaDownload.ts` around lines 226 - 230, Update
persistMessage and the getMessageById, getThreadById, and getThreadMessageById
lookup flow to use the captured db instance inside db.write instead of
database.active. Add a regression test that switches the active database while
the writer is queued and verifies records are read from the captured database.

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.

1 participant