App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-12-08] [$175] Spend - Sort order resets to Descending after applying Ascending

Open applause-bot[bot] opened this issue 1 week ago • 17 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.42-0 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/102885 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: MacBook Pro/13.7.8, Samsung Galaxy S21/Android 15, iPhone 13/18.6.2 App Component: Other

Action Performed:

Precondition: account that has expenses on at least 4 different dates.

  1. Launch Expensify app
  2. Go to Account > Troubleshoot and turn on Simulate poor internet connection.
  3. Log in with valid credentials
  4. Go to Spend > Expenses.
  5. Tap the Display (eye) icon > set Sort order to Ascending and Group by to Day, then tap Apply.
  6. Open the Display settings again.

Expected Result:

Sort order remains set to Ascending after applying the changes.

Actual Result:

Sort order resets to Descending after tapping Apply.

Workaround:

Unknown

Platforms:

  • [ ] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [x] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/adc26c05-cb86-45be-a46f-3f0094edb624

View all open jobs on GitHub

Applause Internal Information Exported by: Svetlana Lazutkina Bug ID: 7319214

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @linhvovan29546

applause-bot[bot] avatar Nov 19 '26 18:11 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/f28350a3c83f192f60fb790b8f155c44ea81d2054f5ec7f0cc1ea808a6e24959

applause-bot[bot] avatar Nov 19 '26 18:11 applause-bot[bot]

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

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

Investigation complete: the source supports a client-side sort reset, but browser reproduction remains unconfirmed. The web tester reached Display; missing expense data and an automation click blocker prevented the sort/group changes. I’ve marked the analysis medium confidence and added the External label. 🤖 Web test steps verification results: ⚠️ partial

Dev NewDot web launched and Display opened. Missing expense data and a blocked sort interaction prevented retention testing.

Display menu showing Date Descending and Group by
Step Status
Launch AppHome rendered; signed-in state confirmed.
✅
Enable poor connectionTroubleshoot was not reached; setting not enabled.
⚠️
Expenses on four datesPrecondition unmet: account had no expenses.
Expenses screen with no expenses
⚠️
Navigate Spend > ExpensesExpenses rendered with Display available.
✅
Open DisplayMenu exposed Date • Descending and Group by.
Display menu showing Date Descending and Group by
✅
Apply AscendingAutomation rejected the click as covered by a dialog; selection was not applied.
⚠️
Apply Day and reopen DisplayBlocked before changing settings.
⚠️
Apply Ascending with Day already activeNot executed.
⚠️
Poor-connection reproductionNot executed; required setup was incomplete.
⚠️
Compare route queryNo successful settings change occurred for comparison.
⚠️

Proposal

What is the root cause of that problem?

Medium confidence — source-confirmed mechanism, browser reproduction incomplete.

Changing Group by clears both the sort column and direction, discarding the Ascending selection. The query parser then supplies Day’s default direction: Descending. Reopening Display reflects that updated query.

Code evidence and alternatives checked

This transformation happens before a server response, so poor connectivity is unnecessary for this mechanism. If Ascending resets without changing grouping, that would require additional investigation.

The reset already existed before the QA-linked PR; Stop Search from flashing its empty state while a Display change loads is discovery context, not an established introducing PR.

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

Separate sort-column reset from sort-direction preservation in the query builder. Changing grouping should select a compatible column without discarding the user’s chosen Ascending direction.

Add regression coverage for:

  • Ascending → newly select Day → direction remains Ascending.
  • Day already active → apply Ascending → direction persists.
  • Fresh Day queries retain their intended default; chart/view transitions remain correct.

Confirm whether all current directions should survive grouping changes. If only explicit user selections should survive, explicit-selection intent must be tracked separately from parser-generated defaults.

What alternative solutions did you explore? (Optional)

Changing Day’s default would mask the problem rather than preserve user choice. Loading-state changes would not prevent the query builder from removing the direction.

Related issue: Spend - Default sort is descending concerns report-table sorting; it is not an established duplicate.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/107444) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run · no recording available

MelvinBot avatar Nov 19 '26 18:11 MelvinBot

Proposal

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

On Spend > Expenses, when a user opens the Display menu and changes the Sort Order from "Descending" to "Ascending", the selection is applied. However, when reopening Display or when changing the Group By filter, the sort order resets back to "Descending".

What is the root cause of that problem?

In src/libs/SearchQueryUtils.ts: Inside buildFilterQueryWithSortDefaults():

    const resetSort = shouldResetSort({
        newGroupBy: filterValues.groupBy,
        oldGroupBy: previousState.groupBy,
    });

    const resetSortForViewChange =
        !resetSort &&
        shouldResetSortForViewChange({
            newView: filterValues.view,
            oldView: previousState.view,
            groupBy: filterValues.groupBy,
        });

    const queryString = buildQueryStringFromFilterFormValues(filterValues, {
        sortBy: resetSort || resetSortForViewChange ? undefined : currentQueryOptions.sortBy,
        sortOrder: resetSort || resetSortForViewChange ? undefined : currentQueryOptions.sortOrder,
        flatFilters: currentQueryOptions.flatFilters,
    });

When resetSort or resetSortForViewChange triggers (or when previousState.groupBy in useUpdateFilterQuery is uninitialized/stale relative to searchAdvancedFiltersForm), buildFilterQueryWithSortDefaults indiscriminately sets both sortBy AND sortOrder to undefined.

When sortOrder is omitted from the built query string, getQueryWithUpdatedValues delegates to searchParser.peggy (lines 104–119). Without an explicit sort-order directive in the query, the parser automatically re-derives the built-in grouping default direction: CONST.SEARCH.SORT_ORDER.DESC (Descending) for table views and Day/Month/Week groupings. Consequently, the user's explicit Ascending selection is wiped out and replaced with Descending upon reopening Display or changing grouping.

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

  1. In src/libs/SearchQueryUtils.ts: In buildFilterQueryWithSortDefaults(), decouple sortBy reset from sortOrder preservation:

    • When resetSort is true (the user switched groupBy), only sortBy needs to be reset so the parser can select the compatible grouping column (e.g. groupDay, groupMonth), while the user's explicit sortOrder (ASC or DESC) should be preserved.
    • For view transitions (resetSortForViewChange), only reset sortOrder when transitioning to views that have a strict, non-negotiable direction constraint (e.g., CONST.SEARCH.VIEW.LINE charts which require chronological ASC left-to-right display):
    const shouldResetSortOrder = resetSortForViewChange && filterValues.view === CONST.SEARCH.VIEW.LINE;
    
    const queryString = buildQueryStringFromFilterFormValues(filterValues, {
        sortBy: resetSort || resetSortForViewChange ? undefined : currentQueryOptions.sortBy,
        sortOrder: shouldResetSortOrder ? undefined : currentQueryOptions.sortOrder,
        flatFilters: currentQueryOptions.flatFilters,
    });
    
  2. In src/components/Search/hooks/useUpdateFilterQuery.tsx: Ensure previousState.groupBy and previousState.view correctly fall back to queryJSON?.groupBy and queryJSON?.view when searchAdvancedFiltersForm fields are not yet populated in Onyx:

    const previousGroupBy = searchAdvancedFiltersForm.groupBy ?? queryJSON?.groupBy;
    const previousView = searchAdvancedFiltersForm.view ?? queryJSON?.view;
    

    This prevents false positive shouldResetSort evaluations when opening and applying filters before Onyx form state is hydrated.

  3. Add unit test coverage in tests/unit/SearchQueryUtilsTest.ts:

    • Assert that changing groupBy from day to month with sortOrder: ASC preserves sortOrder: ASC.
    • Assert that applying sortOrder: ASC and re-generating query defaults does not fall back to DESC.

What alternative solutions did you explore?

Changing the default sort order of day to ASC in searchParser.peggy, but that breaks existing conventions and expectations for table views where users expect newest expenses first by default. Decoupling sortBy column reset from user-selected sortOrder direction in buildFilterQueryWithSortDefaults cleanly preserves user intent across filter and view adjustments without breaking parser defaults.

zainrizvi0611-cmd avatar Nov 19 '26 20:11 zainrizvi0611-cmd

@MelvinBot please update the proposal with this narrower fix in buildFilterQueryWithSortDefaults, instead of always resetting both sortBy and sortOrder when groupBy changes:

  1. sortBy: keep it if it's date or a group default column, since the parser already maps those to the new group column (sortBy:date sortOrder:asc groupBy:day → Day • Ascending). Reset it only for a custom column the new grouping doesn't have (e.g. merchant, amount). Otherwise Display shows "Merchant • Ascending" on Day groups.
  2. sortOrder: keep it only if it differs from the old grouping's default (the user picked it). Otherwise reset it so the new grouping's default applies (e.g. ungrouped date desc → Category should still become asc). Please get the defaults without copying GROUP_BY_DEFAULT_SORT_ORDER out of searchParser.peggy.
  3. Leave the view-change reset (shouldResetSortForViewChange) as is.

linhvovan29546 avatar Nov 20 '26 07:11 linhvovan29546

@linhvovan29546 I sent you a Slack DM to connect GitHub. I will continue the original request once you are connected.

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

Proposal

What is the root cause of that problem?

Changing grouping currently clears both sorting fields, including a user-selected Ascending direction. The parser then applies the new grouping’s default—Descending for Day.

Code evidence

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

Narrow the grouping-change logic in buildFilterQueryWithSortDefaults:

  1. Handle sortBy independently. Preserve date and group-default columns that the parser remaps to the new grouping. Preserve custom columns supported by the destination; clear unsupported ones such as merchant or amount when switching to Day. When removing grouping, clear incompatible group-only columns.
  2. Preserve only a non-default sortOrder. Derive the old grouping/view’s defaults through the existing buildQueryStringFromFilterFormValues → buildSearchQueryJSON path, without passing either current sort field. Preserve the current direction only if it differs from that parsed default; otherwise omit it so the new grouping’s default applies. Do not duplicate the parser’s default-order map.
  3. Leave shouldResetSortForViewChange, its guard, and its existing reset behavior unchanged.

This uses value comparison, not explicit-selection tracking: a user-selected direction equal to the old default is treated as default, as requested.

Regression coverage

Add cases alongside SearchQueryUtilsTest.ts:4726 onward:

  • Ungrouped date asc → Day: Day • Ascending.
  • Ungrouped date desc → Category: Category • Ascending.
  • merchant asc or amount asc → Day: Day • Ascending, without the unsupported column.
  • Supported custom group columns remain selected.
  • Group-default columns remap correctly; ungrouping removes incompatible columns.
  • Old chart/table defaults are respected, and existing view-only reset tests remain unchanged.

What alternative solutions did you explore? (Optional)

Always preserving direction would prevent new grouping defaults from applying. Always clearing the column unnecessarily discards compatible selections.


Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/107444) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 20 '26 07:11 MelvinBot

MelvinBot's proposal LGTM!

🎀 👀 🎀 C+ reviewed

linhvovan29546 avatar Nov 20 '26 08:11 linhvovan29546

Triggered auto assignment to @JS00001, see https://stackoverflow.com/c/expensify/questions/7972 for more details.

@linhvovan29546 feel free to work through this w/ melvin

JS00001 avatar Nov 20 '26 11:11 JS00001

@MelvinBot implement this

linhvovan29546 avatar Nov 23 '26 14:11 linhvovan29546

Implementation blocked: Fetching the latest main timed out on all three attempts (2, 5, and 5 minutes), so I couldn’t safely create the required fresh branch.

Your permissions and the approved proposal were confirmed. No code was changed and no PR was created.

Repository fetching needs to be restored before retrying implementation.


view run

MelvinBot avatar Nov 23 '26 14:11 MelvinBot

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

@MelvinBot implement this

linhvovan29546 avatar Nov 24 '26 06:11 linhvovan29546

🤖 Web test steps verification results: ❌ fail

Implemented in draft PR Preserve compatible expense sorting when grouping changes; all 42,766 automated tests passed. Browser verification was blocked by a blank app page on both attempts—not a confirmed behavioral failure.

Blank web app blocking all five checks
Step Status
Initial web verificationNo app nodes rendered; waiting for Spend timed out.
Blank web page blocking all requested checks
❌
Date Ascending → Day AscendingRetry blocked: app did not render.
Blank web app blocking all five checks
❌
Date Descending → Category AscendingNot executed: app did not render.
❌
Merchant Ascending → Day AscendingNot executed: app did not render.
❌
Day Ascending persists after reopening DisplayNot executed: app did not render.
❌
Month Table → Line → Table retains existing resetsNot executed: app did not render.
❌

view run · no recording available

MelvinBot avatar Nov 24 '26 07:11 MelvinBot

@linhvovan29546

The solution for this issue has been :rocket: deployed to production :rocket: in version 9.5.55-6 and is now subject to a 7-day regression period :calendar:. Here is the list of pull requests that resolve this issue:

  • https://github.com/Expensify/App/pull/107812

If no regressions arise, payment will be issued on 2026-12-08. :confetti_ball:

The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]

melvin-bot[bot] avatar Dec 01 '26 03:12 melvin-bot[bot]