Skip to content

perf: index 1:1 chats by participants instead of scanning reports on confirmation mount - #101219

Merged
Julesssss merged 10 commits into
Expensify:mainfrom
callstack-internal:perf/83503-one-on-one-chat-index
Oct 2, 2026
Merged

Julesssss merged 10 commits into
Expensify:mainfrom
callstack-internal:perf/83503-one-on-one-chat-index

Conversation

@OlimpiaZurek

@OlimpiaZurek OlimpiaZurek commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

IOURequestStepConfirmation resolved the existing P2P chat with a COLLECTION.REPORT selector running getChatByParticipants. That helper is Object.values(reports).find(...) with per-report work (an Object.keys on participants, two report-type predicates, a sort and a deep compare), so answering "which chat do I share with this person" walked the entire report collection on the confirmation page's mount path.

This adds a ONE_ON_ONE_CHAT_REPORT_IDS derived value that indexes 1:1 and system chats by participant set, so the page resolves the chat with a lookup instead. Reports are keyed by reportID, so a participant-set lookup can't be answered without walking them, this re-keys the collection rather than duplicating a key it already has.

Fixed Issues

$ #101401
PROPOSAL:

Tests

  1. Sign in on an account that already has a 1:1 chat with another user.
  2. Open the global +, choose Create expense, enter an amount, and pick that user as the recipient.
  3. On the confirmation page, verify the destination is the existing chat and no new chat is created on submit.
  4. Repeat with a user you have no existing chat with. Verify a new chat is created and opens with the expense, without flashing a report that does not exist.
  5. Web: open the confirmation page for a user you already have a 1:1 chat with, then reload. The page comes back with the same recipient. Submit, then check that the expense is in the existing chat and the LHN has no second chat with that user.
  6. Native: kill the app and open it again. Right away, start Create expense with the same user and submit. Check that the expense is in the existing chat and the LHN has no second chat with that user.
  7. Create an expense with a workspace as the destination and verify it is unaffected.
  • Verify that no errors appear in the JS console

Offline tests

QA Steps

// TODO: These must be filled out, or the issue title must include "[No QA]."
Same as tests

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I used JaimeGPT to get English > Spanish translation. I then posted it in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.ts or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

@melvin-bot

melvin-bot Bot commented Sep 16, 2026

Copy link
Copy Markdown

@FitseTLT Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot removed the request for review from a team September 16, 2026 15:06

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 88a6b3aa0d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@joekaufmanexpensify

Copy link
Copy Markdown
Contributor

No product review needed

@joekaufmanexpensify
joekaufmanexpensify removed their request for review September 17, 2026 16:11
@OlimpiaZurek

Copy link
Copy Markdown
Contributor Author

Hey @FitseTLT, can you take a look at and review if you have a chance? Thanks!

@FitseTLT

Copy link
Copy Markdown
Contributor

Thx REviewing

Comment on lines +12 to +19
let participantsKeyByReportID: Record<string, string> = {};

/**
* In index order, so deleting the winner promotes the next one instead of dropping the key. Optimistic chat creation
* puts two reports on the same participants until the server report replaces the optimistic one, and the confirmation
* page has to keep resolving a chat throughout.
*/
let reportIDsByParticipantsKey: Record<string, string[]> = {};

@FitseTLT FitseTLT Sep 22, 2026 •

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.

BTW the reason we are having this moduled scoped variables is for the case where multiple reports can exist with identical key but I checked the case of creation of a new optimistic dm chat or other dm cases but it doesn't happen. But having them causes the rederivation on every reload. Is it worth it? Even if we want to consider the case we can save the derived as reportid array instead.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed the module scoped variables and changed to refilling the key from reports when the indexed report goes away. However, it still rebuilds once on startup, because the persisted index can be stale against reports.

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.

I really feel like the refill case is irrelevant in any real case but it instead runs when you clear cache for me for some unknown report (with the key change of some key -> undefined key) and when I open the report it shows me not found. Which means the BE is sending some wrong data and clearing it.
From what i understand what would have been a useful circumstance for the refill is if there were two reports with same key and when one is removed we want to recalculate the key with the other report's id because this report might not trigger a recalculation. But for the preexiting report id case the optimsitic first exists then in any order optimistic clearance and BE report writing happens which would trigger a calculation that early returns b/c the optimsitic report is cleared and writing the new BE report id on the key respectively.
But if you still feel safe with it, I am ok.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It only scans reports for another report with the same key and never writes or clears report data. In your clear cache case it just found nothing and left the key empty, which is correct since that report is gone. The not found is the BE data, like you said.
For the preexisting case, I agree it's fine when the optimistic report is cleared before (or in the same update as) the BE report is written. The order that breaks is the other one: replaceOptimisticReportWithActualReport clears the optimistic report and writes the preexisting one inside runAfterTransitions, so it's deferred. If the real report reaches onyx before that runs, its compute skips it because the key still points to the optimistic report. Then the optimistic report is cleared, the key is deleted, and the real report never triggers another compute, so the key stays empty while the report exists. The next confirmation mount then misses the DM and creates another optimistic one. The refill covers exactly that case, and it only costs one scan when an indexed report loses its key, so I'd prefer to keep it.

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/ONYXKEYS.ts 100.00% <ø> (ø)
src/libs/ReportUtils.ts 87.54% <100.00%> (+0.02%) ⬆️
...rc/libs/actions/OnyxDerived/ONYX_DERIVED_VALUES.ts 100.00% <ø> (ø)
...tions/OnyxDerived/configs/oneOnOneChatReportIDs.ts 100.00% <100.00%> (ø)
...es/iou/request/step/IOURequestStepConfirmation.tsx 77.53% <100.00%> (ø)
... and 9 files with indirect coverage changes

// never show up in a delta, so it is rebuilt rather than trusted.
// A SESSION change can carry a different account (delegate switching writes it before clearing Onyx), and
// the index doesn't record which account it was built for.
if (!currentValue || !sourceValues || hasKeyTriggeredCompute(ONYXKEYS.SESSION, triggeredKeys)) {

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.

1.So this will make whole rebuild happen on any prop change on session. We only want if currentUserAccountID changed. So can't we save a unique prop in the derived object to identify to what accountID the derived is calculated for. We will only recalculate when they mismatch.
2. And shouldn't we check for isEmptyObject for currentValue.

or a single check of is it calculated on the currentUserAccountID could suffice.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

  1. Changed.
  2. I don't think we need a separate isEmptyObject check. When there's no accountID or no reports yet we return {reportIDs: {}} without an accountID, so the next compute sees the mismatch and rebuilds. An empty check would also add an extra rebuild on every report update for users with no DMs.

@FitseTLT

FitseTLT commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick).
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately and each prop has a /** comment above it */
    • The file is named correctly
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • For Class Components, any internal methods passed to components event handlers are bound to this properly so there are no scoping issues (i.e. for onClick={this.submit} the method this.submit should be bound to this in the constructor)
    • Any internal methods bound to this are necessary to be bound (i.e. avoid this.submit = this.submit.bind(this); if this.submit is never passed to a component event handler like onClick)
    • All JSX used for rendering exists in the render method
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: HybridApp
2026-09-29.16-41-32.mp4
iOS: HybridApp
iOS: mWeb Safari
2026-09-29.16-40-12.mp4
MacOS: Chrome / Safari
2026-09-29.16-32-34.mp4

@FitseTLT

Copy link
Copy Markdown
Contributor

@OlimpiaZurek Regarding

Cold-start the app and go straight to the confirmation page for an existing 1:1 recipient. Verify the existing chat is still resolved

There is a bug in current branch as it doesn't populate the DM chat properly from a deeplink. In fact if it is immediately after clearing cache it returns not found page.

2026-09-28.19-01-16.mp4

@OlimpiaZurek

Copy link
Copy Markdown
Contributor Author

@OlimpiaZurek Regarding

Cold-start the app and go straight to the confirmation page for an existing 1:1 recipient. Verify the existing chat is still resolved

There is a bug in current branch as it doesn't populate the DM chat properly from a deeplink. In fact if it is immediately after clearing cache it returns not found page.

2026-09-28.19-01-16.mp4

@FitseTLT could you share the exact repro steps? From the video it looks like the link was opened in a different env than the one where the flow was started. The selected recipient isn't passed through the URL, which only contains the fixed draft transaction ID (1) and a reportID. The picked participant lives in the Onyx draft transactionsDraft_1, and staging and dev are separate origins with separate storage.

I see the same behavior on main, so it isn't caused by this PR.

Within the same environment it works as expected for me.

@FitseTLT

Copy link
Copy Markdown
Contributor

Sorry 🙏 @OlimpiaZurek Spot on!

@FitseTLT

Copy link
Copy Markdown
Contributor

Cold-start the app and go straight to the confirmation page for an existing 1:1 recipient. Verify the existing chat is still resolved

How are they going to confirm page directly?

@OlimpiaZurek

Copy link
Copy Markdown
Contributor Author

Cold-start the app and go straight to the confirmation page for an existing 1:1 recipient. Verify the existing chat is still resolved

How are they going to confirm page directly?

This point was a bit misleading, updated it in the PR description

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

LGTM

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

Thanks for working on this!

@Julesssss
Julesssss merged commit 9f83a2b into Expensify:main Oct 2, 2026
37 of 39 checks passed
@github-actions

github-actions Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

🚧 Julesssss has triggered a test Expensify/App build. You can view the workflow run here.

@OSBotify

OSBotify commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify OSBotify mentioned this pull request Oct 4, 2026
59 tasks done
@OSBotify

OSBotify commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/Julesssss in version: 9.5.2-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update is needed. This PR is an internal performance change: it finds an existing 1:1 chat with a lookup instead of scanning every report, and expense creation behaves the same for users.


view run

@OSBotify

OSBotify commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/Julesssss in version: 9.5.2-4 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

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.

7 participants