fix(db): move deleteMessage finds and prepares inside the writer lock - #7550
fix(db): move deleteMessage finds and prepares inside the writer lock#7550OtavioStasiak wants to merge 2 commits into
Conversation
Walkthrough
ChangesMessage deletion concurrency
Estimated code review effort: 3 (Moderate) | ~20 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
app/lib/methods/subscriptions/room.test.ts (1)
272-275: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert that the interaction task ran.
interactionTaskstaysnullif thedeleteMessagebranch never callsrunAfterInteractions.Promise.all([concurrentWrite, null])still resolves to a defined array, so Line 272 and thelogcheck at Line 274 pass without exercising the deletion path. Add an explicit non-null assertion so a regression in the event dispatch fails loudly.💚 Proposed assertion
await new Promise(resolve => setImmediate(resolve)); concurrentGate.resolve(); + expect(interactionTask).not.toBeNull(); await expect(Promise.all([concurrentWrite, interactionTask])).resolves.toBeDefined();🤖 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 272 - 275, Add an explicit assertion after the concurrent operation in the test around interactionTask, verifying that interactionTask is non-null before or alongside awaiting it. Keep the existing logging assertion, but ensure the test fails if deleteMessage never invokes runAfterInteractions.
🤖 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 272-275: Add an explicit assertion after the concurrent operation
in the test around interactionTask, verifying that interactionTask is non-null
before or alongside awaiting it. Keep the existing logging assertion, but ensure
the test fails if deleteMessage never invokes runAfterInteractions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5039f795-5118-4ac8-a7a2-b72cff703080
📒 Files selected for processing (2)
app/lib/methods/subscriptions/room.test.tsapp/lib/methods/subscriptions/room.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (3)
- GitHub Check: ESLint and Test / run-eslint-and-test
- GitHub Check: E2E Shard Preflight
- GitHub Check: format
🧰 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.test.tsapp/lib/methods/subscriptions/room.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/subscriptions/room.test.tsapp/lib/methods/subscriptions/room.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/subscriptions/room.test.tsapp/lib/methods/subscriptions/room.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.test.tsapp/lib/methods/subscriptions/room.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 (4)
app/lib/methods/subscriptions/room.ts (1)
152-178: LGTM!app/lib/methods/subscriptions/room.test.ts (3)
1-6: LGTM!
184-214: LGTM!
216-235: 📐 Maintainability & Code QualityNo change needed.
jest.restoreAllMocks()calls.mockRestore()on every local jest mock function, so it resetsmockDbBatch’s implementation from the inlinemockImplementation.> Likely an incorrect or invalid review comment.
Proposed changes
The
deleteMessagebranch ofhandleNotifyRoomReceivedlooked up the message, thread and thread message and calledprepareDestroyPermanentlyon each outsidedb.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 on the same id, for instance — left the prepared records stale, so the commit threwCannot update a record with pending changes(reaching Bugsnag) and the delete never landed locally: the message stayed visible until the next full sync.The three
findcalls, the threeprepareDestroyPermanentlycalls and thedb.batchnow all run inside a singledb.writecallback, so a remote delete commits its whole batch under the lock.The three locals are now typed
| undefined, which the compiler required once they shared scope with the batch. This is not a behavior change: WatermelonDB'sbatchis typed(...records: $ReadOnlyArray<Model | Model[] | null | void | false>)and documents that falsy entries are ignored, so a record that isn't found is skipped exactly as before.Adds one regression test: a concurrent writer races the record being deleted and the batch must commit without a "pending changes" throw. It fails on the current code and passes with the fix.
handleNotifyRoomReceived's signature and its caller are unchanged.Issue(s)
https://rocketchat.atlassian.net/browse/NATIVE-1465
How to test or reproduce
TZ=UTC pnpm test app/lib/methods/subscriptions/room.test.ts— all pass; revertroom.tsand the new test fails withCannot update a record with pending changesScreenshots
Types of changes
Checklist
Further comments
Summary by CodeRabbit