App icon indicating copy to clipboard operation
App copied to clipboard

[Due for payment 2026-11-14] Wrong sorting on pinned elements in LHN when locale-specific letter is used

Open m-natarajan opened this issue 2 months ago • 115 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.4.76-0 Reproducible in staging?: Y Reproducible in production?: Y If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @sosek108 Slack conversation (hyperlinked to channel name): #Expensify Bugs

Action Performed:

  1. Create 3 custom named group chats with names where one is language Letter is used. Eg.: Nuevo Budget, Ñu Safari, Zote Report
  2. Pin all chats
  3. Observe the sorting

Expected Result:

These should be sorted:  Nuevo Budget, Ñu Safari, Zote Report

Actual Result:

Observed sorting is Nuevo budget, Zote Report , Ñu Safari

Workaround:

Unknown

Platforms:

Select the officially supported platforms where the issue was reproduced:

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

Screenshots/Videos

Image

https://github.com/user-attachments/assets/d954dcbc-d6ce-47f8-a4f3-8d0524bc2618

View all open jobs on GitHub

Issue OwnerCurrent Issue Owner: @mallenexpensify

m-natarajan avatar Sep 11 '26 12:09 m-natarajan

⏱️ Ran out of time before I could finish. This usually means the task was too complex or I got stuck exploring. Please try again with a more specific request or post in #melvinbot-ai.

Run details

MelvinBot avatar Sep 11 '26 13:09 MelvinBot

Whoops! This issue is 2 days overdue. Let's get this updated quick!

melvin-bot[bot] avatar Sep 14 '26 21:09 melvin-bot[bot]

Huh... This is 4 days overdue. Who can take care of this?

melvin-bot[bot] avatar Sep 16 '26 21:09 melvin-bot[bot]

6 days overdue. This is scarier than being forced to listen to Vogon poetry!

melvin-bot[bot] avatar Sep 18 '26 21:09 melvin-bot[bot]

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

melvin-bot[bot] avatar Sep 22 '26 17:09 melvin-bot[bot]

Proposal

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

Pinned chats in the LHN are sorted in the wrong order when a chat name starts with a locale-specific letter such as Ñ. With three pinned chats named "Nuevo Budget", "Ñu Safari" and "Zote Report", the LHN shows "Nuevo Budget", "Zote Report", "Ñu Safari" — the accented name is pushed to the bottom instead of being ordered next to the other N names.

What is the root cause of that problem?

The LHN rows are ordered by sortCategorizedReports, and every alphabetically-sorted group (pinned/GBR, errors, drafts, and — in focus mode — the rest) uses the compareDisplayNames comparator:

https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L506-L518

That comparator does not compare the names themselves. It compares a precomputed sortKey with the plain < / > operators, and only falls back to the locale-aware localeCompare (the Intl.Collator from LocaleContextProvider) when the two sort keys come out exactly equal — which never happens for two different names.

The sort key is built by buildSortKey, which only lowercases the name and zero-pads digit runs:

https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L117-L127

and is attached to each report when the rows are categorized:

https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L443-L448

Because < / > on strings compare raw UTF-16 code units, they order characters by code point and not by alphabet. ñ is U+00F1 (241) while z is U+007A (122), so "ñu safari" is considered greater than "zote report" and the row lands last. Sorting the three names from the report with plain string comparison reproduces the reported order exactly: nuevo budget, zote report, ñu safari. The collator that would have ordered them correctly is reached only in the tie branch, so it never runs for these names.

This affects every non-ASCII letter, not just ñ — accented Latin letters, Cyrillic, Greek, CJK names are all ordered by code point today. The key is purely a performance shortcut (the comment on buildSortKey says it exists "without Intl.Collator"), so the bug is that the shortcut is applied to names it cannot order correctly.

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

Make the fast path opt out for names it cannot order, and let the locale collator handle those.

In buildSortKey in src/libs/SidebarUtils.ts, detect whether the display name contains any character outside the ASCII range. If it does, cache and return an empty string instead of a key, which marks that name as "not comparable by code unit". ASCII-only names keep exactly the key they get today, so the common case pays no extra cost — the check is a single scan of a string we are already lowercasing, and the result stays cached in sortKeyCache.

Then in compareDisplayNames inside sortCategorizedReports, only apply the < / > comparison when both reports have a usable sort key — a non-empty key, or an empty display name (whose key is legitimately empty, so those rows keep sorting first as today). When either report is a non-empty name with an empty key, skip straight to the existing localeCompare(a.displayName, b.displayName) call at the bottom of the comparator, which already uses the user's locale Intl.Collator (created with numeric: true and caseFirst: 'upper', so numeric ordering and case ordering are preserved for those names too). The existing empty-display-name guard and the existing tie fallback stay as they are.

With that, "Ñu Safari" is compared against "Nuevo Budget" and "Zote Report" through the collator and is ordered next to the other N names instead of after Z. The exact position follows the user's locale: with the Spanish collator Ñ is its own letter after N, giving exactly the expected "Nuevo Budget", "Ñu Safari", "Zote Report"; with the English collator Ñ is treated as a variant of N, so "Ñu Safari" lands just before "Nuevo Budget". Meanwhile a list of plain ASCII names still sorts through the fast key path with no collator calls. The same fix applies to all four alphabetical LHN groups at once, since they all share this comparator.

A unit test in tests/unit/SidebarUtilsTest.ts covers the reported names with both the Spanish and English collators (it fails on main), and the existing buildSortKey test that asserted code-point ordering for accented names is updated to the new behavior.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/100959-lhn-locale-sort?expand=1

What alternative solutions did you explore? (Optional)

Stripping diacritics while building the key (normalizing to NFD and removing combining marks, so ñ becomes n) would keep a single fast path for every name, but it only helps Latin scripts, it loses the locale's own alphabet rules (in Spanish Ñ is a letter that sorts after N, not a variant of it), and it still orders Cyrillic, Greek and CJK names by code point. Dropping the sort key entirely and always calling localeCompare is the simplest correct option, but it gives up the performance optimization the key was added for on every LHN recompute, which is why the ASCII-only fast path is preferred.

wildan-m avatar Sep 22 '26 17:09 wildan-m

🚨 Edited by proposal-police: This proposal was edited at 2026-10-01 15:33:54 UTC.

Proposal

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

In the LHN, pinned chats whose names contain locale-specific letters (like Ñ) are sorted after every plain ASCII name instead of in their locale-correct position. With pinned Nuevo Budget, Ñu Safari, Zote Report, the list shows Nuevo Budget, Zote Report, Ñu Safari, so Ñ is pushed past Z.

What is the root cause of that problem?

compareDisplayNames (used by the pinned/GBR, error and draft groups, and by every group in focus mode) compares a precomputed sortKey with plain < / > and only calls the locale collator when the two keys are identical:

https://github.com/Expensify/App/blob/a3f34db9883981762f173be6e0b8e0c39692c7cc/src/libs/SidebarUtils.ts#L517-L529

The key is the lowercased name with zero-padded digit runs, built for every name:

https://github.com/Expensify/App/blob/a3f34db9883981762f173be6e0b8e0c39692c7cc/src/libs/SidebarUtils.ts#L119-L128

< on strings compares UTF-16 code units. ñ is U+00F1 (241) and z is U+007A (122), so "ñu safari" > "zote report" and the row lands last. For two different names the keys are never equal, so the collator never runs. The same happens for any accented Latin, Cyrillic, Greek or CJK name.

This came from #87847, which added the key to avoid ~230k collator calls per sort on large accounts (iOS 740ms -> 164ms, Android 2.1s -> 380ms). That PR already used one shared collator, so the cost it removed is real per-call collator cost on Hermes. The problem is that the key is applied to names it can't order, and a unit test locks that in:

https://github.com/Expensify/App/blob/a3f34db9883981762f173be6e0b8e0c39692c7cc/tests/unit/SidebarUtilsTest.ts#L4359-L4367

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

Keep the #87847 fast path only for names where it is provably identical to the collator, and send everything else to the collator.

For names made only of ASCII letters, digits, spaces and apostrophes (and no digit run longer than the 15-char padding), the lowercased + zero-padded key orders exactly like the app's collator. Apostrophes are included so the very common X's expenses names stay on the fast path. Other punctuation can't be added together with them, because the collator orders punctuation differently from code units. So buildSortKey returns a key only for those names:

const PLAIN_NAME_REGEX = /^[A-Za-z0-9 ']*$/;
const LONG_DIGIT_RUN_REGEX = /\d{16,}/;

function buildSortKey(displayName: string): string | undefined {
    if (sortKeyCache.has(displayName)) {
        return sortKeyCache.get(displayName);
    }

    // Only names where code-unit order matches the collator get a fast key
    const isPlainName = PLAIN_NAME_REGEX.test(displayName) && !LONG_DIGIT_RUN_REGEX.test(displayName);
    const key = isPlainName ? displayName.toLowerCase().replaceAll(DIGIT_SEQUENCE, (match) => match.padStart(NUMERIC_PAD_WIDTH, '0')) : undefined;
    sortKeyCache.set(displayName, key);
    return key;
}

(sortKey on MiniReport and the cache become string | undefined.)

And compareDisplayNames uses the key only when both sides have one:

const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
    if (a.sortKey !== undefined && b.sortKey !== undefined && a.sortKey !== b.sortKey) {
        return a.sortKey < b.sortKey ? -1 : 1;
    }
    if (!a.displayName || !b.displayName) {
        return 0;
    }
    return localeCompare(a.displayName, b.displayName);
};

Why this is correct and stays consistent:

  • Because the fast path never disagrees with the collator, the comparator is just the collator order everywhere. It's a consistent total order, unlike a per-pair ASCII/collator mix, which can give intransitive triples with punctuation (~, {) and make Array.sort order-dependent.
  • I fuzzed 100k random pairs per locale over that charset against Intl.Collator with the app's options (numeric: true, sensitivity: 'variant', caseFirst: 'upper') in en, es, fr, de, it, nl, pl, pt-BR, ja and zh-Hans: 0 mismatches. I ran this both on real Hermes (the hermesvm framework from our Pods, the same Apple Intl as iOS) and on V8.
  • Ñu Safari goes through the collator, so it follows the user's locale:
es: Nuevo Budget, Ñu Safari, Zote Report   <- expected result in the OP
en: Ñu Safari, Nuevo Budget, Zote Report

The English order is the normal English sort (ñ is n with a diacritic and the space in "Ñu " sorts before the "e" in "Nuevo"), so QA should check the OP order on a Spanish account.

Performance: plain names keep #87847's string compare. Only pairs where a name has accents, non-Latin letters or other punctuation pay for the collator, and they get the correct order in exchange. The cache stays per unique name, as today. Sorting 15k names on Hermes (measured on a Mac, so a phone is slower, but the ratios hold):

name mix                  collator only   main (key only)   this fix
2% accented               74ms            17ms              23ms
30% "X's expenses"        80ms            17ms              20ms
10% "#room"               73ms            16ms              25ms
30% "#room"               76ms            17ms              40ms

Branch with the fix and tests: https://github.com/Expensify/App/compare/main...dilshodmackbook-sketch:App:poc/100959-locale-sort

What specific scenarios should we cover in automated tests to prevent reoccurrence of the issue?

  • _sortCategorizedReports on pinned Nuevo Budget, Ñu Safari, Zote Report with an es collator: expect the OP order. Same input with en: expect Ñu Safari first, and never after Zote Report.
  • Report 2 before Report 10 still holds on the fast path.
  • A mixed group (plain, accented and punctuation names) gives the same order as sorting the names with the collator directly, so the fast path can't drift from the collator.
  • Replace the buildSortKey test that asserts accented names sort "by Unicode code point" with one asserting that non-plain names get no key.

What alternative solutions did you explore? (Optional)

  • Remove the key and always use the collator (my original solution). Simplest and correct, but it brings back the per-call collator cost #87847 measured on large accounts.
  • Per-pair fallback: key for ASCII pairs, collator otherwise. Keeps more of the fast path, but ASCII punctuation sorts differently by code unit than by collator, so the comparator can be intransitive.
  • Build ASCII keys from a collator-derived character rank table (preston-56's direction). Keeps the fast path for names with punctuation too, at the cost of a generated table that has to match every locale.
  • Strip or re-encode accents in the key. Fast, but locale-agnostic: it forces one order everywhere (wrong for en/de/sv/pl) and non-Latin scripts still sort by code point.

David-2002065 avatar Sep 22 '26 17:09 David-2002065

Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

melvin-bot[bot] avatar Sep 22 '26 17:09 melvin-bot[bot]

Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

melvin-bot[bot] avatar Sep 22 '26 17:09 melvin-bot[bot]

🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.

github-actions[bot] avatar Sep 22 '26 17:09 github-actions[bot]

Proposal

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

Pinned LHN chats whose names contain a locale-specific letter sort in the wrong place. With Nuevo Budget, Ñu Safari, Zote Report pinned, the LHN renders Nuevo Budget, Zote Report, Ñu Safari — Ñ lands after Z.

What is the root cause of that problem?

  1. The LHN comparator no longer uses a collator. compareDisplayNames orders reports with plain < / > on a pre-built sortKey, and only calls the injected localeCompare when the two keys are exactly equal: https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L506-L518

  2. sortKey is just the lowercased name with digit runs zero-padded — explicitly built so ordering happens "without Intl.Collator": https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L111-L126

  3. < / > on strings compare UTF-16 code units, not letters. 'ñ' is U+00F1 (241), 'z' is U+007A (122), so every non-ASCII initial sorts after the whole ASCII alphabet. Because the keys "ñu safari" and "zote report" are not equal, line 517's collator fallback is unreachable — it is dead code for any two distinct names.

Running the reporter's three names through both comparators reproduces the report exactly:

sortKey (<,>) : Nuevo Budget, Zote Report, Ñu Safari   <- Actual Result
Intl.Collator : Nuevo Budget, Ñu Safari, Zote Report   <- Expected Result (es locale)

This is a regression from #87847 ("Optimize LHN sidebar sorting with pre-computed sort keys", merged 2026-04-17). Commit 70dd28add6b replaced the line const compareDisplayNames = (a, b) => (a?.displayName && b?.displayName ? localeCompare(a.displayName, b.displayName) : 0); with the key comparison above. The PR assumed a lowercased key compares like a collator; for non-ASCII letters that assumption is false. The same PR added a unit test that locks the broken behaviour in: https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/tests/unit/SidebarUtilsTest.ts#L4185-L4193

Every LHN group is affected, not just pinned. compareDisplayNames is the comparator for pinned/GBR, error and draft rows always, and for non-archived + archived rows in focus mode: https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L528-L543 In default (most-recent) mode the non-archived group is date-sorted first and only falls back to the name comparator on a date tie (L523-L526), which is why the reporter noticed it on pinned rows — those are the group that is always ordered purely by name. sortReportsToDisplayInLHN is shared with no platform split, which matches the four platforms ticked in the report.

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

Restore the collator as the comparator — i.e. put back exactly what #87847 removed:

const compareDisplayNames = (a: MiniReport, b: MiniReport) =>
    a?.displayName && b?.displayName ? localeCompare(a.displayName, b.displayName) : 0;

https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L506-L518

The one-liner is the whole fix. The objection you'd expect — that this loses the natural-number ordering the key was built for — does not hold: the app's collator is already created with numeric: true: https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/components/LocaleContextProvider.tsx#L97 so Report 2 still sorts before Report 10. The whole buildSortKey / sortKeyCache machinery becomes redundant and should be deleted in the same PR (buildSortKey, sortKeyCache, NUMERIC_PAD_WIDTH, DIGIT_SEQUENCE, MiniReport.sortKey, the sortKeyCache.clear() at L428, the sortKey: assignment at L446 and the _buildSortKey test export at L1041 — nothing outside SidebarUtils.ts reads them). The SidebarUtilsTest case quoted above must be inverted to assert locale order.

Regression safety: this is the comparator the LHN used from #36592 (Feb 2024) until April 2026, localeCompare is already injected into this function, and no other group's ordering rule changes.

Secondary (optional), for the perf goal of #87847: the Intl.Collator is constructed on every LocaleContextProvider render (const collator = new Intl.Collator(...), L143, no useMemo in the file). Wrapping it in useMemo(..., [currentLocale]) gives back the construction cost the sort key was working around, without trading away correctness.

What alternative solutions did you explore? (Optional)

Keep the fast key path and only fall back to localeCompare when a name is non-ASCII. This is the tempting "preserve the optimisation" fix and it is incorrect: it makes the comparator non-transitive, because ASCII pairs are ranked by code unit while mixed pairs are ranked by collation. With ~Team, Ñu Safari, Zote Report: ~Team < Ñu Safari and Ñu Safari < Zote Report (collator), but ~Team > Zote Report ('~' U+007E > 'z'). Array.prototype.sort with a non-transitive comparator is implementation-defined — I ran a 12-name list through it in 300 different input orders and got 46 different outputs, so the LHN would reorder itself on unrelated re-renders. ASCII is not a safe fast path anyway: {, |, }, ~ all sort after z by code unit and before letters by collation.

Strip diacritics into the sort key (normalize('NFD') + remove combining marks). Fails the reported repro: it maps ñ → n, giving Ñu Safari, Nuevo Budget, Zote Report in Spanish, where ñ is a distinct letter that sorts after n. It also leaves Cyrillic, Greek and CJK names in code-point order and silently ties different names (Ana / Aña).

ahmdshrif avatar Sep 22 '26 17:09 ahmdshrif

Proposal updated — added compare branch with implementation and a unit test.

wildan-m avatar Sep 22 '26 17:09 wildan-m

🚨 Edited by proposal-police: This proposal was edited at 2026-10-03 20:41:14 UTC.

Withdrawn. FitseTLT's concern above about the performance cost holds for this approach. I measured it on Hermes, the engine the iOS and Android apps run: sorting 15,000 generated reports by name (focus mode) went from about 25 ms to about 86 ms, roughly 3.4x, because every name comparison is a collator call again (about 210,000 calls per sort instead of about 600, close to the ~230k #87847 describes for a large account). In the default mode it was faster (about 29 ms to 17 ms), because main rebuilds all 15,000 sort keys on every recompute while that mode sorts most reports by date. The focus-mode cost is the one #87847 gave up locale order to remove, so this direction should not be picked. Like dilshod's numbers above, mine come from a Mac rather than a phone: a copy of the sort code compiled to Hermes bytecode and run on Apple Silicon. The original is left below for reference.


Updated 2026-09-30: I corrected several statements that did not hold up. The collator fallback does run when two keys tie (for example Abc and abc), so uppercase-first still applies there. buildSortKey came from #87847, which measured a large speed-up on iOS and Android and accepted code-point order for accented letters on purpose, and a unit test locks that in. The expected order also depends on the user's locale, and folding accents into the key would not give the Spanish order either. The fix direction is unchanged.

Proposal

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

Pinned chats named Nuevo Budget, Ñu Safari, Zote Report render in the LHN as Nuevo Budget, Zote Report, Ñu Safari — the accented name is pushed below Z instead of sitting next to the other N names.

What is the root cause of that problem?

LHN rows are ordered by compareDisplayNames, which compares a precomputed sortKey with the plain < / > operators and only reaches the locale-aware collator when both keys are identical:

https://github.com/Expensify/App/blob/b0569a754ffd0a6462399e8fdf266b4ce9ab0be2/src/libs/SidebarUtils.ts#L517-L529

< / > compare UTF-16 code units. ñ is U+00F1 (241), z is U+007A (122), so 'ñu safari' > 'zote report', which is the repro exactly. The localeCompare fallback at L528 only runs when two keys are identical, such as Abc and abc.

The key comes from #87847, which replaced per-comparison collator calls with these precomputed keys to speed up sorting on large accounts (its description reports iOS 740ms → 164ms and Android 2.1s → 380ms). It accepted Unicode code-point order for letters like Spanish ñ as the tradeoff, and tests/unit/SidebarUtilsTest.ts locks that in (should sort accented characters by Unicode code point, not locale-aware order). The key also has two problems of its own:

https://github.com/Expensify/App/blob/b0569a754ffd0a6462399e8fdf266b4ce9ab0be2/src/libs/SidebarUtils.ts#L112-L128

1. The padding is itself an ordering bug. NUMERIC_PAD_WIDTH is 15 (L98) and padStart(15) is a no-op on a longer digit run. "Invoice 1234567890123456" (16 digits) keeps its run intact while "Invoice 999999999999999" (15 digits) pads to exactly 15, and code-unit compare then puts the larger number first. A second, independent ordering defect in the same helper — no accented characters required.

2. The cache is cleared on every recompute. Its doc comment promises each unique name "pays the cost only once", but categorizeReportsForLHN clears it on entry, so each LHN recompute rebuilds every key:

https://github.com/Expensify/App/blob/b0569a754ffd0a6462399e8fdf266b4ce9ab0be2/src/libs/SidebarUtils.ts#L431-L439

Blast radius is wider than the pinned group. The same comparator sorts the error and draft groups, and when isInDefaultMode is false (focus mode) it sorts the entire non-archived and archived lists:

https://github.com/Expensify/App/blob/b0569a754ffd0a6462399e8fdf266b4ce9ab0be2/src/libs/SidebarUtils.ts#L546-L556

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

Delete the sort-key path and compare with the collator. Every collator in the app is built from one shared options object with numeric: true, so "Report 2" sorts before "Report 10" without padding, and it follows the user's locale for letters like ñ:

https://github.com/Expensify/App/blob/b0569a754ffd0a6462399e8fdf266b4ce9ab0be2/src/libs/CollatorUtils.ts#L1-L25

In src/libs/SidebarUtils.ts:

const compareDisplayNames = (a: MiniReport, b: MiniReport) => localeCompare(a.displayName, b.displayName);

Then remove buildSortKey, sortKeyCache, NUMERIC_PAD_WIDTH, DIGIT_SEQUENCE, the sortKeyCache.clear() call, the sortKey field on MiniReport, its assignment in categorizeReportsForLHN, and the _buildSortKey test export at L1070. localeCompare is already a parameter of sortCategorizedReports, so no signatures change and no imports are added.

On cost: name comparisons go back to one collator call each, as before #87847. getCollator memoizes the collator per locale (CollatorUtils.ts L14-L23), so nothing is constructed per comparison, but the per-call cost is what #87847 removed. In Node (v20), sorting 15,000 generated names took about 27–31 ms through the collator and 17–19 ms through the key path, roughly 1.5x slower. I have not measured it on iOS or Android, where #87847 reports a much bigger gap.

Tests: drop the _buildSortKey import (L21), the describe('buildSortKey') block, and the literal sortKey fields from the fixtures. Then add cases over the reporter's names: with an es collator the order is ['Nuevo Budget', 'Ñu Safari', 'Zote Report'], and with en it is ['Ñu Safari', 'Nuevo Budget', 'Zote Report'], because English collation treats ñ as an accented n. Also add "Report 2" before "Report 10", and a 15-vs-16-digit case to pin defect 1.

What alternative solutions did you explore? (Optional)

Keeping the fast key and folding diacritics into it — displayName.normalize('NFD').replace(/\p{Diacritic}/gu, ''), so Ñu becomes nu and only exact ties reach the collator. I rejected it: it hardcodes English-style accent folding into a key used for every locale. pl is a valid preferred locale (beta, src/CONST/LOCALES.ts), and Polish orders ą between a and b at the primary level, so "Ąa" must sort after "Ab"; folding gives "aa" < "ab", and the tie-break never fires because the keys differ. It doesn't fix Spanish either: folded, Ñu Safari becomes nu safari and still sorts before Nuevo Budget, while Spanish puts ñ after n. The same folding misorders Czech č and Swedish å, and it leaves defects 1 and 2 in place.

trasnake87 avatar Sep 22 '26 17:09 trasnake87

Proposal

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

When a user pins several group chats whose names start with locale-specific letters (e.g. "Nuevo Budget", "Ñu Safari", "Zote Report"), the LHN sorts them incorrectly. Expected alphabetical order is Nuevo Budget, Ñu Safari, Zote Report, but the actual order is Nuevo Budget, Zote Report, Ñu Safari — the name starting with "Ñ" is pushed to the very end instead of sorting next to "N".

What is the root cause of that problem?

The LHN pinned/GBR group (and the other name-sorted groups) is sorted by compareDisplayNames, which first compares a precomputed sortKey using plain JavaScript < / > operators, and only falls back to the locale-aware localeCompare (an Intl.Collator) when the two sortKeys are exactly equal:

https://github.com/Expensify/App/blob/8bf07f846fd4abf47c2314b1e89370cbfab0a7e5/src/libs/SidebarUtils.ts#L517-L529

The sortKey itself is built by buildSortKey, which just lowercases the display name and zero-pads digit sequences — it does not do any locale-aware normalization/collation:

https://github.com/Expensify/App/blob/8bf07f846fd4abf47c2314b1e89370cbfab0a7e5/src/libs/SidebarUtils.ts#L112-L128

Because sortKey comparison uses plain </>, JavaScript compares the strings by raw UTF-16 code unit value, not by locale collation rules. "n" is U+006E (110), "z" is U+007A (122), and "ñ" is U+00F1 (241). So for the lowercased keys "nuevo budget", "zote report", "ñu safari", plain code-unit comparison places "ñu safari" after "zote report" (241 > 122 > 110), which is exactly the buggy order observed in the issue. Since the three sort keys are never equal to each other, the code never reaches the localeCompare(a.displayName, b.displayName) fallback on line 528, so the locale-correct Intl.Collator comparison (which is set up correctly and would sort "ñ" adjacent to "n") is never actually applied here.

For confirmation, the locale-aware comparator passed in is built from a real Intl.Collator for the current locale:

https://github.com/Expensify/App/blob/8bf07f846fd4abf47c2314b1e89370cbfab0a7e5/src/components/LocaleContextProvider.tsx#L142

https://github.com/Expensify/App/blob/8bf07f846fd4abf47c2314b1e89370cbfab0a7e5/src/components/LocaleContextProvider.tsx#L171

So the collator would sort these three names correctly if it were actually used to compare them — the bug is purely that buildSortKey + raw </> comparison is used as the primary comparison, and it produces a different (and wrong) ordering than the collator would, so the collator fallback is unreachable in this case.

Worth noting: tests/unit/SidebarUtilsTest.ts already has a unit test asserting that buildSortKey('Café') > buildSortKey('Cafe') (i.e. Unicode code-point ordering, not locale-aware ordering) for the buildSortKey helper in isolation. That test only documents buildSortKey's own behavior — it does not exercise the full compareDisplayNames pipeline (with the localeCompare fallback), so it isn't evidence that non-locale-aware ordering is the intended end-to-end behavior for the LHN; it simply shows the helper was never meant to be locale-correct by itself, which is exactly why it shouldn't be trusted as the primary/authoritative comparison.

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

The sortKey fast-path exists purely as a performance optimization to avoid calling the (relatively expensive) Intl.Collator for every pairwise comparison. However, that optimization is only correct if sortKey's ordinal ordering agrees with the locale collator's ordering — which it doesn't for locale-specific letters like "ñ", accented characters, etc. The fix should make compareDisplayNames always defer to the locale-aware comparator for the actual ordering decision, rather than trusting the ordinal sortKey comparison as the source of truth.

Original code: https://github.com/Expensify/App/blob/8bf07f846fd4abf47c2314b1e89370cbfab0a7e5/src/libs/SidebarUtils.ts#L517-L529

The most robust, minimal fix is to stop trusting sortKey's ordinal </> result as authoritative and instead always resolve ties/ordering through localeCompare, using sortKey only as a pre-check for equality (skip the collator call entirely when the two mini-reports are already known to be identical) rather than for ordering:

const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
    if (a.sortKey === b.sortKey) {
        if (!a.displayName || !b.displayName) {
            return 0;
        }
        return localeCompare(a.displayName, b.displayName);
    }
    return localeCompare(a.displayName, b.displayName);
};

Since both branches end up calling localeCompare on the display names, this simplifies to always calling the locale-aware comparator directly for ordering, which is what should happen since correctness matters more than the ordinal-key micro-optimization for the (typically small) pinned/GBR/error/draft groups being sorted here:

const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
    if (!a.displayName || !b.displayName) {
        return 0;
    }
    return localeCompare(a.displayName, b.displayName);
};

This removes the incorrect ordinal sortKey comparison as the primary sort decision while still keeping buildSortKey/sortKeyCache available if it's needed elsewhere (e.g. as a cheap equality/memoization check), and guarantees the LHN pinned/GBR/error/draft/non-archived/archived groups are always ordered using the real Intl.Collator for the user's locale — which is exactly the mechanism already built and wired up via LocaleContextProvider, just not consistently applied. This keeps the fix idiomatic (reusing the existing localeCompare collator plumbing that's already threaded through sortReportsToDisplayInLHN and sortCategorizedReports) and doesn't introduce any new sorting utilities or workarounds.

This also does not regress the existing natural-numeric-sort behavior (e.g. "Report 2" sorting before "Report 10") that buildSortKey's digit zero-padding was compensating for: the shared collator options already set numeric: true, so Intl.Collator/localeCompare natively sort numeric segments in natural order on its own, independent of buildSortKey.

https://github.com/Expensify/App/blob/8bf07f846fd4abf47c2314b1e89370cbfab0a7e5/src/libs/CollatorUtils.ts#L6

abbasifaizan70 avatar Sep 22 '26 17:09 abbasifaizan70

🚨 Edited by proposal-police: This proposal was edited at 2026-09-24 04:27:06 UTC.

Proposal

What is the root cause of that problem?

Pinned chats named Nuevo Budget, Ñu Safari, and Zote Report show as Nuevo Budget, Zote Report, Ñu Safari. Ñ is pushed below Z.

compareDisplayNames does not compare the names. It compares a sortKey with < and >, and only calls localeCompare when the two keys are exactly the same:

https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L506-L518

buildSortKey only lowercases the name and pads numbers. It does not change letters like Ñ:

https://github.com/Expensify/App/blob/93ee23751288105b63158ae3306e9f230c7a8c0b/src/libs/SidebarUtils.ts#L117-L127

< and > compare character codes. ñ is 241 and z is 122, so ñu safari sorts after zote report. The two keys are not equal, so localeCompare never runs. The same thing happens to other letters that sit above z, such as Á, É, and Ü.

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

We should keep the < / > sort from #87847. Change only buildSortKey in SidebarUtils. We don't need to delete sortKey or change compareDisplayNames.

buildSortKey still lowercases the name and zero-pads numbers, so Report 2 still comes before Report 10. After that, it rewrites language letters so < and > put them after the plain letter and before the next letter.

Ñ.toLowerCase() is ñ. normalize('NFD') splits that into n plus a tilde. We keep the tilde and insert a mark in front of it. The mark is \uFFFF, which is higher than any letter, digit, or normal punctuation in a chat name. Letters that do not split this way (ł, ø, æ, and a few others) are stored as their base letter, then the same mark, so they do not fall after Z.

const LANGUAGE_LETTER_MARK = '\uFFFF';

function encodeLanguageLetters(value: string): string {
    let encoded = '';
    for (const char of value.normalize('NFD')) {
        const atomicBase = ATOMIC_LANGUAGE_LETTER_BASES[char];
        if (atomicBase) {
            encoded += atomicBase + LANGUAGE_LETTER_MARK + char;
            continue;
        }
        if (isCombiningMark(char.codePointAt(0) ?? 0)) {
            encoded += LANGUAGE_LETTER_MARK + char;
            continue;
        }
        encoded += char;
    }
    return encoded;
}

function buildSortKey(displayName: string): string {
    const normalizedName = displayName.toLowerCase().replaceAll(DIGIT_SEQUENCE, (match) => match.padStart(NUMERIC_PAD_WIDTH, '0'));
    return encodeLanguageLetters(normalizedName);
}

The comparator stays exactly as it is today:

const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
    if (a.sortKey < b.sortKey) {
        return -1;
    }
    if (a.sortKey > b.sortKey) {
        return 1;
    }
    if (!a.displayName || !b.displayName) {
        return 0;
    }
    return localeCompare(a.displayName, b.displayName);
};

localeCompare still runs only when two keys are equal, for example Alpha and alpha. Pinned, error, draft, and focus-mode name sorts all use this same comparator. Plain ASCII names never hit the extra letter logic, so they stay on the fast path.

What alternative solutions did you explore? (Optional)

Using < / > for ASCII names and localeCompare only for accented names is unsafe. The two orders disagree on punctuation, so the same list can come out differently depending on input order.

Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

POC https://github.com/user-attachments/assets/459b2418-378c-48ab-b3ca-1fe8cd51db6a

samranahm avatar Sep 22 '26 17:09 samranahm

Proposal

What is the root cause of that problem?

I found that LHN display names are converted into lowercase, digit-padded sortKey values:

https://github.com/Expensify/App/blob/8a6645213f4cf7fc8a3f104c83158cfb66ce4883/src/libs/SidebarUtils.ts#L112-L128

compareDisplayNames compares those keys with JavaScript’s < and > operators. Those operators use Unicode code-point order, so ñ sorts after z. The locale-aware comparison is reached only when both keys are equal:

https://github.com/Expensify/App/blob/8a6645213f4cf7fc8a3f104c83158cfb66ce4883/src/libs/SidebarUtils.ts#L517-L529

This regressed when PR #87847 optimized LHN sorting with precomputed keys:

https://github.com/Expensify/App/commit/873723838cd0cd6c28fbf326f931fa481e461c86

The current test even asserts the incorrect code-point behavior instead of exercising the actual LHN order:

https://github.com/Expensify/App/blob/8a6645213f4cf7fc8a3f104c83158cfb66ce4883/tests/unit/SidebarUtilsTest.ts#L4360-L4368

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

I think we should retain the optimized sortKey comparator for a category only when every display name in that category is ASCII. If any name contains a locale-specific character, the whole category must use localeCompare.

It is important to select one comparator for the entire category. Falling back to localeCompare only for pairs containing a non-ASCII name would mix two different orderings and can produce a non-transitive comparator, making the final order dependent on the sort algorithm and input order.

Illustratively:

- sortIfNeeded(reports, compareDisplayNames);
+ const comparator = reports.some(({displayName}) => /[^\x00-\x7F]/.test(displayName))
+     ? compareLocaleDisplayNames
+     : compareSortKeys;
+ sortIfNeeded(reports, comparator);

The locale comparator is already backed by a cached Intl.Collator configured for numeric sorting, so names such as Report 2 and Report 10 remain correctly ordered:

https://github.com/Expensify/App/blob/8a6645213f4cf7fc8a3f104c83158cfb66ce4883/src/libs/CollatorUtils.ts#L3-L22

I would apply this selection to every category sorted alphabetically, including the display-name tie-breaker for non-archived reports in default mode. ASCII-only categories keep the existing fast path, while mixed or non-ASCII categories get one consistent locale-aware ordering.

I would also replace the code-point buildSortKey test with sortCategorizedReports coverage using Nuevo Budget, Ñu Safari, and Zote Report, and retain the existing numeric-order coverage.

What alternative solutions did you explore? (Optional)

Always using localeCompare would be correct but would discard the LHN comparison optimization introduced by #87847.

Normalizing or removing diacritics would still be locale-incorrect—for example, some languages treat accented characters as distinct letters. Pair-by-pair fallback is also unsafe because it mixes comparators within one sort.

mukhrr avatar Sep 22 '26 17:09 mukhrr

Proposal

What is the root cause of that problem?

compareDisplayNames primarily compares sortKey values with JavaScript < and >; it reaches the locale comparator only when the two keys are equal. [The comparator] https://github.com/Expensify/App/blob/f2a4120bd57aa25b19db23610609fd9f16c1ead7/src/libs/SidebarUtils.ts#L517-L529 therefore follows Unicode code-point order for most different names.

buildSortKey currently only lowercases a display name and zero-pads its numbers. [It does not fold accented letters] https://github.com/Expensify/App/blob/f2a4120bd57aa25b19db23610609fd9f16c1ead7/src/libs/SidebarUtils.ts#L112-L128 so ñ remains after z in a raw string comparison. This is why Ñu Safari can appear after Zote Report.

The fast key path was added deliberately for large LHN lists. The problem is not pinning, Onyx, or rendering; it is that the fast key has no best-effort equivalent for most accented Latin characters.

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

Keep the existing fast sortKey comparison, but make buildSortKey create a best-effort accent-folded key before it applies the existing numeric padding:

  1. Reuse [StringUtils.normalizeAccents] https://github.com/Expensify/App/blob/f2a4120bd57aa25b19db23610609fd9f16c1ead7/src/libs/StringUtils/index.ts#L102-L120 after lowercasing the display name and before applying numeric padding. It folds common accents such as ñ to n, é to e, and č to c, and skips normalize('NFD') entirely for ASCII-only names.
  2. Keep the existing numeric-padding step, so the fast path continues to order Report 2 before Report 10.
  3. Keep the existing locale-comparator fallback for equal folded keys. For example, Cafe and Café share a folded key, so the current fallback can still decide their final order.
  4. Do not add a large locale-specific replacement table for characters without a safe general equivalent, such as ß, æ, ø, œ, and đ. Leave those characters unchanged. This makes the limitation explicit instead of silently applying incorrect rules for a language.

This is deliberately best-effort ordering, not locale collation. Folding ñ to n can produce a different order from a Spanish collator; for example, the folded keys put Ñu Safari before Nuevo Budget because nu sorts before nue. That trade-off must be accepted for option 3, rather than presenting the result as the Spanish alphabetical order.

This is a small change contained in buildSortKey https://github.com/Expensify/App/blob/f2a4120bd57aa25b19db23610609fd9f16c1ead7/src/libs/SidebarUtils.ts#L119-L128 It preserves the existing fast < / > comparisons, with no changes to Onyx, optimistic pinning, the backend, or LHN rendering. sortKeyCache is cleared on each categorization https://github.com/Expensify/App/blob/f2a4120bd57aa25b19db23610609fd9f16c1ead7/src/libs/SidebarUtils.ts#L433-L439 so profile complete LHN recomputation on iOS and Android after the change; do not describe normalization as zero-cost.

Update SidebarUtilsTest https://github.com/Expensify/App/blob/f2a4120bd57aa25b19db23610609fd9f16c1ead7/tests/unit/SidebarUtilsTest.ts#L4359-L4380 to cover the folded result for the reported names, a folded-key collision such as Cafe/Café, composed versus decomposed forms, numeric sorting, and the documented behavior for an unmapped character such as ø. Also verify that generated keys use the same accent-folding result as StringUtils.normalizeAccents.

What alternative solutions did you explore? (Optional)

  • Calling the locale comparator for every comparison gives fully locale-correct ordering, but restores the performance cost that the fast key was introduced to avoid on very large lists.
  • A large manual map for ß, æ, ø, œ, đ, and similar letters looks more complete, but those characters have different valid positions in different languages. It would turn this best-effort performance trade-off into an incorrect global collation rule.
  • A collator fallback for every non-ASCII name is more correct than folding, but is a different hybrid approach and has a higher comparison cost. This proposal follows the stated option to improve most decomposable accented characters while accepting explicit limitations for the rest.

nabi-ebrahimi avatar Sep 22 '26 17:09 nabi-ebrahimi

Proposal

What is the root cause of that problem?

Pinned/GBR rows are ordered by compareDisplayNames, which compares a precomputed sortKey with < / > and only reaches the collator when the two keys are identical:

https://github.com/Expensify/App/blob/ff03a5d7152dff4df170133e3c35fcac40075ff4/src/libs/SidebarUtils.ts#L517-L529

The key is the lowercased name with zero-padded digit runs, built deliberately without the collator in #87847:

https://github.com/Expensify/App/blob/ff03a5d7152dff4df170133e3c35fcac40075ff4/src/libs/SidebarUtils.ts#L119-L128

< on strings compares UTF-16 code units, so ñ (U+00F1) sorts after z and "Ñu Safari" goes to the bottom. A unit test locks that in:

https://github.com/Expensify/App/blob/ff03a5d7152dff4df170133e3c35fcac40075ff4/tests/unit/SidebarUtilsTest.ts#L4360-L4366

Option 3 is the right call, and this update is scoped to it. Two things about it still need deciding before it can be implemented, and one is a product question rather than a technical one.

1. Folding reorders the example in this issue, so the stated Expected Result cannot be met. Folding strips the combining mark, so "Ñu Safari" becomes nu safari, and the space (U+0020) sorts before e. I applied the fold in buildSortKey and ran the three names from the issue through _buildSortKey and _sortCategorizedReports, with each locale's collator passed in as the tie-break:

Expected Result in this issue   : Nuevo Budget | Ñu Safari | Zote Report
current main                    : Nuevo Budget | Zote Report | Ñu Safari
with folding, en collator       : Ñu Safari | Nuevo Budget | Zote Report
with folding, es collator       : Ñu Safari | Nuevo Budget | Zote Report

The two locales give the same answer, and that is the part worth being precise about: once folding makes the two keys differ, compareDisplayNames returns on the < comparison and the collator is never consulted. The tie-break only runs on identical keys. So this ordering is not the Spanish result or the English result — the locale has no effect on it at all, and there is no locale setting under which option 3 produces the Expected Result as written.

The order it does produce is correct English alphabetization, and ñ is n with a diacritic in ten of the eleven supported locales; Spanish is the one that treats it as a separate letter after n, which is what the Expected Result was written from.

So this needs one line from product: the Expected Result should be updated to Ñu Safari | Nuevo Budget | Zote Report, with the understanding that Spanish users will see ñ ordered as n. That is the behaviour option 3 delivers in every locale, it is correct for ten of the eleven supported locales, and it fixes the reported bug — accented names no longer collect at the bottom. Without that line, a correct implementation fails QA against the text of the issue.

It also decides the replacement for the test above, which currently asserts the opposite of what option 3 does.

2. The performance figures on record are not reachable, and the ASCII fast path is worth about four times the added cost. sortKeyCache.clear() is the first statement of categorizeReportsForLHN:

https://github.com/Expensify/App/blob/ff03a5d7152dff4df170133e3c35fcac40075ff4/src/libs/SidebarUtils.ts#L433-L439

The cache therefore only serves repeated lookups inside a single pass — every LHN recomputation rebuilds every key from scratch, so there is no warm-cache state across passes to measure. Timing the real buildSortKey over 10,000 unique names at 95% ASCII, so no lookup ever hits the cache, min of 21 runs and two independent runs of each variant:

current main                            min 3.28 / 3.37 ms
fold behind an isAscii guard            min 3.50 / 3.51 ms   (+0.2 ms, +6%)
fold with unconditional .normalize()    min 4.29 / 4.22 ms   (+0.9 ms, +28%)

Both variants produce byte-identical keys and identical ordering, so the guard is free correctness: it cuts the added cost roughly fourfold. That is Node, not Hermes, so it does not answer the request to measure on a large account — Hermes implements normalize separately and is the engine that decides this. What it does settle is that folding is affordable and that essentially all of the cost sits in the non-ASCII branch, which an account hits rarely.

On the test suite: with the fold applied, tests/unit/SidebarUtilsTest.ts fails exactly one test, the code-point assertion at line 4360 that encodes today's behaviour, and the other 109 pass. Nothing else regresses.

And the ligature map does its job. Running a mixed set through the real sort path confirms the inconsistency that was the main objection to option 3 is gone once the non-decomposing letters are expanded:

current main : Alpha Team | Nuevo Budget | Zote Report | ßeta | Æon | Øresund | Čapek | Łukasz
option 3     : Æon | Alpha Team | Čapek | Łukasz | Nuevo Budget | Øresund | ßeta | Zote Report

Every name lands in correct alphabetical position; nothing is stranded after Zote.

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

Put the fold in StringUtils beside normalizeAccents, not in buildSortKey. The guard that makes this cheap is isAscii, and it is module-private, so SidebarUtils cannot reuse it:

https://github.com/Expensify/App/blob/ff03a5d7152dff4df170133e3c35fcac40075ff4/src/libs/StringUtils/index.ts#L102-L120

A sibling helper — normalizeAccents plus the ligature expansion, behind the same single isAscii early return — gives one owner for the folding grammar, one place the fast path lives, and no NFD call on ASCII names. buildSortKey then stays three lines and keeps its existing digit padding.

The ligature expansion is needed because NFD does not touch letters that are not base-plus-mark: ß æ ø œ đ ð þ ł all come back unchanged, which is why they are the characters with no simple equivalent. Expanding them by their standard alphabetical equivalents (ß→ss, æ→ae, œ→oe, ø→o, đ/ð→d, þ→th, ł→l) removes the inconsistency that was the main objection to option 3, and the lowercase has to happen before the expansion, or the map has to carry both cases, so Ø and ø produce the same key. Anything left out of that map still sorts after z — ı, ħ, ŋ, ĸ, ŧ are the remaining Latin-script cases worth adding.

No change to compareDisplayNames. Folding makes keys collide for real pairs — José and Jose produce the same key — and the tied-key branch already falls back to localeCompare, which is the correct tie-break and costs a collator call only on an actual collision. That path is currently almost unreachable and becomes genuinely useful here, so it needs no new work.

Tests. Replace the code-point assertion at SidebarUtilsTest.ts:4360 with the order product confirms, keyed to the three names in this issue so QA and the unit test agree. Add: Øresund, ßeta, Æon, Łukasz sorting among ASCII names rather than after Zote; Ø and ø producing the same key; José/Jose tying on the key and resolving through the collator; and the existing digit-run cases unchanged.

What alternative solutions did you explore? (Optional)

  • Locale-aware ordering via the collator. This was my original recommendation and it is the only thing that gives Spanish users Nuevo, Ñu, Zote while giving English users Ñu, Nuevo, Zote. It was declined for hot-path cost, and I agree with that trade-off for pinned-chat ordering now that the folded result is understood to be correct for ten of eleven locales — the remaining gap is a product expectation, not a defect.
  • Keeping the combining mark instead of stripping it. Matches the text of this issue without a product decision, but it ranks an accented letter after every unaccented letter at whichever position decides the comparison, so Ñu sorts after Nz and Éclair after Ezra. That is wrong in every locale, Spanish included: Spanish treats é as e at the primary level and only ñ as a letter of its own.
  • Leaving the ligatures unmapped. Keeps the change to NFD alone, but ø, ß, æ and ł names stay at the bottom, which is the reported bug for Danish, Norwegian, German and Polish names.

preston-56 avatar Sep 22 '26 17:09 preston-56

Proposal

What is the root cause of that problem?

The LHN comparator never reaches the locale collator. It compares a precomputed sortKey with the plain < / > operators and only falls through to localeCompare when the two keys are exactly equal, which cannot happen for two different names:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/src/libs/SidebarUtils.ts#L517-L529

The key is the lowercased name with digit runs zero-padded:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/src/libs/SidebarUtils.ts#L119-L128

< / > on strings compare UTF-16 code units, so ñ (241) is greater than z (122). I ran the three reported names through _sortCategorizedReports on current main and got the reported order:

● BUG CASE: an accented pinned name is not ordered past Z (es locale)

expect(received).toEqual(expected) // deep equality

    - Expected  - 1
    + Received  + 1

      Array [
        "Nuevo Budget",
    -   "Ñu Safari",
        "Zote Report",
    +   "Ñu Safari",
      ]

The prediction that pins the cause. If it is code-unit ordering rather than "accents go last", two accented names must also be ordered against each other by code point. I added Über Trip (ü = 252) and checked on unfixed main: the order is Nuevo Budget | Zote Report | Ñu Safari | Über Trip — Ñu beats Über at 241 < 252. That passes, so the cause is the operator, not accent handling.

It is not specific to pinned chats. The same comparator sorts the pinned/GBR, error and draft groups, the non-archived and archived groups in focus mode, and breaks date ties in default mode:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/src/libs/SidebarUtils.ts#L542-L555

Why no test caught it. A test asserts the broken ordering as intended behaviour:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/tests/unit/SidebarUtilsTest.ts#L4325-L4332

And every existing sortCategorizedReports case passes bare String.prototype.localeCompare as the collator, without the options production uses, and none of them uses a non-ASCII name:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/tests/unit/SidebarUtilsTest.ts#L4181-L4182

A second mechanism I killed. I first suspected the collator itself, since getCollator keys on the user locale and a missing locale collates as root:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/src/libs/CollatorUtils.ts#L6

I measured root, en and es with those exact options: all three place Ñu Safari among the N names. The collator was never wrong — it is never called.

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

Compare the names, not the key:

const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
    if (!a.displayName || !b.displayName) {
        return 0;
    }
    return localeCompare(a.displayName, b.displayName);
};

That is the whole fix — seven lines deleted in one function. COLLATOR_OPTIONS already sets numeric: true, so the zero-padding is redundant, and caseFirst: 'upper' is what the key could only reach by tying.

I applied it and re-ran: my five cases go green, SidebarUtilsTest.ts stays at 108/108 passing with no test edits, and reverting the seven lines turns the bug cases red again.

Leave buildSortKey and the sortKey field in place in this PR. They become dead, but deleting them means dropping the _buildSortKey export and the sortKey field from MiniReport, which touches 40 sortKey references in SidebarUtilsTest.ts and deletes three of its cases. Better as a separate cleanup.

On the optimization this gives up (#87847). sortKeyCache is cleared at the top of every categorizeReportsForLHN call, so the "computed at most once per unique display name" comment does not hold across recomputes — each recompute rebuilds all N keys with a regex pass. I benchmarked both paths with the repo's collator options, 20 runs each:

https://github.com/Expensify/App/blob/fe2089300bf2e300b9d419b98d04bf69a177f8b8/src/libs/SidebarUtils.ts#L437-L439

N=100    sortKey 0.13ms   collator 0.08ms
N=500    sortKey 0.25ms   collator 0.58ms
N=2000   sortKey 0.99ms   collator 2.91ms

At LHN sizes the collator is the faster of the two; the cost only shows up in the thousands, at about 2ms.

What I want to be straight about. The resulting order depends on the viewer's locale, and in English it is not the literal Expected Result. I measured the reported names:

  • es → Nuevo Budget | Ñu Safari | Zote Report — the issue's expected order
  • en → Ñu Safari | Nuevo Budget | Zote Report

Both are correct for their locale: in en, ñ and n share a primary weight, so Ñu compares against Nuev and the space sorts before e. Nothing is pushed past Z any more, which is the defect. Worth agreeing before QA retests in English.

Regression safety — each of these came out identical before and after the fix: Report 1 | Report 2 | Report 10, Alpha | alpha, and Alpha | Charlie | Zebra. The empty-display-name guard is kept and now runs first, and compareNonArchivedDefault still sorts by lastVisibleActionCreated, calling this comparator only on a date tie.

Tests — in SidebarUtilsTest.ts, with a real Intl.Collator built from COLLATOR_OPTIONS rather than the bare localeCompare mock:

  1. Pinned Nuevo Budget / Ñu Safari / Zote Report under es → the issue's expected order. Red on main with the failure quoted above.
  2. The same three under en → Ñu Safari first, so the locale dependence is pinned rather than rediscovered later.
  3. Control: Report 1 / Report 2 / Report 10, proving the padding removal is safe.
  4. Control: Alpha / alpha.

What alternative solutions did you explore? (Optional)

Return an empty sort key for non-ASCII names and fall through to the collator for them. I applied this one and ran the suite: it fails the existing accented-name test with Expected: true, Received: false, because buildSortKey('Café') becomes '' and '' > 'cafe' is false. It also stitches two different orderings into one comparator, so transitivity across a mixed list is not guaranteed, and Array.prototype.sort is undefined for a non-transitive comparator.

Strip diacritics into the key (normalize('NFD'), drop combining marks). Keeps one fast path and stops Ñ sorting after Z, but it is locale-agnostic: Spanish Ñ is a letter after N, Swedish å ä ö belong at the end of the alphabet, and Cyrillic, Greek and CJK names stay in code-point order.

Sort ASCII names by key, non-ASCII by collator, then merge. Collator calls only at the merge boundary, but that is a lot of machinery for the ~2ms the benchmark says it saves.

yusufdeveloper2903 avatar Sep 22 '26 17:09 yusufdeveloper2903

Proposal

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

Pinned LHN rows whose names contain a locale-specific letter land in the wrong place: with "Nuevo Budget", "Ñu Safari" and "Zote Report" pinned, the LHN renders "Nuevo Budget, Zote Report, Ñu Safari" — "Ñ" is pushed below every ASCII name instead of sorting next to "N". The same comparator also orders the error, draft and (in focus mode) the non-archived and archived groups, so the bug is not limited to pinned rows.

What is the root cause of that problem?

compareDisplayNames inside sortCategorizedReports (src/libs/SidebarUtils.ts) does not compare the display names. It compares the precomputed sortKey with the plain < / > operators and only calls the injected localeCompare when the two keys are exactly equal:

if (a.sortKey < b.sortKey) { return -1; }
if (a.sortKey > b.sortKey) { return 1; }
// Sort keys tied — fall back to Collator for locale-correct ordering
return localeCompare(a.displayName, b.displayName);

< / > on strings compare UTF-16 code units. buildSortKey only lowercases the name and zero-pads digit runs, so Ñ stays U+00F1 (241) while z is U+007A (122) and "ñu safari" > "zote report". Two distinct names never produce equal keys, so the collator branch is unreachable and the code-unit order always wins. That reproduces the reported order exactly.

Two further points that matter for choosing the fix, because they rule out "keep the fast path for ASCII-only names":

  1. The key disagrees with the app collator even inside pure ASCII. ~Team vs Ateam: the key says ~Team last (~ is U+007E, after z), the collator in CollatorUtils says ~Team first. So a per-group "all names are ASCII → use the key" switch would still order those rows differently from every other list in the app, and adding one accented chat to the same bucket would silently reshuffle the unrelated ASCII rows.
  2. NUMERIC_PAD_WIDTH is 15 and padStart(15) is a no-op on a longer digit run, so Invoice 1234567890123456 (16 digits) sorts after Invoice 999999999999999 (15 digits) — a second ordering defect in the same helper, with no accents involved.

The key also does not amortize: categorizeReportsForLHN calls sortKeyCache.clear() on entry, so every LHN recompute pays one toLowerCase() plus one global-regex replaceAll per report before a single comparison runs.

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

In src/libs/SidebarUtils.ts, order display names with the locale collator that is already passed into sortCategorizedReports:

// Always order display names with the locale Collator. Comparing normalized keys with < / > orders by UTF-16 code unit,
// which puts every non-ASCII letter ("Ñ", "Å", Cyrillic, CJK, …) after "Z" instead of next to its base letter.
const compareDisplayNames = (a: MiniReport, b: MiniReport) => {
    if (!a.displayName || !b.displayName) {
        return 0;
    }
    return localeCompare(a.displayName, b.displayName);
};

With the key path gone, buildSortKey, sortKeyCache, NUMERIC_PAD_WIDTH, DIGIT_SEQUENCE, the sortKeyCache.clear() call, the sortKey field on MiniReport, its assignment in categorizeReportsForLHN and the buildSortKey as _buildSortKey test export are dead and are removed. No signature changes, no new imports, nothing outside SidebarUtils.ts reads them.

Why this is safe rather than a straight perf regression:

  • localeCompare here is the LocaleContextProvider wrapper over getCollator(currentLocale).compare, and CollatorUtils caches one Intl.Collator per locale — the expensive part (building the collator) is not repeated per comparison.
  • That collator is built with numeric: true, so Report 2 still sorts before Report 10 without the zero-padding, and caseFirst: 'upper' is now respected instead of being erased by toLowerCase().
  • Measured locally on 5,000 names sorted 20 times: key path 116 ms, cached collator 139 ms — about 1 ms per recompute in the focus-mode worst case where the entire non-archived list is name-sorted. Against that we drop two string allocations per report per recompute that the cleared cache guaranteed we paid anyway. In default mode the name comparator only runs on lastVisibleActionCreated ties.

Regression note for the reviewer: the comparator now depends entirely on the injected localeCompare. The LHN always renders under LocaleContextProvider (useSidebarOrderedReports takes it from useLocalize), so it is the real collator; the only no-op localeCompare: () => 0 is the default context value, which is not what the sidebar consumes.

Tests: tests/unit/SidebarUtilsTest.ts drops the _buildSortKey import and the sortKey literals from the MiniReport fixtures, and the buildSortKey describe block is removed — one of its cases asserts that accented names must sort "by Unicode code point, not locale-aware order", i.e. it locks in exactly the bug being reported, so it has to go rather than be tweaked. New cases cover the reported data end to end through SidebarUtils.sortReportsToDisplayInLHN.

One detail worth stating because the "Expected Result" in the report is locale-specific: with the Spanish collator the order is exactly Nuevo Budget, Ñu Safari, Zote Report (Ñ is its own letter after N); with the English collator Ñ folds onto N, so Ñu Safari sorts just before Nuevo Budget. In both locales Ñ sits with the N names and never after Z, which is the invariant the fix guarantees.

Verified locally: the change passes the test in tests/unit/SidebarUtilsTest.ts, and that test fails on main without it.

What specific scenarios should we cover in automated tests?

  • Three pinned reports named Zote Report, Nuevo Budget and Ñu Safari sorted through SidebarUtils.sortReportsToDisplayInLHN with the Spanish collator return the IDs in the order Nuevo Budget, Ñu Safari, Zote Report (this is the test added; it returns Nuevo Budget, Zote Report, Ñu Safari on unmodified code).
  • The same three pinned reports sorted with the English collator put Ñu Safari before Zote Report and leave Zote Report last, so the accented name is never pushed to the bottom regardless of locale.
  • Two pinned reports named Report 10 and Report 2 sorted through sortReportsToDisplayInLHN return Report 2 first, proving the collator's numeric: true replaces the removed zero-padding.
  • The existing sortCategorizedReports and combineReportCategories cases keep passing with MiniReport fixtures that no longer carry a sortKey field.
  • Focus mode (PRIORITY_MODE.GSD) with non-archived reports named with accented and ASCII letters orders the whole list by the collator, since that group also uses compareDisplayNames.

What alternative solutions did you explore? (Optional)

Keep the key and switch comparators per group (use < / > when every name in the group is ASCII, collator otherwise). It avoids the non-transitivity of a per-pair fallback, but it keeps two real defects: ASCII names still sort differently from the collator (~Team vs Ateam), and the 15-digit padding bug survives. It also makes the order of ASCII rows depend on whether an unrelated accented chat happens to be in the same bucket, which is a worse failure mode than the one being fixed because it is silent.

Fall back to localeCompare only for pairs where one name is non-ASCII. Rejected: ASCII pairs would be ranked by code unit and mixed pairs by collation, which is non-transitive (~Team < Ñu Safari < Zote Report by collator, but ~Team > Zote Report by code unit), and Array.prototype.sort with a non-transitive comparator gives implementation-defined results.

Normalize the key to NFD (or strip diacritics) before comparing. Stripping marks maps ñ to n and loses locale rules — Spanish treats Ñ as a distinct letter after N, Swedish puts å/ä/ö at the end of the alphabet, and Polish orders ą between a and b. Keeping the combining marks happens to give the right answer for this particular trio but still orders Cyrillic, Greek and CJK by code point and keeps the padding defect, so it fixes the screenshot rather than the rule.

sangnv00452 avatar Sep 22 '26 17:09 sangnv00452