Skip to content

Fix cache key eviction #629

Merged
mountiny merged 23 commits intoExpensify:mainfrom
callstack-internal:test-for-keys-eviction-implementation
Apr 28, 2025
Merged

Fix cache key eviction #629
mountiny merged 23 commits intoExpensify:mainfrom
callstack-internal:test-for-keys-eviction-implementation

Conversation

@kubabutkiewicz
Copy link
Copy Markdown
Contributor

@kubabutkiewicz kubabutkiewicz commented Apr 16, 2025

Details

This PR renames safeEvictionKeys to evictableKeys throughout the codebase for clearer naming that better reflects the parameter's purpose. It also refactors the key eviction system by:

  • Moving eviction-related state and functionality from OnyxUtils to OnyxCache
  • Improving the eviction algorithm to only remove keys explicitly marked as evictable
  • Preserving the most recently accessed key during evictions
  • Updating documentation to reflect the changes
    These changes make Onyx's storage management more predictable and maintainable.

Related Issues

Expensify/App#59913

Automated Tests

Added the tests verifying that only keys added to evictableKeys are evicted from cache.

Manual Tests

  1. Verify that we are evicting keys from cache that are added to evictableKeys
  2. Verify that data from LHN is not disappearing during using the app

Author Checklist

  • I linked the correct issue in the ### Related 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 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 / Chrome
    • iOS / native
    • iOS / Safari
    • MacOS / Chrome / Safari
    • MacOS / Desktop
  • 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 the left part of a conditional rendering a React component is a boolean and NOT a string, e.g. myBool && <MyComponent />.
    • 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 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.js 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 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
    • If we are not using the full Onyx data that we loaded, I've added the proper selector in order to ensure the component only re-renders when the data it is using changes
    • 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 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 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 author checklist, including those that don't apply to this PR.

Screenshots/Videos

Android: Native
android.mp4
Android: mWeb Chrome
android-web.mp4
iOS: Native
ios.mp4
iOS: mWeb Safari
MacOS: Chrome / Safari
wev.mp4
MacOS: Desktop
desktop.mp4

…s evicting keys not added to the list of safeEvictionKeys
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 16, 2025

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

CLABotify added a commit to Expensify/CLA that referenced this pull request Apr 17, 2025
@kubabutkiewicz kubabutkiewicz changed the title Unit test for eviction implementation Fix cache key eviction Apr 23, 2025
@kubabutkiewicz kubabutkiewicz marked this pull request as ready for review April 23, 2025 14:46
@kubabutkiewicz kubabutkiewicz requested a review from a team as a code owner April 23, 2025 14:46
@melvin-bot melvin-bot Bot requested review from AndrewGable and removed request for a team April 23, 2025 14:46
@AndrewGable AndrewGable requested review from mountiny and removed request for AndrewGable April 23, 2025 18:10
@AndrewGable
Copy link
Copy Markdown
Contributor

Going to assign @mountiny as they are involved in the original issue!

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

Also waiting for @fabioh8010 review!

Comment thread lib/OnyxCache.ts Outdated
Comment thread lib/OnyxCache.ts
Comment on lines +302 to +310
/**
* Check if a given key matches a pattern key
* @param configKey - Pattern that may contain a wildcard
* @param key - Key to test against the pattern
*/
private isKeyMatch(configKey: OnyxKey, key: OnyxKey): boolean {
const isCollectionKey = configKey.endsWith('_');
return isCollectionKey ? Str.startsWith(key, configKey) : configKey === key;
}
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.

Is this a copy of OnyxUtils.isKeyMatch? Can't we reuse 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.

We cannot import OnyxUtils to OnyxCache as this produces dependency cycle

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.

Let's please extract this to another file that both OnyxUtils and OnyxCache can import, to avoid duplicate code

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.

We could think about splitting up the OnyxUtils file in general, because at the moment it's around ~1500 lines long and there's not that much inter-dependent state between the functions

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.

But maybe let's do that in a follow-up PR 😅

Comment thread lib/OnyxUtils.ts Outdated
Comment thread lib/OnyxCache.ts Outdated
Comment thread tests/unit/cacheEvictionTest.ts Outdated
// When a new connection for a safe eviction key happens
Onyx.connect({key: `${ONYX_KEYS.COLLECTION.MOCK_COLLECTION}10`, callback: jest.fn()});
})
.then(waitForPromisesToResolve)
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.

Same

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.

This is needed as we need to wait till onyx connect resolves to check if its in the cache

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.

This is needed as we need to wait till onyx connect resolves to check if its in the cache

That sounds good to me 👍🏼

Comment thread tests/unit/onyxCacheTest.tsx
@fabioh8010
Copy link
Copy Markdown
Contributor

Also cc @chrispader for visibility

Copy link
Copy Markdown
Contributor

@fabioh8010 fabioh8010 left a comment

Choose a reason for hiding this comment

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

LGTM!

@mountiny
Copy link
Copy Markdown
Contributor

mountiny commented Apr 24, 2025

@kubabutkiewicz can you please provide videos for this PR?

@mountiny mountiny requested a review from jjcoffee April 24, 2025 17:53
@mountiny
Copy link
Copy Markdown
Contributor

@jjcoffee will you be able to do a checklist/ test this change in App please?

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

@mountiny Yeah, I am on it

@jjcoffee
Copy link
Copy Markdown

@mountiny Yessir!

@jjcoffee
Copy link
Copy Markdown

jjcoffee commented Apr 25, 2025

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: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • 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 shown in the product is localized by adding it to src/languages/* files and using the translation method
    • 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 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)
  • 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
  • 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.
  • 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.
  • 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: Native
android-app-2025-04-25_15.04.04.mp4
Android: mWeb Chrome
android-chrome-2025-04-25_15.09.55.mp4
iOS: Native
ios-app-2025-04-25_14.24.18.mp4
iOS: mWeb Safari
ios-safari-2025-04-25_14.28.30.mp4
MacOS: Chrome / Safari
desktop-chrome-2025-04-25_13.49.47.mp4
MacOS: Desktop
desktop-app-2025-04-25_13.55.21.mp4

@jjcoffee

This comment was marked as resolved.

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

@jjcoffee in the App you need to change here https://github.com/Expensify/App/blob/5f5f4a0857a5211dc00b61ea77e93ea5a20bc887/src/setup/index.ts#L31 safeEvictionKeys to evictableKeys

@jjcoffee

This comment was marked as resolved.

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

@jjcoffee No its not, let me check it

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

@jjcoffee Issue fixed

@jjcoffee
Copy link
Copy Markdown

@kubabutkiewicz Nice thanks, tests well now! Are we ignoring the perf test fail?

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

@jjcoffee I think yes based on Fabio comment #629 (comment)

Copy link
Copy Markdown

@jjcoffee jjcoffee left a comment

Choose a reason for hiding this comment

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

LGTM!

@mountiny
Copy link
Copy Markdown
Contributor

@fabioh8010 how can we be sure they failed due to flakiness?

Comment thread tests/perf-test/OnyxUtils.perf-test.ts Outdated
Comment on lines +285 to +286
() => false,
() => Promise.resolve(new Set(Object.keys(data))),
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.

@kubabutkiewicz please move () => false and () => Promise.resolve(new Set(Object.keys(data))) to outside measureAsyncFunction

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.

@fabioh8010 I am not sure what do you mean, something like that?
image

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.

Yeah it's okay this way!

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.

ok thanks, pushed a change

@fabioh8010
Copy link
Copy Markdown
Contributor

@fabioh8010 how can we be sure they failed due to flakiness?

Let's wait for Kuba to address the last comment and I will manually analyse the next Reassure run

@fabioh8010
Copy link
Copy Markdown
Contributor

@mountiny @kubabutkiewicz

Reassure output of significant changes:

 - Onyx update one call with 5k sets and 5k merges updates [async function]: 397.0 ms → 432.0 ms (+35.0 ms, +8.8%) 🔴 | 1 → 1 
 - OnyxUtils remove 10k calls [async function]: 170.2 ms → 179.7 ms (+9.5 ms, +5.6%) 🔴 | 1 → 1 
 - OnyxUtils scheduleNotifyCollectionSubscribers one call with 10k heavy objects to update 10k subscribers [async function]: 80.9 ms → 87.3 ms (+6.4 ms, +7.9%) 🔴 | 1 → 1 
 - OnyxUtils keyChanged one call with one heavy object to update 10k subscribers [function]: 36.4 ms → 41.0 ms (+4.6 ms, +12.6%) 🔴 | 1 → 1 
 - Onyx clear one call with 10k records to clean [async function]: 25.4 ms → 27.8 ms (+2.4 ms, +9.3%) 🔴 | 1 → 1 
 - OnyxCache removeLeastRecentlyUsedKeys one call removing 1000 keys [function]: 0.2 ms → 1.6 ms (+1.4 ms, +729.1%) 🔴🔴 | 1 → 1 
 - OnyxUtils multiGet one call getting 10k heavy objects from cache [async function]: 5.6 ms → 6.7 ms (+1.1 ms, +19.5%) 🔴 | 1 → 1 
 - OnyxUtils updateSnapshots one call with 100 updates [async function]: 6.5 ms → 7.6 ms (+1.1 ms, +16.6%) 🔴 | 1 → 1 
 - OnyxUtils tryGetCachedValue one call passing collection key without selector [function]: 6.0 ms → 7.1 ms (+1.1 ms, +17.7%) 🔴 | 1 → 1 
 - OnyxUtils getCachedCollection one call retrieving a collection with 5k heavy objects [function]: 4.6 ms → 5.6 ms (+1.0 ms, +22.8%) 🔴 | 1 → 1 
 - OnyxConnectionManager disconnectAll one call disconnecting 10k connections [function]: 3.7 ms → 4.4 ms (+0.8 ms, +20.5%) 🔴 | 1 → 1 
 - OnyxCache addToAccessedKeys one call adding one key [function]: 0.0 ms → 0.0 ms (+0.0 ms, +71.4%) 🔴🔴 | 1 → 1 
 - OnyxCache get one call getting one key among 10k ones [function]: 0.0 ms → 0.0 ms (+0.0 ms, +28.4%) 🔴 | 1 → 1 
 - OnyxCache set one call setting one key [function]: 0.0 ms → 0.0 ms (+0.0 ms, +18.0%) 🔴 | 1 → 1 
 - OnyxCache setRecentKeysLimit one call [function]: 0.0 ms → 0.0 ms (+0.0 ms, +11.4%) 🔴 | 1 → 1 
 - OnyxUtils hasPendingMergeForKey one call to look through 10k pending merges [function]: 0.0 ms → 0.0 ms (+0.0 ms, +37.4%) 🔴🔴 | 1 → 1 
 - OnyxUtils isSafeEvictionKey one call checking one key [function]: 0.0 ms → 0.0 ms (+0.0 ms, +105.5%) 🔴🔴 | 1 → 1 
 - OnyxCache addNullishStorageKey one call adding one key [function]: 0.0 ms → 0.0 ms (+0.0 ms, +10.2%) 🔴 | 1 → 1 
 - OnyxUtils sendActionToDevTools one call [function]: 0.0 ms → 0.0 ms (+0.0 ms, +55.5%) 🔴🔴 | 1 → 1 
 - OnyxUtils getMergeQueuePromise one call [function]: 0.0 ms → 0.0 ms (+0.0 ms, +56.1%) 🔴🔴 | 1 → 1 
 - OnyxUtils getDefaultKeyStates one call [function]: 0.0 ms → 0.0 ms (+0.0 ms, +72.8%) 🔴🔴 | 1 → 1 
 - OnyxUtils isCollectionMemberKey one call with correct key [function]: 0.0 ms → 0.0 ms (+0.0 ms, +34.1%) 🔴🔴 | 1 → 1 
 - OnyxUtils getSkippableCollectionMemberIDs one call [function]: 0.0 ms → 0.0 ms (+0.0 ms, +56.7%) 🔴🔴 | 1 → 1 
 - OnyxUtils getEvictionBlocklist one call [function]: 0.0 ms → 0.0 ms (+0.0 ms, +54.3%) 🔴🔴 | 1 → 1 
 - OnyxUtils splitCollectionMemberKey one call passing the collection key [function]: 0.0 ms → 0.0 ms (+0.0 ms, +24.0%) 🔴 | 1 → 1 

This one seems to be the only one "significant" related to the PR

 - OnyxCache removeLeastRecentlyUsedKeys one call removing 1000 keys [function]: 0.2 ms → 1.6 ms (+1.4 ms, +729.1%) 🔴🔴 | 1 → 1 

Still, I don't think a +1.4 ms deviation is something to worry about.

BTW, I'm working on a improvement for Reasure workflow measurements here.

@fabioh8010
Copy link
Copy Markdown
Contributor

@kubabutkiewicz Could you merge this again with main? The Reassure flakiness improvements PR was merged, let's see in action.

@kubabutkiewicz
Copy link
Copy Markdown
Contributor Author

@fabioh8010 Done 😄

Copy link
Copy Markdown
Contributor

@mountiny mountiny left a comment

Choose a reason for hiding this comment

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

Thanks, looks nice and clean! One question just to make sure we dont miss anything

Comment thread README.md
```js
Onyx.init({
safeEvictionKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS],
evictableKeys: [ONYXKEYS.COLLECTION.REPORT_ACTIONS],
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.

Will this require any migration?

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.

The only thing we need to do is just change the parameter name in the app. I am also thinking we should add more keys in the App which are evictable. Like NYXKEYS.COLLECTION.REPORT_ACTIONS_DRAFTS, ONYXKEYS.COLLECTION.REPORT_ACTIONS_PAGES, ONYXKEYS.COLLECTION.REPORT_ACTIONS_REACTIONS tested it already and there seems to not be any disadvantages

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.

Ok thanks, feel free to work on the bump PR

@mountiny mountiny merged commit 20f9c12 into Expensify:main Apr 28, 2025
5 checks passed
@os-botify
Copy link
Copy Markdown
Contributor

os-botify Bot commented Apr 28, 2025

🚀 Published to npm in 2.0.104 🎉

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.

6 participants