Repository navigation
Keep inline edits from flickering back when a stale Search response lands - #104997
Conversation
…e edit Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
|
I created this PR from an upstream branch since I don't have push access to your fork. To take ownership of this branch and be able to push updates, run: Then you can close this PR and open a new one from your fork. |
… DiscardStaleSearchSnapshot Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
|
Fixed the failing This PR registers a 17th middleware,
|
|
🤖 Android test steps verification results: ✅ pass The PR's Tests section is still a TODO, so I tested steps derived from the PR description. Inline cell editing runs only on wide layouts ( |
|
@MelvinBot merge main |
…eSearchFlicker Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com> # Conflicts: # src/libs/Middleware/register.ts # src/libs/actions/Search.ts # tests/unit/MiddlewareRegistrationTest.ts
|
Merged Main and this PR changed the same lines in three files. I kept both sides in each:
I couldn't run the tests locally, so CI will be the first check of this merge. |
|
@MelvinBot Please update Tests
Offline testsN/A. QA StepsSame as Tests step PR Author ChecklistMark all author checklist checked |
|
@MelvinBot Mark this PR ready for review |
|
I updated the PR description:
I left the "Verify that no errors appear in the JS console" checkbox in Tests and QA unchecked. Check it once you confirm it. |
|
I marked this PR as ready for review. |
|
@ahmedGaber93 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button] |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7f10004041
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const discardStaleSearchSnapshot: Middleware = (requestResponse, request) => | ||
| requestResponse.then((response) => { | ||
| const hash = request?.data?.hash; | ||
| if (request?.command !== READ_COMMANDS.SEARCH || typeof hash !== 'number' || !guardedSearchHashes.has(hash) || !response?.onyxData || getPersistedRequestsLength() === 0) { |
There was a problem hiding this comment.
Remember writes after they leave the queue
When an intervening edit's write completes and is removed from PersistedRequests before the older Search response resolves, this returns the response unchanged because the current queue length is zero, even though the server may have produced that snapshot before processing the write. No follow-up search is scheduled, so the table can remain reverted until another refresh; the guard needs to record whether any write was queued during the request rather than inspecting only the queue's state at response time.
AGENTS.md reference: AGENTS.md:L99-L101
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e9d7466. The guard now remembers whether a write was queued while the search was in flight, even if that write has already finished. Before, it only checked for writes still in the queue.
PersistedRequests.tshas a new counter of every request ever queued, including ones merged from other tabs. UnlikegetLength(), it never goes down.DiscardStaleSearchSnapshot.tsrecords that count when it guards a search. When the response arrives, it drops the snapshot if the count has gone up or writes are still pending. The search then runs again and picks up the write.
One behavior change: any write queued during the search, including an unrelated one, now causes one extra re-run. Before, that only happened if the write was still pending when the response arrived. Each re-run records a fresh count, so it only repeats if yet another write is queued while it is in flight.
Tests and checks
- New middleware tests: the snapshot is dropped when the write finished before the response arrived, and kept when the only writes were queued before the guard was set.
- New
PersistedRequeststest: the counter still counts a request after it leaves the queue. - Passed: targeted Jest suites (80 suites, 2,205 tests),
npm run typecheck, and lint and spell check on the changed files. - Not run: the oxfmt check and the full Jest suite.
| @@ -1401,6 +1409,7 @@ function search({ | |||
| // A re-fire that only adds the save flag returns the same results the finished request just showed, | |||
There was a problem hiding this comment.
Preserve the stale guard through search deduplication
When this auto-refetch collides with an identical in-flight search and does not require a totals, recent-search, breakdown, or trip-room upgrade, the earlier inFlightRequest branch returns without creating this callback. Because shouldDiscardStaleSnapshot is not itself treated as an upgrade dimension, the existing pre-edit request remains unguarded and can overwrite the optimistic snapshot; schedule a guarded refire for this collision too.
AGENTS.md reference: AGENTS.md:L99-L101
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
@MelvinBot Could you please explain this further here in this conversation?
There was a problem hiding this comment.
The finding is real but narrow. A guarded auto-refetch can merge into an unguarded search that is already running for the same query. When that happens, nothing guards the unguarded search, so its stale response can still flip an edited cell back.
Why it happens
search()lets only one request run perhash_offset(Search.ts:1378-1381). A second call with the same key joins the running one instead of sending its own request.- The joining call only schedules a re-run for four differences: totals, save-to-recent, footer breakdown or trip rooms (
Search.ts:1386-1395).shouldDiscardStaleSnapshotisn't one of them. A guarded call that differs only in that flag returnsundefinedatSearch.ts:1418, and its flag is lost. - The guard is only set inside a request's own
waitForWrites().then(Search.ts:1608), and only when that request was started with the flag. A request started without the flag can never become guarded.
Example
- A report action calls
refreshSearchAfterReportAction(SearchRefreshUtils.ts:17). That search is unguarded and waits for the write queue. - You make edit 1. The auto-refetch (
useSearchAutoRefetch.ts:183) callssearch()with the guard flag. It merges into the waiting search and the flag is lost. - Edit 1's write finishes, so the unguarded search is sent.
- You make edit 2 while that search is in flight.
- Its response lands and overwrites edit 2's optimistic value. This is the flip-back this PR is meant to fix.
How narrow it is
- The auto-refetch skips
search()entirely if the snapshot already showsisLoading(Search.ts:1374). So it only collides with an unguarded search that hasn't shown loading yet: one still waiting for writes, or one sent withshouldShowLoading: false. - This isn't a regression. Before this PR, no search was guarded.
- When the merge does schedule a re-run (for example a totals upgrade), the re-run carries the flag and fixes the data. The cell can still flicker once before that.
Possible fixes
- Full fix: store
shouldDiscardStaleSnapshoton the running request. When a guarded call joins, upgrade the running request in place: set the flag, and if it has already been sent, guard it right away. This stops the flicker. - Smaller fix: treat a missing guard as another reason to re-run, like the other four. The data ends up correct, but the cell can still flicker once.
I haven't changed any code for this. To have me make one of these fixes, reply @MelvinBot with the one you want.
There was a problem hiding this comment.
A request started without the flag can never become guarded.
Ah, normal search call still reproduce this issue.
Screen.Recording.2026-11-03.at.3.10.12.PM.mov
There was a problem hiding this comment.
The full fix is in ad79a38. A refetch that wants the guard now passes it to the search already running for the same query. This also covers the normal search case in your video, where the results already show loading.
What changed
- The guard joins the running search (
Search.ts:1382-1397). This happens before theisLoadingcheck, so the loading case no longer drops it.- If that search is still waiting for writes, it guards itself when it is sent.
- If it was already sent, it is guarded right away. Writes are counted from when it was sent, so the edit's write counts even if it finishes first.
- Each in-flight search stores its guard state: the flag, the query it sent, and the queued-request count when it was sent. The guard is set at
Search.ts:1643.guardSearchAgainstStaleSnapshotnow takes that count. - A late join still re-runs (
Search.ts:1501). If the refetch joins after the response already passed the guard, the stale snapshot is applied. But a write queued since the search was sent schedules a guarded re-run, which corrects it. - Re-runs keep the guard. A re-run set up by a joining call, for example a totals upgrade, is guarded too.
A search started with skipWaitForWrites is still never guarded, so it can't loop.
Tests and checks
- New
search()tests:- A guarded refetch joins a search already sent while it shows loading. That search is guarded with the count from when it was sent, and runs again after its snapshot is dropped.
- A guarded refetch joins a search still waiting for writes, which then guards itself when sent. Only one request goes out.
- A write queued since sending causes a re-run even when the snapshot passed the guard.
- New middleware test: writes are counted from when the search was sent, even if it is guarded later.
- Passed: targeted Jest suites (79 suites, 2,183 tests),
npm run typecheck, and lint and spell check on the changed files. - Not run: the oxfmt check, the full Jest suite, and a manual repro of your video's flow.
Reviewer Checklist
Screenshots/VideosAndroid: HybridAppAndroid: mWeb ChromeiOS: HybridAppiOS: mWeb SafariMacOS: Chrome / SafariScreen.Recording.2026-11-03.at.11.44.18.PM.mov |
|
@MelvinBot review |
Review: changes neededThe approach is sound: the middleware runs before One change fixes 1–3 together. Record a write watermark when the guard is set, for example a counter bumped in
To have me make these fixes, reply |
|
@ahmedGaber93 let's go with option 2. I think the inflight invalidation would be fine in this case |
|
@MelvinBot Please implement option 2 here #104997 (comment) |
Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
|
🤖 Web test steps verification results: ❌ fail Implemented option 2 and pushed 4781973: inline edits explicitly invalidate sent Search snapshots, with no queue counter; 76 suites (2,104 tests), lint, typecheck, formatting, spelling and Storybook passed, while full Jest timed out. Browser verification was blocked by unsupported DevTools/throttling controls—not a confirmed product failure.
|
|
@MelvinBot merge main |
Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
ahmedGaber93
left a comment
There was a problem hiding this comment.
@MelvinBot Please fix
|
|
||
| // The queue can also become idle offline. Keep cached results until the reconnect refetch. | ||
| if (getIsOffline()) { | ||
| inFlightSearchRequests.delete(dedupeKey); | ||
| return undefined; | ||
| } | ||
|
|
There was a problem hiding this comment.
I think this change isn't needed for what this PR fixes. It changes how every Search behaves offline, not only after inline edits, so let's remove it and related tests.
There was a problem hiding this comment.
We don't need this test now, please remove it.
|
@MelvinBot please address this changes #104997 (review) |
Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
|
Addressed both review comments in ffc71de:
115 targeted tests, typecheck, lint, formatting, spelling and Storybook passed. Full Jest timed out. |
|
Both requested changes are already addressed in ffc71de:
Verified against the current PR head; no additional changes were needed. |
There was a problem hiding this comment.
@MelvinBot tests/unit/useSearchAutoRefetchTest.ts only has line-wrapping changes left (git diff -w shows nothing), from the removed shouldDiscardStaleSnapshot assertions. Can we revert it to main so it drops out of the diff?
Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
|
@MelvinBot A small improvement from Claude (reviewed it locally): only mark in-flight Searches for the edited snapshot's hash as stale, instead of all of them. If you agree, please apply it and update the tests that call
The edit only writes optimistic data to function markInFlightSearchRequestsStale(hash: number | undefined) {
for (const request of inFlightSearchRequests.values()) {
if (!request.isSent || request.hash !== hash) {
continue;
}
markSearchSnapshotStale(request.jsonQuery);
}
}with Suggested diffdiff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts
--- a/src/libs/actions/Search.ts
+++ b/src/libs/actions/Search.ts
@@ -1293,6 +1293,7 @@ type InFlightSearchRequest = {
pendingShouldSaveRecentSearch?: boolean;
pendingUpgradeRequest?: () => Promise<string | number | undefined> | undefined;
didSucceed?: boolean;
+ hash: number;
jsonQuery: string;
/** False while the request waits for writes. */
isSent: boolean;
@@ -1309,13 +1310,14 @@ const inFlightSearchRequests = new Map<string, InFlightSearchRequest>();
/**
* Invalidates sent Search snapshots before an inline edit applies its optimistic update. Requests waiting for writes
* already include the edit when they are sent. Call synchronously before the edit's write so a Search cannot slip between them.
+ * Only the edited snapshot is invalidated: the edit writes no other snapshot, and dropping one still loading would show it empty.
*/
-function markInFlightSearchRequestsStale() {
- for (const {jsonQuery, isSent} of inFlightSearchRequests.values()) {
- if (!isSent) {
+function markInFlightSearchRequestsStale(hash: number | undefined) {
+ for (const request of inFlightSearchRequests.values()) {
+ if (!request.isSent || request.hash !== hash) {
continue;
}
- markSearchSnapshotStale(jsonQuery);
+ markSearchSnapshotStale(request.jsonQuery);
}
}
@@ -1546,6 +1548,7 @@ function search({
shouldSaveRecentSearch: shouldSaveSearchToAccount,
footerTotal,
shouldReturnTripRooms: isTripRoomsSearch,
+ hash: queryJSON.hash,
jsonQuery,
isSent: false,
};
diff --git a/src/libs/actions/TransactionInlineEdit.ts b/src/libs/actions/TransactionInlineEdit.ts
--- a/src/libs/actions/TransactionInlineEdit.ts
+++ b/src/libs/actions/TransactionInlineEdit.ts
@@ -265,7 +265,7 @@ function getIouParamsForTransaction({
function editTransactionDateInline(params: TransactionInlineEditParams, newDate: string, personalPolicyOutputCurrency: string | undefined) {
const iouParams = getIouParamsForTransaction(params);
- markInFlightSearchRequestsStale();
+ markInFlightSearchRequestsStale(params.hash);
updateMoneyRequestDate({
isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
...iouParams,
@@ -297,7 +297,7 @@ function editTransactionMerchantInline(translate: LocalizedTranslate, params: Tr
// Building params can create a transaction thread, so do it only once the merchant is valid.
const iouParams = getIouParamsForTransaction(params);
- markInFlightSearchRequestsStale();
+ markInFlightSearchRequestsStale(params.hash);
updateMoneyRequestMerchant({
isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
...iouParams,
@@ -321,7 +321,7 @@ function editTransactionDescriptionInline(translate: LocalizedTranslate, params:
}
const iouParams = getIouParamsForTransaction(params);
- markInFlightSearchRequestsStale();
+ markInFlightSearchRequestsStale(params.hash);
updateMoneyRequestDescription({
isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
...iouParams,
@@ -333,7 +333,7 @@ function editTransactionDescriptionInline(translate: LocalizedTranslate, params:
/** Updates the category of an expense from the Search results table or the Expense Report page. */
function editTransactionCategoryInline(params: TransactionInlineEditParams, newCategory: string) {
const iouParams = getIouParamsForTransaction(params);
- markInFlightSearchRequestsStale();
+ markInFlightSearchRequestsStale(params.hash);
updateMoneyRequestCategory({
isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
...iouParams,
@@ -364,7 +364,7 @@ function editTransactionAmountInline(translate: LocalizedTranslate, params: Tran
const taxPercentage = getTaxValue(iouParams.policy, iouParams.transaction, taxCode) ?? '';
const decimals = params.getCurrencyDecimals(getCurrency(iouParams.transaction));
const taxAmount = convertToBackendAmount(calculateTaxAmount(taxPercentage, newAmount, decimals));
- markInFlightSearchRequestsStale();
+ markInFlightSearchRequestsStale(params.hash);
updateMoneyRequestAmountAndCurrency({
isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
...iouParams,
@@ -384,7 +384,7 @@ function editTransactionAmountInline(translate: LocalizedTranslate, params: Tran
/** Updates the tag of an expense from the Search results table or the Expense Report page. */
function editTransactionTagInline(params: TransactionInlineEditParams, newTag: string) {
const iouParams = getIouParamsForTransaction(params);
- markInFlightSearchRequestsStale();
+ markInFlightSearchRequestsStale(params.hash);
updateMoneyRequestTag({
isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
...iouParams, |
Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
|
Agreed—applied in 2a4f989.
2,427 targeted tests, typecheck, lint, formatting, spelling and Storybook passed. Full Jest timed out. |
|
@luacmartins All yours! |
|
🚧 luacmartins has triggered a test Expensify/App build. You can view the workflow run here. |
|
✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release. |
|
🧪🧪 Use the links below to test this adhoc build on Android, iOS, and Web. Happy testing! 🧪🧪
|
|
🚀 Deployed to staging by https://github.com/luacmartins in version: 9.5.42-0 🚀
|
|
No help site update needed — this PR fixes edited expense values briefly reverting on slow connections, restoring expected behavior without introducing a new workflow or making existing instructions incorrect. |
|
🚀 Deployed to production by https://github.com/marcaaron in version: 9.5.42-2 🚀
Bundle Size Analysis (Sentry): |






Explanation of Change
Follow-up item 5 from #89166 (comment): on a slow network, editing two table cells quickly made the first edited value flicker back to its old value.
Why it happened: an inline edit changes
transactions_<id>, souseSearchAutoRefetchcallssearch(). That search waits for the write queue to go idle, so it is sent right after the firstUpdateMoneyRequest*write finishes. If the user makes a second edit while that search is in flight, the second write merges its optimistic value intosnapshot_<hash>. Then the search response lands. Read responses are applied right away (only write responses are held until the queue flushes), and this one holds the server's values from before the second edit. It overwrites the optimistic snapshot row, and the cell flips back until the second write finishes and another refetch corrects it.What this PR does:
DiscardStaleSearchSnapshot, registered beforeSaveResponseInOnyx, removes only the invalidated request's snapshot update. Other response updates and final loading cleanup still apply. Invalidation uses the serialized query, including its offset, so releasing one page does not release another.PersistedRequestsoruseSearchAutoRefetchrelative to the branch's main merge base.Fixed Issues
$ #82534
PROPOSAL: #89166 (comment)
Tests
Precondition: Large screen - web only.
UpdateMoneyRequestMerchantrequest to finish and the subsequentsearchrequest to start.searchrequest completes, select Category B from the already-open category picker. Verify that Category B is applied optimistically in the UI.searchrequest completes, verify that Category B is still displayed and has not been overwritten by the original Category A returned by thesearchresponse.UpdateMoneyRequestMerchantandsearchrequests by step 6 have completed, verify that Category B is still displayed.Offline tests
N/A.
QA Steps
Same as Tests steps.
PR Author Checklist
### Fixed Issuessection aboveTestssectionOffline stepssectionQA stepssectionAvatar, I verified the components usingAvatarare working as expected)npm run compress-svg)Avataris modified, I verified thatAvataris working as expected in all cases)Designlabel and/or tagged@Expensify/designso the design team can review the changes.mainbranch was merged into this PR after a review, I tested again and verified the outcome was still expected according to theTeststeps.AI Tests
prettierscript remains unavailable, so the repository's Oxfmt script was used. Full Jest exceeded four minutes with no failures observed before timeout; no complete full-suite pass is claimed. The hash-scoping behavior was verified in unit tests, not in a browser.npm run lint,npm run lint-changed,npm run typecheck,npm run spell-changed, and Storybook smoke test. Staged code review found no violations.prettierscript does not exist. Used the repository'snpm run fmtinstead; a second run made no further changes, and the pre-commit formatter passed.origin/); attempts to supply the correct base were denied. Translation dry-run could not start under this branch's TypeScript/ts-node combination (ts.sysunavailable); no translation files changed.Screenshots/Videos
Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari