Skip to content

Reuse unchanged derived values and skip no-op derived writes - #76

Merged
sosek108 merged 5 commits into
feature/onyx-store-pr-5-recutfrom
fix/onyx-117-derived-ref-reuse
Oct 9, 2026
Merged

sosek108 merged 5 commits into
feature/onyx-store-pr-5-recutfrom
fix/onyx-117-derived-ref-reuse

Conversation

@sosek108

@sosek108 sosek108 commented Oct 6, 2026

Copy link
Copy Markdown

Explanation of Change

This targets the Onyx 3.0.117 bump in Expensify#98956.

On 3.0.117, useOnyx without a selector compares by reference only. Before, a top-level shallowEqual kept an equal new value at the old reference. OnyxDerived writes with skipCacheCheck, and GUIDE_ACCOUNT_IDS and LOGIN_TO_ACCOUNT_ID_MAP build a new array or map on every PERSONAL_DETAILS_LIST write. So after the bump, every personal-details write re-renders all 10 consumers of these keys, even when nothing they use has changed. In useSidebarOrderedReports it is worse: the new reference looks like guides being loaded, so the LHN re-checks every report.

The two configs now return the current value when the new result is shallow-equal to it. The engine skips the write when compute returns the value it already holds, so a no-op recompute no longer notifies subscribers or rewrites the whole value to disk. That applies to every derived key, and every config already copies before changing anything, so a real update is never skipped.

Reassure, 10 renames of a user who is in none of the reports or rows, compared with main on 3.0.115:

  • LHN with 500 reports: 147 ms on main, 215 ms on the bump, 104 ms with this fix.
  • 50 Search rows with attendees: 23 ms on main, 172 ms on the bump, 22 ms with this fix.

The full Reassure suite shows no regression from this fix. Two regressions come from the bump itself and are not addressed here: getReportsToDisplayInLHN on 15k reports is about 30% slower, and MoneyRequestReportActionsList renders once more when a transaction on an unrelated report changes.

Fixed Issues

$ Expensify#98956
PROPOSAL:

Tests

  1. Sign in to an account in a domain that has an Expensify guide, or with an #admins room that includes a setup specialist.
  2. Verify the domain room appears in the LHN and opens without a "not found" page.
  3. Clear the cache and sign in again. Verify the domain room still appears once the guide's personal details load.
  4. Close and reopen the app. Verify the domain room is still there.
  5. With the LHN open, rename a contact you have a chat with. Verify the LHN row and the report header show the new name.
  6. Use a workspace category with attendee tracking. Create an expense and add an attendee by email for a user who doesn't have an account yet.
  7. Verify the attendee avatar shows on the confirmation page, then in the expense view after it is submitted, and in the attendees column on the Search page.
  8. Sign out and sign in as a different user. Verify no domain rooms or attendee avatars from the previous account appear.
  • Verify that no errors appear in the JS console

Offline tests

  1. Go offline.
  2. Add an attendee by email to an expense and rename a contact.
  3. Verify the attendee avatar and the new name show while offline.
  4. Go back online. Verify both stay correct after the server responds.

QA Steps

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 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 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)
  • 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 the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • 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

@sosek108

sosek108 commented Oct 6, 2026

Copy link
Copy Markdown
Author

One test from the analysis is not in this PR: tests/unit/useSidebarOrderedReportsGuideRecomputeTest.tsx.

It renders useSidebarOrderedReports with 50 reports, then writes GUIDE_ACCOUNT_IDS again with the same content and skipCacheCheck: true, which copies what the derived engine used to do after every personal-details write. It asserts that the LHN doesn't re-check every report.

Results:

So it showed the problem, but it can't confirm the fix. SidebarLinksPersonalDetailsWrites.perf-test.tsx covers the LHN end to end with the real engine instead: 147 ms on main, 215 ms on Expensify#98956, 104 ms with this fix. The existing test "should not recompute all reports when the guide accountIDs are recomputed to the same set" in useSidebarOrderedReportsTest.tsx doesn't catch this either, because it writes without skipCacheCheck and uses only one report.

If we want the hook itself to tolerate a fresh but equal guide list, the guideAccountIDs !== prevGuideAccountIDs check in useSidebarOrderedReports would need to compare contents. That would be a separate change.

Test source
import {act, renderHook} from '@testing-library/react-native';

import OnyxListItemProvider from '@components/OnyxListItemProvider';

import {CurrentReportIDContextProvider} from '@hooks/useCurrentReportID';
import {SidebarOrderedReportsContextProvider, useSidebarOrderedReports} from '@hooks/useSidebarOrderedReports';

import SidebarUtils from '@libs/SidebarUtils';

import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Report} from '@src/types/onyx';

import type {OnyxMultiSetInput} from 'react-native-onyx';

import React from 'react';
import Onyx from 'react-native-onyx';

import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct';

jest.mock('@libs/SidebarUtils', () => ({
    sortReportsToDisplayInLHN: jest.fn(),
    getReportsToDisplayInLHN: jest.fn(),
    updateReportsToDisplayInLHN: jest.fn(),
    filterReportsForInboxTab: jest.fn((reportIDs: string[]) => reportIDs),
    getInboxTabSummary: jest.fn(() => ({counts: {}, hasStaleUnreadReport: false})),
}));
jest.mock('@libs/Navigation/Navigation', () => ({
    getActiveRouteWithoutParams: jest.fn(() => ''),
    isNavigationReady: jest.fn(() => Promise.resolve()),
    getTopmostReportId: jest.fn(),
}));
jest.mock('@libs/ReportUtils', () => ({
    parseReportRouteParams: jest.fn(() => ({reportID: undefined})),
    getReportIDFromLink: jest.fn(() => ''),
}));

const mockSidebarUtils = jest.mocked(SidebarUtils);

const GUIDE_ACCOUNT_ID = 8;
const REPORT_COUNT = 50;

function buildReports(): Record<string, Report> {
    const reports: Record<string, Report> = {};
    for (let i = 1; i <= REPORT_COUNT; i++) {
        reports[`${ONYXKEYS.COLLECTION.REPORT}${i}`] = {
            reportID: String(i),
            reportName: `Chat ${i}`,
            lastVisibleActionCreated: '2024-01-01 10:00:00',
            type: CONST.REPORT.TYPE.CHAT,
        };
    }
    return reports;
}

function TestWrapper({children}: {children: React.ReactNode}) {
    return (
        <OnyxListItemProvider>
            <CurrentReportIDContextProvider>
                <SidebarOrderedReportsContextProvider>{children}</SidebarOrderedReportsContextProvider>
            </CurrentReportIDContextProvider>
        </OnyxListItemProvider>
    );
}

describe('useSidebarOrderedReports on an equal guide accountIDs recompute', () => {
    beforeAll(() => {
        Onyx.init({keys: ONYXKEYS});
    });

    beforeEach(async () => {
        jest.clearAllMocks();
        const reports = buildReports();
        await act(async () => {
            await Onyx.clear();
            await Onyx.set(ONYXKEYS.SESSION, {accountID: 12345, email: 'test@example.com', authTokenType: CONST.AUTH_TOKEN_TYPES.ANONYMOUS});
            await Onyx.multiSet({
                [ONYXKEYS.NVP_PRIORITY_MODE]: CONST.PRIORITY_MODE.DEFAULT,
                [ONYXKEYS.COLLECTION.POLICY]: {},
                [ONYXKEYS.COLLECTION.TRANSACTION]: {},
                [ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS]: {},
                [ONYXKEYS.BETAS]: [],
                [ONYXKEYS.DERIVED.REPORT_ATTRIBUTES]: {reports: {}},
                [ONYXKEYS.DERIVED.GUIDE_ACCOUNT_IDS]: [GUIDE_ACCOUNT_ID],
                ...reports,
            } satisfies OnyxMultiSetInput);
        });
        mockSidebarUtils.getReportsToDisplayInLHN.mockReturnValue(reports);
        mockSidebarUtils.updateReportsToDisplayInLHN.mockImplementation(({displayedReports}) => displayedReports);
        mockSidebarUtils.sortReportsToDisplayInLHN.mockReturnValue([]);
        await waitForBatchedUpdatesWithAct();
    });

    afterAll(async () => {
        await act(async () => {
            await Onyx.clear();
        });
    });

    it('should not re-evaluate every report when the guide accountIDs are rewritten with the same content', async () => {
        // Given the LHN has built its list of reports
        renderHook(() => useSidebarOrderedReports(), {wrapper: TestWrapper});
        await waitForBatchedUpdatesWithAct();
        mockSidebarUtils.updateReportsToDisplayInLHN.mockClear();
        mockSidebarUtils.getReportsToDisplayInLHN.mockClear();

        // When the derived engine flushes after an unrelated personal-details write. It writes a fresh array with
        // skipCacheCheck, exactly like setDerivedValue, so Onyx notifies even though the content is unchanged.
        await act(async () => {
            await Onyx.set(ONYXKEYS.DERIVED.GUIDE_ACCOUNT_IDS, [GUIDE_ACCOUNT_ID], {skipCacheCheck: true});
        });
        await waitForBatchedUpdatesWithAct();

        // Then no call may re-check all reports, the guide-hydration branch is only for a real change of guides
        const reEvaluatedReportCounts = mockSidebarUtils.updateReportsToDisplayInLHN.mock.calls.map(([params]) => params.updatedReportsKeys.length);
        expect(reEvaluatedReportCounts).not.toContain(REPORT_COUNT);
        expect(mockSidebarUtils.getReportsToDisplayInLHN).not.toHaveBeenCalled();
    });
});

@coderabbitai

coderabbitai Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Essentials
  • Run ID: 3a2232a3-bb49-4297-986d-fa96af939530

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Billing warning: we have not been able to collect payment for this subscription for more than 72 hours. Please update the payment method or pay any pending invoices in Billing to avoid service interruption.


Comment @coderabbitai help to get the list of available commands.

@sosek108
sosek108 requested a review from fabioh8010 October 7, 2026 12:56
Comment on lines +149 to +151
if (newDerivedValue === derivedValue) {
return;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

In case we hit this we will still reach the finally block, right?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Yes, finally is ran after return is called.

Confirmed with this simple script

Image

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do we really need this new file? Can't we reuse the existing test files?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do we really need this new file? Can't we reuse the existing test files?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Had to keep this one. Rest files are moved to OnyxDerivedTest

It needs a fresh engine, and OnyxDerivedTest.tsx can't give it one.

The test checks what happens after an app restart, when the derived value is already on disk. The engine reads that saved value only once, when init() starts (src/libs/actions/OnyxDerived/index.ts:59-74). So the test has to save the value to Onyx first and only then call initOnyxDerivedValues().

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do we really need this new file? Can't we reuse the existing test files?

@fabioh8010

Copy link
Copy Markdown
Collaborator

This looks good @sosek108 , once it's ready feel free to merge to my PR!

@sosek108
sosek108 marked this pull request as ready for review October 9, 2026 13:08
@sosek108
sosek108 merged commit 745c909 into feature/onyx-store-pr-5-recut Oct 9, 2026
4 of 25 checks passed
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.

2 participants