Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/OnyxCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -401,12 +401,18 @@ class OnyxCache {
return returnPromise;
}

/** Check if the value has changed. Uses reference equality as a fast path, falls back to deep equality. */
/**
* Check if the value has changed. Uses reference equality as a fast path, then a cheap check of the top-level
* primitive properties (which catches most values that really changed), and falls back to deep equality.
*/
hasValueChanged(key: OnyxKey, value: OnyxValue<OnyxKey>): boolean {
const currentValue = this.storageMap[key];
if (currentValue === value) {
return false;
}
if (utils.hasTopLevelPrimitiveChange(currentValue, value)) {
return true;
}
return !deepEqual(currentValue, value);
}

Expand Down
77 changes: 70 additions & 7 deletions lib/OnyxUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,29 @@ function prepareKeyValuePairsForStorage(
return {pairs, keysToRemove};
}

/**
* Splits prepared key-value pairs into the ones whose value differs from the cached value and the keys whose value is
* deep-equal to it, using the same `cache.hasValueChanged()` check as `setWithRetry`.
*
* Bulk set paths keep the cached object for the unchanged keys instead of replacing it with an equal copy, so
* reference-based consumers (subscribers, derived values, React) see no change for them. Pass the pairs returned by
* `prepareKeyValuePairsForStorage()`, so the comparison uses the value the cache would actually hold (without nested nulls).
*/
function partitionPairsByCacheChange(pairs: StorageKeyValuePair[]): {changedPairs: StorageKeyValuePair[]; unchangedKeys: Set<OnyxKey>} {
const changedPairs: StorageKeyValuePair[] = [];
const unchangedKeys = new Set<OnyxKey>();

for (const pair of pairs) {
if (cache.hasValueChanged(pair[0], pair[1])) {
changedPairs.push(pair);
} else {
unchangedKeys.add(pair[0]);
}
}

return {changedPairs, unchangedKeys};
}

/**
* Merges an array of changes with an existing value or creates a single change.
*
Expand Down Expand Up @@ -1208,13 +1231,22 @@ function multiSetWithRetry(data: OnyxMultiSetInput, retryAttempt?: number): Prom
}
>();

const unchangedKeys = new Set<OnyxKey>();

for (const [key, value] of keyValuePairsToSet) {
// When we use multiSet to set a key we want to clear the current delta changes from Onyx.merge that were queued
// before the value was set. If Onyx.merge is currently reading the old value from storage, it will then not apply the changes.
if (OnyxUtils.hasPendingMergeForKey(key)) {
delete OnyxUtils.getMergeQueue()[key];
}

// Like setWithRetry, a value deep-equal to the cached one keeps the cached object and is neither
// re-cached nor notified, so reference-based consumers see no change for it.
if (!cache.hasValueChanged(key, value)) {
unchangedKeys.add(key);
continue;
}

const collectionKey = OnyxKeys.getCollectionKey(key);
if (collectionKey && OnyxKeys.isCollectionMemberKey(collectionKey, key)) {
// Capture the previous cached value before calling cache.set() so notifyCollection()
Expand Down Expand Up @@ -1274,7 +1306,12 @@ function multiSetWithRetry(data: OnyxMultiSetInput, retryAttempt?: number): Prom
const keyValuePairsToStore = keyValuePairsToSet.filter((keyValuePair) => {
const [key] = keyValuePair;
// Filter out the RAM-only key value pairs, as they should not be saved to storage
return !OnyxKeys.isRamOnlyKey(key);
if (OnyxKeys.isRamOnlyKey(key)) {
return false;
}
// Unchanged values are already in storage, so writing them again is redundant. On a retry the cache
// already holds the new values (every key looks unchanged), so storage must still get the full write.
return !!retryAttempt || !unchangedKeys.has(key);
});
const keysToRemoveFromStorage = keysToRemove.filter((key) => !OnyxKeys.isRamOnlyKey(key));

Expand Down Expand Up @@ -1357,13 +1394,22 @@ function setCollectionWithRetry<TKey extends CollectionKeyBase>({collectionKey,
// Capture the previous collection before cache mutations so notifyCollection() can diff removed members.
const previousCollection = OnyxUtils.getCachedCollection(collectionKey);

for (const [key, value] of keyValuePairs) cache.set(key, value);
// Members deep-equal to their cached value keep the cached object and are left out of the notification.
const {changedPairs, unchangedKeys} = partitionPairsByCacheChange(keyValuePairs);

for (const [key, value] of changedPairs) cache.set(key, value);
for (const key of keysToRemove) cache.drop(key);

// Skip subscriber notification on retry — already notified on attempt 0.
if (!retryAttempt) {
// Removed members are notified as undefined, matching mergeCollection/multiSet.
const partialForNotify = Object.fromEntries(Object.entries(mutableCollection).map(([key, value]) => [key, value ?? undefined]));
const partialForNotify: OnyxInputKeyValueMapping = {};
for (const [key, value] of Object.entries(mutableCollection)) {
if (unchangedKeys.has(key)) {
continue;
}
partialForNotify[key] = value ?? undefined;
}
notifyCollection(collectionKey, partialForNotify, previousCollection);
}

Expand All @@ -1375,9 +1421,13 @@ function setCollectionWithRetry<TKey extends CollectionKeyBase>({collectionKey,

const inFlightKeys = new Set<OnyxKey>(keyValuePairs.map(([key]) => key));

// Unchanged members are already in storage, so they are skipped. On a retry the cache already holds
// the new values (every member looks unchanged), so storage must still get the full write.
const keyValuePairsToStore = retryAttempt ? keyValuePairs : changedPairs;

// One batched removal = one cross-tab sync event instead of one per key. A failed removal is
// logged, not retried — keysToRemove cannot be re-derived after the cache update.
const storagePromises = [Storage.multiSet(keyValuePairs)];
const storagePromises = [Storage.multiSet(keyValuePairsToStore)];

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Do not record empty bulk batches as successful writes

When a native capacity-eviction retry is outstanding and another bulk request filters down to zero changed pairs, this still invokes Storage.multiSet([]). The SQLite provider resolves that without I/O (lib/storage/providers/SQLiteProvider.ts:273–275), but the following recordWriteSuccess() clears the outstanding eviction's no-progress streak or closes a half-open breaker despite no write succeeding. Interleaved unchanged bulk updates can therefore defeat the five-eviction safety limit while real writes continue failing. Skip empty writes and their success recording in this path, multiSetWithRetry, and partialSetCollection.

Useful? React with 👍 / 👎.

if (keysToRemove.length > 0) {
storagePromises.push(Storage.removeItems(keysToRemove).catch((error) => Logger.logAlert(`setCollection failed to remove keys from storage. Error: ${error}`)));
}
Expand Down Expand Up @@ -1645,13 +1695,22 @@ function partialSetCollection<TKey extends CollectionKeyBase>({collectionKey, co
// Capture the previous collection before cache mutations so notifyCollection() can diff removed members.
const previousCollection = getCachedCollection(collectionKey, existingKeys);

for (const [key, value] of keyValuePairs) cache.set(key, value);
// Members deep-equal to their cached value keep the cached object and are left out of the notification.
const {changedPairs, unchangedKeys} = partitionPairsByCacheChange(keyValuePairs);

for (const [key, value] of changedPairs) cache.set(key, value);
for (const key of keysToRemove) cache.drop(key);

// Skip subscriber notification on retry — already notified on attempt 0.
if (!retryAttempt) {
// Removed members are notified as undefined, matching mergeCollection/multiSet.
const partialForNotify = Object.fromEntries(Object.entries(mutableCollection).map(([key, value]) => [key, value ?? undefined]));
const partialForNotify: OnyxInputKeyValueMapping = {};
for (const [key, value] of Object.entries(mutableCollection)) {
if (unchangedKeys.has(key)) {
continue;
}
partialForNotify[key] = value ?? undefined;
}
notifyCollection(collectionKey, partialForNotify, previousCollection);
}

Expand All @@ -1662,9 +1721,13 @@ function partialSetCollection<TKey extends CollectionKeyBase>({collectionKey, co

const inFlightKeys = new Set<OnyxKey>(keyValuePairs.map(([key]) => key));

// Unchanged members are already in storage, so they are skipped. On a retry the cache already holds
// the new values (every member looks unchanged), so storage must still get the full write.
const keyValuePairsToStore = retryAttempt ? keyValuePairs : changedPairs;

// One batched removal = one cross-tab sync event instead of one per key. A failed removal is
// logged, not retried — keysToRemove cannot be re-derived after the cache update.
const storagePromises = [Storage.multiSet(keyValuePairs)];
const storagePromises = [Storage.multiSet(keyValuePairsToStore)];
if (keysToRemove.length > 0) {
storagePromises.push(Storage.removeItems(keysToRemove).catch((error) => Logger.logAlert(`setCollection failed to remove keys from storage. Error: ${error}`)));
}
Expand Down
34 changes: 34 additions & 0 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,39 @@ function areDeepEqualArrays(a: unknown, b: unknown): boolean {
return Array.isArray(a) && Array.isArray(b) && deepEqual(a, b);
}

/** Checks whether the value is a non-null object that isn't an array. */
function isNonArrayObject(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}

/**
* Cheap pre-check for a deep comparison: reports whether two plain objects differ in a top-level primitive property.
* It allocates nothing and returns at the first difference, so a value that really changed usually skips the full
* `deepEqual()` (which allocates both objects' key lists before comparing anything). `true` always means "not deep-equal";
* `false` means "unknown", so the caller still has to run the full comparison.
*/
function hasTopLevelPrimitiveChange(a: unknown, b: unknown): boolean {
if (!isNonArrayObject(a) || !isNonArrayObject(b)) {
return false;
}

// oxlint-disable-next-line core/no-restricted-syntax, guard-for-in
for (const key in a) {
const valueA = a[key];
const valueB = b[key];
if (valueA === valueB || (typeof valueA === 'object' && valueA !== null) || (typeof valueB === 'object' && valueB !== null)) {
continue;
}
// Both are primitives (or nullish) and differ. Two NaNs count as equal, matching `deepEqual()`.
// oxlint-disable-next-line no-self-compare
if (valueA === valueA || valueB === valueB) {
return true;
}
}

return false;
}

/**
* Reports whether a value needs cleaning (nested null/undefined, or the replace-object mark) before it's
* safe to store by reference. Read-only, non-allocating.
Expand Down Expand Up @@ -430,6 +463,7 @@ export default {
formatActionName,
removeNestedNullValues,
needsNormalization,
hasTopLevelPrimitiveChange,
checkCompatibilityWithExistingValue,
pick,
omit,
Expand Down
69 changes: 69 additions & 0 deletions tests/perf-test/useOnyx.perf-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -461,5 +461,74 @@ describe('useOnyx', () => {
afterEach: clearOnyxAfterEachMeasure,
});
});

/**
* Expected renders: 1.
*
* Setting deep-equal members (arrays included) keeps the cached references, so a subscriber without a selector doesn't re-render.
*/
test('setting deep-equal members with setCollection does not re-render', async () => {
const key = ONYXKEYS.COLLECTION.TEST_KEY;
await measureRenders(<UseOnyxWrapper onyxKey={key} />, {
beforeEach: async () => {
await Onyx.setCollection(key, createObjectArrayCollection(key, 3));
},
scenario: async () => {
await screen.findByText(dataMatcher(key, createObjectArrayCollection(key, 3)));

await act(async () => {
await Onyx.setCollection(key, createObjectArrayCollection(key, 3));
});

await screen.findByText(dataMatcher(key, createObjectArrayCollection(key, 3)));
},
afterEach: clearOnyxAfterEachMeasure,
});
});

/**
* Expected renders: 2 (the initial render and one commit for the update).
*
* Large list of members, each subscribing to its own collection member key, with the whole collection set
* again (like a full reconnect response) and a single member really changed. Deep-equal members keep their
* cached references, so only that member's item re-renders inside the commit, which shows in the render duration.
*/
test('large list of members, setCollection with a single member changed', async () => {
const SCALE = 100;
const createScaledCollection = (changedIndex?: number) =>
Object.fromEntries(Array.from({length: SCALE}, (_, index) => [`${ONYXKEYS.COLLECTION.TEST_KEY}${index}`, {name: index === changedIndex ? 'changed' : `n${index}`}]));

function ScaledItem({index}: {index: number}) {
const [data] = useOnyx(`${ONYXKEYS.COLLECTION.TEST_KEY}${index}`);
return <Text>{`item_${index}_${JSON.stringify(data)}`}</Text>;
}

function ScaledList() {
return (
<View>
{Array.from({length: SCALE}, (_, index) => (
<ScaledItem
key={index}
index={index}
/>
))}
</View>
);
}

await measureRenders(<ScaledList />, {
beforeEach: async () => {
await Onyx.setCollection(ONYXKEYS.COLLECTION.TEST_KEY, createScaledCollection());
},
scenario: async () => {
await screen.findByText(`item_0_${JSON.stringify({name: 'n0'})}`);

Onyx.setCollection(ONYXKEYS.COLLECTION.TEST_KEY, createScaledCollection(1));

await screen.findByText(`item_1_${JSON.stringify({name: 'changed'})}`);
},
afterEach: clearOnyxAfterEachMeasure,
});
});
});
});
Loading
Loading