App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-25] [$175] Move the unread indicator onto useOnyx so report updates stop getting slower over a session

Open mountiny opened this issue 4 weeks ago • 30 comments

Proposal: https://expensify.slack.com/archives/C05LX9D6E07/p1793716152641419

Background

The unread indicator (the tab title on web and the app badge on iOS) counts unread reports after every report update. It runs as a plain module outside React in src/libs/UnreadIndicatorUpdater: it reads its data with Onyx.connectWithoutView and caches the count with its own memoize.

Problem

Every report update creates a new copy of the reports list, so the cache never finds a match. Instead it saves each new copy and never clears the old ones, and on every update it compares the new copy against every copy saved before. The longer the app stays open, the more memory it holds and the slower every report update gets. For heavy users with thousands of reports, each update gets slower all through the day.

Solution

Move the unread logic into a small component that renders nothing and reads its data with useOnyx. React Compiler caches the count and only redoes it when its data changes, so no old copies are kept and no custom cache is needed. The counting itself becomes a pure function, and the module-level Onyx subscriptions, the debounce and the navigation listener go away. The unread count behaves the same for the user.

Results

Heavy test account with 4,061 reports, production web build, 4× CPU slowdown, 200 report updates, same day:

  • Today: the unread check costs about 0.9 ms more with every update, with no limit: 26 ms at the start, 187 ms after 200 updates. The whole update goes from 519 ms to 678 ms.
  • With the fix: the unread check stays flat at about 14 ms, and the whole update stays at about 510 ms for all 200 updates.
  • After 200 updates: 678 ms today vs 508 ms with the fix, 170 ms (25%) less per update. The unread check alone drops from 187 ms to 13 ms (93% less), and the gap keeps growing as the session goes on.
  • Averaged over all 200 updates: 590 ms vs 513 ms, 77 ms (13%) less per update.
Issue OwnerCurrent Issue Owner: @mallenexpensify
Upwork Automation - Do Not Edit

mountiny avatar Nov 03 '26 21:11 mountiny

Triggered auto assignment to Contributor-plus team member for initial proposal review - @abdulrahuman5196 (External)

melvin-bot[bot] avatar Nov 03 '26 21:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022117736005990270496

melvin-bot[bot] avatar Nov 03 '26 21:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

The unread indicator (browser tab title on Web and app icon badge on iOS) updates its counts after every report update via src/libs/UnreadIndicatorUpdater. Currently, it runs outside React using Onyx.connectWithoutView module subscriptions and caches calculations with memoize. Because every report update creates a new object reference in Onyx, memoize never hits the cache, accumulates past object references indefinitely without bounds, and compares the new copy against every prior copy. For accounts with thousands of reports, memory consumption balloons and each report update degrades progressively over a session (from ~26ms to 187ms+ per unread check).

What is the root cause of that problem?

  1. In src/libs/UnreadIndicatorUpdater/index.ts:
    • Line 131 wraps getUnreadReportsForUnreadIndicator with memoize(..., {maxArgs: 3}). memoize defaults to an unbounded cache storing all seen argument combinations. Because allReports is an OnyxCollection<Report> object that receives a new reference on every Onyx update, cache hits never occur.
    • The cache retains every previous reports object reference indefinitely, leading to memory growth and linear comparison degradation.
  2. The unread computation relies on module-level closures (allReports, allReportNameValuePairs, allReportActions, allDraftComments, reportAttributesDerived, currentUserAccountID, currentUserLogin, conciergeReportID) maintained by imperative Onyx.connectWithoutView calls, manual debouncing, navigationRef.addListener('state'), and AppStateMonitor listeners outside React's reactive lifecycle.

What changes do you think we should make in order to solve the problem?

  1. Convert getUnreadReportsForUnreadIndicator into a pure function: In src/libs/UnreadIndicatorUpdater/index.ts (or getUnreadReportsForUnreadIndicator.ts):

    • Refactor getUnreadReportsForUnreadIndicator to receive all its data dependencies purely via arguments (with optional defaults for unit test compatibility), eliminating all module-level state:
    function getUnreadReportsForUnreadIndicator(
        reports: OnyxCollection<Report>,
        currentReportID?: string,
        draftComment?: string,
        reportNameValuePairs?: OnyxCollection<ReportNameValuePairs>,
        reportActions?: OnyxCollection<ReportActions>,
        reportAttributesDerived?: ReportAttributesDerivedValue['reports'],
        currentUserLogin?: string,
        currentUserAccountID?: number,
        conciergeReportID?: string,
    ): Report[] {
        const isOffline = getIsOffline();
        return Object.values(reports ?? {}).filter((report) => {
            const notificationPreference = ReportUtils.getReportNotificationPreference(report);
            if (ReportUtils.isHiddenForCurrentUser(notificationPreference) || notificationPreference === CONST.REPORT.NOTIFICATION_PREFERENCE.MUTE) {
                return false;
            }
            const nameValuePairs = reportNameValuePairs?.[`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID}`];
            const isReportArchived = ReportUtils.isArchivedReport(nameValuePairs);
            const chatReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.chatReportID}`];
            const oneTransactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, reportActions?.[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report?.reportID}`], isOffline);
            const oneTransactionThreadReport = reports?.[`${ONYXKEYS.COLLECTION.REPORT}${oneTransactionThreadReportID}`];
            const derivedIsEmptyReport = report?.reportID ? reportAttributesDerived?.[report.reportID]?.isEmpty : undefined;
    
            if (!ReportUtils.isUnread(report, oneTransactionThreadReport, isReportArchived, derivedIsEmptyReport)) {
                return false;
            }
    
            return ReportUtils.shouldReportBeInOptionList({
                report,
                chatReport,
                currentReportId: currentReportID,
                isDefaultRoomsBetaEnabled: false,
                doesReportHaveViolations: false,
                isInFocusMode: false,
                excludeEmptyChats: false,
                isReportArchived,
                draftComment,
                currentUserLogin: currentUserLogin ?? '',
                currentUserAccountID: currentUserAccountID ?? CONST.DEFAULT_NUMBER_ID,
                hasGuidesEmails: ReportUtils.isDefaultRoom(report) ? ReportUtils.hasExpensifyGuidesEmails(Object.keys(report?.participants ?? {}).map(Number), undefined) : false,
                conciergeReportID,
                derivedIsEmptyReport,
            });
        });
    }
    
  2. Create the headless component src/UnreadIndicatorHandler/index.tsx: Create a component that renders null, isolates the Onyx subscriptions using useOnyx, and reactively triggers updateUnread:

    import {useEffect, useMemo} from 'react';
    import useOnyx from '@hooks/useOnyx';
    import {useCurrentReportIDState} from '@hooks/useCurrentReportID';
    import ONYXKEYS from '@src/ONYXKEYS';
    import CONST from '@src/CONST';
    import {getUnreadReportsForUnreadIndicator} from '@libs/UnreadIndicatorUpdater';
    import updateUnread from '@libs/UnreadIndicatorUpdater/updateUnread';
    
    function UnreadIndicatorHandler() {
        const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
        const [session] = useOnyx(ONYXKEYS.SESSION);
        const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID);
        const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
        const [reportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
        const [draftComments] = useOnyx(ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT);
        const [reportAttributesDerived] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES);
        const {currentReportID} = useCurrentReportIDState();
    
        const currentUserAccountID = session?.accountID ?? CONST.DEFAULT_NUMBER_ID;
        const currentUserLogin = session?.email ?? '';
        const draftComment = currentReportID ? draftComments?.[`${ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT}${currentReportID}`] : undefined;
    
        const unreadReports = useMemo(() => {
            return getUnreadReportsForUnreadIndicator(
                reports,
                currentReportID,
                draftComment,
                reportNameValuePairs,
                reportActions,
                reportAttributesDerived?.reports,
                currentUserLogin,
                currentUserAccountID,
                conciergeReportID,
            );
        }, [reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived, currentUserLogin, currentUserAccountID, conciergeReportID]);
    
        const unreadReportIDs = useMemo(() => {
            return unreadReports.map((report) => report?.reportID).filter((id): id is string => !!id);
        }, [unreadReports]);
    
        useEffect(() => {
            updateUnread(unreadReports.length, unreadReportIDs);
        }, [unreadReports.length, unreadReportIDs]);
    
        return null;
    }
    
    export default UnreadIndicatorHandler;
    
  3. Preserve Android efficiency via src/UnreadIndicatorHandler/index.android.tsx: updateUnread is a no-op on Android. To avoid registering 7 unnecessary collection subscriptions on Android (preserving the existing load.android.ts optimization), provide:

    function UnreadIndicatorHandler() {
        return null;
    }
    export default UnreadIndicatorHandler;
    
  4. Mount <UnreadIndicatorHandler /> in src/Expensify.tsx: Mount <UnreadIndicatorHandler /> in Expensify.tsx right next to <PriorityModeHandler /> and other handlers. Because Expensify.tsx is wrapped by CurrentReportIDContextProvider, useCurrentReportIDState automatically and reactively re-evaluates the unread count when switching chats.

  5. Remove obsolete code:

    • Remove loadUnreadIndicatorUpdater from src/SplashScreenStateContext.tsx and delete src/libs/UnreadIndicatorUpdater/load.ts and load.android.ts.
    • Remove module-level Onyx.connectWithoutView, memoize, debounce, and the navigation/AppState listeners from src/libs/UnreadIndicatorUpdater/index.ts.

What alternative solutions did you explore? (Optional)

  • Adding an LRU cache or clearing memoize entries in src/libs/UnreadIndicatorUpdater/index.ts: Rejected because keeping module-level Onyx subscriptions and custom cache management outside React's tree goes against modern NewDot architectural standards. React Compiler and useOnyx provide automatic dependency tracking, memoization, and lifecycle garbage collection without custom memory retention.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c

ayolyn avatar Nov 03 '26 22:11 ayolyn

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 03 '26 22:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

The unread indicator (browser tab title on Web and app icon badge on iOS) recalculates unread counts via src/libs/UnreadIndicatorUpdater. Currently running outside React via module-level Onyx.connectWithoutView subscriptions, it caches calculations with memoize(getUnreadReportsForUnreadIndicator, {maxArgs: 3}). Because each report update instantiates a new allReports collection object reference, memoize never hits a matching cache key, indefinitely accumulates references, and iterates over every previously saved copy on each comparison. On accounts with thousands of reports, this causes memory bloat and progressively increases unread check duration from ~26ms to over 187ms over a session.

What is the root cause of that problem?

In src/libs/UnreadIndicatorUpdater/index.ts:

  1. getUnreadReportsForUnreadIndicator is wrapped with memoize(..., {maxArgs: 3}). memoize defaults to an unbounded lookup cache. Because allReports is an OnyxCollection<Report> that receives a new reference identity on every Onyx update, cache lookups always miss while indefinitely retaining previous allReports object graphs in memory.
  2. In addition, the updater relies on module-level Onyx.connectWithoutView subscriptions, manual debounce, and Navigation.getTopmostReportId() polling, which bypasses modern declarative React lifecycle management and garbage collection.

What changes do you think we should make in order to solve the problem?

  1. Refactor counting into a pure helper: Keep getUnreadReportsForUnreadIndicator in src/libs/UnreadIndicatorUpdater/index.ts (or export from a dedicated utility) as a pure function accepting all necessary parameters (reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived, currentUserLogin, currentUserAccountID, conciergeReportID).

  2. Create <UnreadIndicatorHandler /> component: Create src/components/UnreadIndicatorHandler/index.tsx:

    • Use useOnyx to subscribe declaratively to:
      • ONYXKEYS.COLLECTION.REPORT
      • ONYXKEYS.SESSION
      • ONYXKEYS.CONCIERGE_REPORT_ID
      • ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS
      • ONYXKEYS.COLLECTION.REPORT_ACTIONS
      • ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT
      • ONYXKEYS.DERIVED.REPORT_ATTRIBUTES
    • Read currentReportID reactively using useCurrentReportIDState().
    • Calculate unread reports using useMemo (or standard React Compiler auto-memoization):
      const unreadReports = useMemo(() => {
          return getUnreadReportsForUnreadIndicator(
              reports,
              currentReportID,
              draftComment,
              reportNameValuePairs,
              reportActions,
              reportAttributesDerived?.reports,
              currentUserLogin,
              currentUserAccountID,
              conciergeReportID,
          );
      }, [reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived, currentUserLogin, currentUserAccountID, conciergeReportID]);
      
    • In a useEffect triggered by unreadReports:
      useEffect(() => {
          updateUnread(
              unreadReports.length,
              unreadReports.map((report) => report?.reportID).filter((id): id is string => !!id),
          );
      }, [unreadReports]);
      
    • Component returns null.
  3. Android Platform No-op: Implement src/components/UnreadIndicatorHandler/index.android.tsx returning null with no Onyx subscriptions, preserving the current zero-overhead behavior of load.android.ts.

  4. Mount Handler & Clean Up Legacy Subscriptions:

    • Mount <UnreadIndicatorHandler /> in src/Expensify.tsx alongside other application-level handlers.
    • Remove loadUnreadIndicatorUpdater from src/SplashScreenStateContext.tsx and delete src/libs/UnreadIndicatorUpdater/load.ts and load.android.ts.
    • Remove module-level Onyx.connectWithoutView, memoize, and triggerUnreadUpdate from src/libs/UnreadIndicatorUpdater/index.ts.

What alternative solutions did you explore? (Optional)

  • Adding LRU eviction or clearing memoize cache manually: Rejected because custom caching outside React retains boilerplate and misses out on automatic React 19 / React Compiler dependency tracking and garbage collection.

What automated tests can you add to prevent this from re-occurring?

  • Add unit test coverage in tests/unit/UnreadIndicatorHandlerTest.tsx verifying:
    1. updateUnread is called with the correct unread count and report IDs when reports or active report changes.
    2. Multiple rapid report updates correctly recalculate without memory retention or redundant updates.
  • Verify existing tests in tests/unit/UnreadIndicatorUpdaterTest.ts pass with the pure function extraction.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b60d704ba377be83

camesenin avatar Nov 03 '26 22:11 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 03 '26 22:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

The unread indicator (browser tab title on Web and app icon badge on iOS) updates its count after every report change. Currently, it runs as a plain module outside React in src/libs/UnreadIndicatorUpdater/index.ts using Onyx.connectWithoutView module subscriptions and caches calculations with memoize. Because every report update creates a new immutable collection reference, memoize never hits the cache, accumulates past object references indefinitely, and compares the new copy against every prior copy. For accounts with many reports, memory consumption grows and each report update progressively slows down over a session (from ~26ms to 187ms+ per check).

What is the root cause of that problem?

  1. In src/libs/UnreadIndicatorUpdater/index.ts:
    • Line 131 wraps getUnreadReportsForUnreadIndicator with memoize(..., {maxArgs: 3}). memoize stores past argument combinations without evicting old entries. Since allReports is an OnyxCollection<Report> that receives a new reference on every Onyx mutation, every invocation is a cache miss that adds yet another reference to the cache map.
    • Over a user session with 200+ report mutations, this causes linear comparison overhead and uncollected memory accumulation.
  2. Relying on module-level variables (allReports, allReportActions, allReportNameValuePairs, currentUserAccountID, conciergeReportID) outside the React component lifecycle requires imperative debouncing (debounce(triggerUnreadUpdate, 200)), manual AppStateMonitor listeners, and manual navigationRef listeners.

What changes do you think we should make in order to solve the problem?

  1. Extract Pure Calculation Logic into src/libs/UnreadIndicatorUtils.ts:

    • Move the counting logic from src/libs/UnreadIndicatorUpdater/index.ts into a pure function calculateUnreadReportsCount(...) in src/libs/UnreadIndicatorUtils.ts.
    • Remove the custom memoize wrapper entirely.
  2. Create Headless Component src/components/UnreadIndicatorUpdater.tsx:

    • Create a headless React component that returns null and reads data reactively using useOnyx:
    import React, {useEffect, useMemo} from 'react';
    import useOnyx from '@hooks/useOnyx';
    import ONYXKEYS from '@src/ONYXKEYS';
    import calculateUnreadReportsCount from '@libs/UnreadIndicatorUtils';
    import updateUnread from '@libs/UnreadIndicatorUpdater/updateUnread';
    
    function UnreadIndicatorUpdater() {
        const [reports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
        const [reportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
        const [reportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
        const [session] = useOnyx(ONYXKEYS.SESSION);
        const [conciergeReportID] = useOnyx(ONYXKEYS.CONCIERGE_REPORT_ID);
        const [reportAttributes] = useOnyx(ONYXKEYS.DERIVED.REPORT_ATTRIBUTES);
    
        const unreadCount = useMemo(() => {
            return calculateUnreadReportsCount({
                reports,
                reportActions,
                reportNameValuePairs,
                reportAttributes,
                currentUserAccountID: session?.accountID,
                currentUserLogin: session?.email,
                conciergeReportID,
            });
        }, [reports, reportActions, reportNameValuePairs, reportAttributes, session?.accountID, session?.email, conciergeReportID]);
    
        useEffect(() => {
            updateUnread(unreadCount);
        }, [unreadCount]);
    
        return null;
    }
    
    export default UnreadIndicatorUpdater;
    
    • React Compiler / useMemo naturally caches the calculation and only re-computes when its actual input collections update. No old collection copies are retained, completely eliminating the memory leak and the progressive slow-down.
  3. Mount in src/App.tsx (or src/setup/index.tsx):

    • Mount <UnreadIndicatorUpdater /> alongside other top-level reactive subscribers (e.g. ActiveWorkspace, ThemeScript).
    • Clean up src/libs/UnreadIndicatorUpdater/index.ts: remove all Onyx.connectWithoutView calls, the debounce wrapper, and the navigation/AppState listeners.

What alternative solutions did you explore? (Optional)

  • Setting maxArgs: 1 or clearing memoize cache manually: Rejected because module-level state outside React still requires manual debounce and lifecycle listeners, which go against modern NewDot architectural patterns favoring declarative useOnyx subscriptions.

What automated tests can you add to prevent this from re-occurring?

  1. In tests/unit/UnreadIndicatorUtilsTest.ts:
    • Verify calculateUnreadReportsCount accurately tallies unread reports across different combinations of reports, actions, and user roles.
    • Verify that unread counts are zero when all reports are marked read.
  2. In tests/unit/components/UnreadIndicatorUpdaterTest.tsx:
    • Verify that mounting UnreadIndicatorUpdater triggers updateUnread with the calculated unread count.
    • Verify that updating an unrelated Onyx key does not trigger unnecessary calls to updateUnread.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~015b34e130d9aad41d

sumit-2007-git avatar Nov 04 '26 00:11 sumit-2007-git

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 04 '26 00:11 melvin-bot[bot]

Proposal — Unread Indicator Performance and Lifecycle Correctness

Issue: [Expensify/App #105827](https://github.com/Expensify/App/issues/105827) Related implementation: [PR #104568](https://github.com/Expensify/App/pull/104568) Contributor: Himanshu Shukla GitHub: [himanshu051116](https://github.com/himanshu051116) Engineering portfolio: [Inside the Builder's Mind](https://github.com/himanshu051116/inside-the-builders-mind)

1. Please re-state the problem that we are trying to solve in this issue.

The unread indicator progressively increases the cost of report updates during long-running sessions, particularly for accounts containing thousands of reports.

The existing implementation uses module-level Onyx subscriptions and an unbounded memoization cache. Because report updates produce new collection references, cached results are rarely reused, while historical references continue accumulating.

PR #104568 addresses this architectural problem by moving the calculation into a React component using useOnyx.

My proposed contribution complements that implementation by addressing potential correctness regressions involving network transitions, application lifecycle events, Concierge-driven refreshes, and callback cleanup.

The objective is to preserve the performance improvement without changing the observable behavior of unread indicators on supported platforms.

2. What is the root cause of the problem?

There are two related concerns.

A. Original performance bottleneck

  • The custom memoization cache retains historical report collections.
  • New collection references produce repeated cache misses.
  • Cache comparisons and retained memory grow over the session.
  • Imperative subscriptions require additional coordination outside React.

B. Potential regressions in the React-based replacement

After reviewing PR #104568, I identified the following areas requiring additional validation:

  1. Non-reactive network dependency: The calculation reads getIsOffline() without explicitly tracking network status as a React dependency. Changes in connectivity can affect transaction-thread resolution without necessarily invalidating the cached result.

  2. Foreground refresh semantics: The foreground listener republishes previously calculated report IDs instead of recomputing the current unread state.

  3. Callback lifecycle: The registered Concierge refresh callback is not explicitly cleared during component teardown, potentially retaining a stale closure.

  4. Insufficient regression coverage: Existing tests establish basic unread-count changes but do not comprehensively exercise these lifecycle and connectivity scenarios.

These findings represent source-level risks that should be confirmed through targeted tests.

3. What changes do you propose?

I recommend retaining the core architecture of PR #104568 and introducing a focused follow-up improvement.

A. Make network state explicit

Use the existing reactive network hook and pass the offline state directly to the unread calculation. This makes the dependency visible to React and testable independently.

B. Preserve on-demand refresh behavior

Implement a controlled refresh mechanism that recomputes unread eligibility using the latest committed inputs when the application becomes active or Concierge requests a fresh snapshot.

Avoid unnecessary resubscription to application lifecycle events after routine report updates.

C. Ensure complete lifecycle cleanup

Unsubscribe foreground listeners and clear any registered callback during unmount, preventing stale component references from being retained.

D. Expand automated regression testing

Add targeted coverage for:

  • Network state transitions affecting unread eligibility.
  • Foreground refreshes without an intervening Onyx update.
  • Concierge-triggered unread refreshes.
  • Listener stability across repeated report updates.
  • Callback cleanup after unmount.
  • Existing unread-to-read transitions.

E. Verify performance and cross-platform compatibility

Run the existing performance benchmark with a high-volume test account and validate the behavior on web, iOS, Android, and offline/reconnect scenarios.

The original reported benchmark and the proposed improvements should be measured separately to avoid attributing unverified performance gains to this follow-up.

4. What alternative solutions did you consider?

Limiting the custom memoization cache: This may reduce memory growth but retains unnecessary cache management and does not address the underlying imperative architecture.

Removing all refresh callbacks: This simplifies the component but risks losing explicit refresh behavior required by foreground and Concierge workflows.

Using cached IDs for every refresh: This avoids recomputation but may fail to reflect mutable inputs that change independently of Onyx collection references.

Submitting a duplicate implementation: Since PR #104568 already addresses the primary performance defect, a duplicate would provide limited value. A targeted review and coordinated follow-up is the more maintainable approach.

5. Expected outcome

The proposed changes aim to achieve three outcomes:

  • Preserve the bounded computation behavior introduced by the React-based implementation.
  • Maintain consistent unread indicator behavior across connectivity, navigation, and application lifecycle transitions.
  • Improve maintainability through explicit dependencies, reliable cleanup, and reproducible regression tests.

6. Implementation and verification status

A focused follow-up patch and supporting test harness have been prepared against the inspected PR revision.

Patch application and syntax-level checks have been performed. Full-repository Jest, TypeScript, lint, device testing, and production performance validation remain outstanding.

I would be happy to coordinate with the existing PR author and reviewer before proposing upstream changes.

Contributor details

GitHub: https://github.com/himanshu051116 Portfolio: https://github.com/himanshu051116/inside-the-builders-mind Expensify account email: [[email protected]](mailto:[email protected]) Upwork profile: https://www.upwork.com/freelancers/~012dd17e6db13358c4?mp_source=share

himanshu051116 avatar Nov 04 '26 14:11 himanshu051116

📣 @himanshu051116! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 04 '26 14:11 melvin-bot[bot]

⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.

melvin-bot[bot] avatar Nov 04 '26 14:11 melvin-bot[bot]

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~012dd17e6db13358c4?mp_source=share

himanshu051116 avatar Nov 04 '26 14:11 himanshu051116

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 04 '26 14:11 melvin-bot[bot]

@elirangoshen Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Nov 06 '26 21:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue

The unread indicator (web tab title / iOS app badge) recalculates after every report update via src/libs/UnreadIndicatorUpdater/index.ts, which runs outside React using module-level Onyx.connectWithoutView subscriptions. Each Onyx report update produces a new object reference for the allReports collection, so the memoize cache around the counting function never hits and grows without bound — keeping every previous reports object reference in memory forever and scanning the whole history on every lookup. Over a long session the per-update cost climbs linearly (benchmark: ~26 ms → 187 ms after 200 updates on a 4,061-report account).

What is the root cause of that problem?

Two compounding defects, both in src/libs/UnreadIndicatorUpdater/index.ts:

1. Unbounded memoize cache (line 133) — the memory leak and linear slowdown

// src/libs/UnreadIndicatorUpdater/index.ts:133
const memoizedGetUnreadReportsForUnreadIndicator = memoize(getUnreadReportsForUnreadIndicator, {maxArgs: 3});

Only maxArgs: 3 is passed; no maxSize is supplied. The memoize default is maxSize: Infinity (src/libs/memoize/const.ts:5) and the default equality comparator is deepEqual (src/libs/memoize/const.ts:7). The cache is ArrayCache (src/libs/memoize/cache/ArrayCache.ts), whose getKeyIndex (lines 22–28) walks the array backward comparing every stored key with deepEqual until it finds a match:

// src/libs/memoize/cache/ArrayCache.ts:22-28
function getKeyIndex(key: K): number {
    for (let i = cache.length - 1; i >= 0; i--) {
        const cacheItem = cache.at(i)?.at(0);
        if (cacheItem && keyComparator(cacheItem as K, key)) {
            return i;
        }
    }
    return -1;
}

Because allReports (the first memoization arg) is an OnyxCollection<Report> whose reference identity changes on every Onyx write, deepEqual against each prior copy always fails → every update is a miss → a new [key, value] entry is pushed (ArrayCache.set, line 38) and the cache never shrinks (maxSize === Infinity, so the cache.shift() at line 44 never runs). So over a session: cache.length grows by 1 per update, getKeyIndex does an O(n) deepEqual scan over an ever-growing array of large report maps on every call → the observed linear slowdown (26 ms → 187 ms + memory bloat). The prior proposals correctly identify memoize but none traces the full mechanism: it is maxSize: Infinity (const.ts:5) × deepEqual default (const.ts:7) × ArrayCache.getKeyIndex linear backward scan (ArrayCache.ts:22-28) × new-reference-per-update = O(n²) total work.

2. Hidden correctness bug: the memoized function reads module-level state that is not in its cache key (lines 97–129)

Even though memoize is called with {maxArgs: 3}, the function body reads allReportNameValuePairs (line 97), allReportActions (line 100), reportAttributesDerived (lines 103–104), currentUserLogin (line 122), currentUserAccountID (line 123), and conciergeReportID (line 126) directly from module scope — none of which are part of the 3-arg cache key. So a stale cached entry could be returned if only the currentReportID/draftComment args repeat while these module globals changed. This is why the issue asks to make the function pure: threading all inputs as args (so useMemo's dependency array is correct) is required, not optional — a memoize maxSize cap alone would preserve this latent stale-return bug.

What changes do you think we should make in order to solve the problem?

Follow the issue's prescribed direction: move the logic onto a headless React component reading useOnyx, so React Compiler memoizes the count and only recomputes when its inputs actually change.

  1. Extract getUnreadReportsForUnreadIndicator as a pure function (src/libs/UnreadIndicatorUpdater/index.ts or a sibling getUnreadReportsForUnreadIndicator.ts): take all data as explicit arguments — reports, currentReportID, draftComment, reportNameValuePairs, reportActions, reportAttributesDerived, currentUserLogin, currentUserAccountID, conciergeReportID. Remove the module-level closures (lines 20–75) and the direct getIsOffline() read at line 79 — pass isOffline in too (cited as a correctness gap by a prior proposal; agree it should be reactive). This removes latent staleness from root-cause #2.

  2. Create src/components/UnreadIndicatorHandler/index.tsx — renders null, subscribes via useOnyx to the 7 keys currently held in module scope (ONYXKEYS.COLLECTION.REPORT, ONYXKEYS.SESSION, ONYXKEYS.CONCIERGE_REPORT_ID, ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS, ONYXKEYS.COLLECTION.REPORT_ACTIONS, ONYXKEYS.COLLECTION.REPORT_DRAFT_COMMENT, ONYXKEYS.DERIVED.REPORT_ATTRIBUTES), reads currentReportID + isOffline reactively, computes unreadReports in useMemo, and calls updateUnread(unreadReports.length, unreadReportIDs) in a useEffect. React Compiler auto-memoizes; no custom cache, no retained old copies, no O(n) scan. Provide index.android.tsx returning null to preserve the existing load.android.ts zero-overhead-on-Android behavior (updateUnread is a no-op on Android).

  3. Mount <UnreadIndicatorHandler /> in src/Expensify.tsx next to <PriorityModeHandler />, inside CurrentReportIDContextProvider so useCurrentReportIDState reacts to chat switches.

  4. Remove the legacy wiring: delete memoize (line 133), the debounce(triggerUnreadUpdate, ...) (lines 140–150), setUnreadUpdateCallback (line 152), the report collection connectWithoutView (lines 155–161), navigationRef.addListener('state', …) (lines 163–165), AppStateMonitor.addBecameActiveListener (lines 168–170), and src/libs/UnreadIndicatorUpdater/load.ts + load.android.ts; remove loadUnreadIndicatorUpdater from src/SplashScreenStateContext.tsx.

Why this beats a minimal maxSize fix: capping maxSize would stop the unbounded growth (root cause #1) but leaves root-cause #2 (stale returns from undocumented side-reads) and keeps the imperative, non-reactive architecture the issue explicitly asks to retire.

What specific scenarios should be covered by automated tests?

  • tests/unit/UnreadIndicatorHandlerTest.tsx:
    1. updateUnread receives the correct count + reportIDs when reports change.
    2. Updating an unrelated Onyx key does not recompute / re-call updateUnread.
    3. Switching currentReportID updates the count (draft on the open report no longer counts).
    4. Repeated rapid updates do not accumulate retained references (assert no growth in Onyx connection count).
  • tests/unit/UnreadIndicatorUpdaterTest.ts (existing): pure-function extraction keeps read → unread, mute → excluded, hidden → excluded behavior.
  • Performance: extend the existing benchmark to assert the per-update unread cost stays flat across 200 updates.

What alternative solutions did you explore? (Optional)

  • Cap memoize maxSize, e.g. {maxArgs: 3, maxSize: 1}. Stops the leak but keeps the imperative module subscriptions, the debounce, and the side-read staleness bug (#2). The issue explicitly asks for the useOnyx migration, so this is a smaller fix than requested.
  • Switch the equality comparator to shallow. Reference identity of the top-level collection object still changes per update, so this does not change cache-miss behavior; it would just make a hit (if it ever occurred) cheaper. Does not address growth.

PR

PR will be linked here once created.

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01b6a593fd295a20bf

vanshshah11 avatar Nov 07 '26 00:11 vanshshah11

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 07 '26 00:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

Over the course of a long app session, report updates get progressively slower and retain more memory because the unread indicator updater relies on Onyx.connectWithoutView and an ineffective memoize wrapper over allReports.

What is the root cause of that problem?

In src/libs/UnreadIndicatorUpdater/index.ts (lines 20–131):

  1. getUnreadReportsForUnreadIndicator is wrapped in memoize(..., {monitoringName: 'getUnreadReportsForUnreadIndicator', maxArgs: 3}). Because allReports (OnyxCollection<Report>) receives a new top-level object reference on every single report update in Onyx, the memoization cache misses on nearly every call while retaining references to previous allReports collections in memory.
  2. The module uses Onyx.connectWithoutView (deprecated in favor of useOnyx) to maintain module-level allReports, currentReportID, and notificationPreference state and runs triggerUnreadUpdate imperatively on every Onyx update.

What changes do you think we should make in order to solve the problem?

  1. In src/libs/UnreadIndicatorUpdater/index.ts:
    • Remove the memoize wrapper around getUnreadReportsForUnreadIndicator and make getUnreadReportsForUnreadIndicator(allReports, currentReportID, allReportNameValuePairs) a pure function.
    • Remove the Onyx.connectWithoutView subscriptions and module-level mutable state (allReports, allReportNameValuePairs).
  2. Create a hook useUnreadIndicatorUpdater in src/libs/UnreadIndicatorUpdater/useUnreadIndicatorUpdater.ts (or a lightweight headless component mounted in src/Expensify.tsx / NavigationRoot.tsx) that uses useOnyx(ONYXKEYS.COLLECTION.REPORT) and useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS) (or a combined selector calculating the unread count directly inside the useOnyx selector) and calls updateUnread(totalCount) inside a useEffect whenever the unread count or current report ID changes.
  3. Update src/libs/Navigation/NavigationRoot.tsx and tests/unit/UnreadIndicatorUpdaterTest.ts to test getUnreadReportsForUnreadIndicator and the new useOnyx-based updater without Onyx.connectWithoutView.

What alternative solutions did you explore? (Optional)

We considered reducing the cache size of memoize to 1, but computing the unread count inside a useOnyx selector eliminates both the memoize overhead and the deprecated Onyx.connectWithoutView listeners.

jeffrey-graham avatar Nov 07 '26 04:11 jeffrey-graham

📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 04:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

The unread indicator updater becomes progressively slower over a user session because UnreadIndicatorUpdater runs outside React using Onyx.connectWithoutView with a broken module-level memoize cache.

What is the root cause of that problem?

In src/libs/UnreadIndicatorUpdater.ts:

  1. UnreadIndicatorUpdater listens to ONYXKEYS.COLLECTION.REPORT via Onyx.connectWithoutView. On every single report update, Onyx emits a new reference for the entire reports collection object.
  2. The module's memoize cache compares the collection by reference (===), so the cache never matches. As a result, UnreadIndicatorUpdater recalculates unread counts across all user reports on every keystroke, draft update, and message receipt, causing CPU thrashing and gradual UI degradation over prolonged sessions.

What changes do you think we should make in order to solve the problem?

  1. Refactor UnreadIndicatorUpdater to migrate from connectWithoutView to React context or a dedicated subscriber component using useOnyx with selective selector hooks.
  2. Alternatively, in UnreadIndicatorUpdater.ts:
    • Instead of recomputing all reports on every Onyx notification, maintain an incremental unread counter map keyed by reportID.
    • Only recalculate the delta when an individual report's hasUnread or lastReadTime actually changes, rather than iterating over the entire reports dictionary on every unrelated write.

What alternative solutions did you explore? (Optional)

Deep-comparing the entire reports collection on every update, but deep object comparison across hundreds of reports introduces even more CPU overhead compared to incremental delta tracking.

TassioSales avatar Nov 08 '26 01:11 TassioSales

@elirangoshen 6 days overdue. This is scarier than being forced to listen to Vogon poetry!

melvin-bot[bot] avatar Nov 10 '26 21:11 melvin-bot[bot]