Skip to content

fix: re-fetch message inside the write in getThreadName - #7557

Open
OtavioStasiak wants to merge 1 commit into
developfrom
fix.refetch-message-inside-the-write-in-getthreadname
Open

fix: re-fetch message inside the write in getThreadName#7557
OtavioStasiak wants to merge 1 commit into
developfrom
fix.refetch-message-inside-the-write-in-getthreadname

Conversation

@OtavioStasiak

@OtavioStasiak OtavioStasiak commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

In getThreadName, the "no thread yet" branch prepared its update on a message record fetched before the network call and decryption. A sync write can update or delete that row during the gap, making prepareUpdate throw on a record with pending changes.

The message is now re-fetched inside the db.write callback, and the update is prepared on that fresh record. getSingleMessage and Encryption.decryptMessage stay outside the lock, and the function signature and callers are unchanged.

Added a regression test that mocks database.active and simulates a concurrent writer during the gap, the function still commits without throwing.

Issue(s)

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

How to test or reproduce

  • Run TZ=UTC npx jest app/lib/methods/getThreadName.test.ts — passes on this branch.
  • Stash app/lib/methods/getThreadName.ts and re-run — the test fails, showing the update was prepared on the stale record.
  • Manually: open a thread message from a room where the parent thread isn't cached yet (jump to message from Search/Messages view, or tap a thread
    reply after a fresh cache clear) while messages are syncing. The thread name should resolve and no "Cannot update a record with pending changes"
    error should be logged.
  • No UI changes — affects RoomView, SearchMessagesView and MessagesView only through the thread name they display.

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 thread naming updates to use the latest message data, preventing stale information from being saved during concurrent changes.
  • Tests

    • Added coverage for concurrent message updates and verified that thread names are saved correctly without unnecessary error logging.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

getThreadName now re-fetches the target message before the batched update. A Jest test covers concurrent replacement of a stale message and verifies the fresh record is updated.

Changes

Thread name race-condition fix

Layer / File(s) Summary
Refresh message before batch and verify the race path
app/lib/methods/getThreadName.ts, app/lib/methods/getThreadName.test.ts
getThreadName re-fetches the message before the batched update. The test verifies that the fresh record is updated once, the decrypted thread name is returned, and no error is logged.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

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 and concisely describes the main bugfix: re-fetching the message inside the write operation in getThreadName.

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

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

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

Add a fixture interface and an explicit helper return type.

buildMessageRecord has no return type. Define a MessageRecordFixture interface and declare buildMessageRecord(id: string): MessageRecordFixture. This keeps the fixture contract checked when the mocked update behavior changes.

As per coding guidelines, “add explicit type annotations to function parameters and return types” and “prefer interfaces over type aliases for defining object shapes in TypeScript”.

🤖 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/getThreadName.test.ts` around lines 47 - 61, Define a
MessageRecordFixture interface for the fixture object, then update
buildMessageRecord to explicitly return MessageRecordFixture while retaining its
existing id, tmsg, stale, and prepareUpdate members and behavior.

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/getThreadName.test.ts`:
- Around line 77-102: Strengthen the test around getThreadName by tracking when
the mocked db.write callback is active, then record whether each
mockedGetMessageById call occurs within that callback. Assert that the second
lookup happens while db.write is active, ensuring the re-fetch immediately
precedes the write rather than merely occurring after the network/decryption
work.

In `@app/lib/methods/getThreadName.ts`:
- Around line 37-44: Update the queued writer around getMessageById and the
thread prepareCreate to re-fetch getThreadById(tmid) after the writer begins;
only prepare the thread creation when that lookup still returns null. Keep the
existing create data and message update behavior unchanged, while preventing
duplicate creation when concurrent callers both passed the earlier check.

---

Nitpick comments:
In `@app/lib/methods/getThreadName.test.ts`:
- Around line 47-61: Define a MessageRecordFixture interface for the fixture
object, then update buildMessageRecord to explicitly return MessageRecordFixture
while retaining its existing id, tmsg, stale, and prepareUpdate members and
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: 9da091ca-d936-4f3c-96c9-405ec33b57be

📥 Commits

Reviewing files that changed from the base of the PR and between 41e87a8 and 3fbf11d.

📒 Files selected for processing (2)
  • app/lib/methods/getThreadName.test.ts
  • app/lib/methods/getThreadName.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/getThreadName.test.ts
  • app/lib/methods/getThreadName.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/getThreadName.test.ts
  • app/lib/methods/getThreadName.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/getThreadName.test.ts
  • app/lib/methods/getThreadName.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/getThreadName.test.ts
  • app/lib/methods/getThreadName.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/getThreadName.test.ts

Comment thread app/lib/methods/getThreadName.test.ts
Comment thread app/lib/methods/getThreadName.ts
Comment thread app/lib/methods/getThreadName.ts
Comment thread app/lib/methods/getThreadName.test.ts
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