← Back to Pull requests

sort: bound collation-key precomputation per line #12144

Open
mattsu2020 opened this pull request with 179 lines diff across 3 files
View on GitHub
mattsu2020 mattsu2020 commented on May 04, 2026 12:40 UTC
Author

In UTF-8 locales, generating ICU collation keys for enormous lines can dominate sorting time. Precompute keys only for lines up to 16 MiB of input and compare larger lines lazily. Apply the limit per line so a chunk with many moderately long lines keeps reusable keys.

Closes #12138.

Diff: 179 lines (+159 / -20) across 3 files Reviewer: sylvestre Review duration: 308121m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.44) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.44 · 179 lines diff across 3 files
0.44
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.91 · 5 substantive comment(s)
0.91
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
89%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.311
Real PR Conversation Timeline
31 items
github-actions[bot] github-actions[bot] commented on May 04, 2026 13:06 UTC
Bot

<!-- gnu-comment-bot -->
GNU testsuite comparison:

Congrats! The gnu test tests/tail/follow-name is no longer failing!
Congrats! The gnu test tests/tail/pid-pipe is no longer failing!

codspeed[bot] codspeed[bot] commented on May 04, 2026 13:15 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will degrade performance by 13.11%

<details>
<summary><b>1 warning, 1 note</b></summary>

:warning: 29 benchmarks are dominated by system calls

> System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

> Learn more about system calls

> See affected benchmarks

:information_source: 1 benchmark has no flamegraph

> The flamegraph wasn't generated: most of the time was spent in runtime internals, which would leave nothing useful to analyze.

> See affected benchmarks

</details>

❌ 1 regressed benchmark
✅ 57 untouched benchmarks
⏩ 426 skipped benchmarks[^skipped]

[!WARNING]

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | CPU Simulation | ` sort_german_de_locale | 285.7 ms | 328.9 ms | -13.11% |

[!TIP]

Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.

---

<sub>Comparing <code>mattsu2020:fix_sort_performance</code> (71f605c) with <code>main</code> (293a724)[^unexpected-base]</sub>

<a href="https://app.codspeed.io/uutils/coreutils/branches/mattsu2020%3Afix_sort_performance?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 426 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
[^unexpected-base]: No successful run was found on <code>main</code> (2cb55db) during the generation of this report, so 293a724 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

xtqqczze xtqqczze commented on May 04, 2026 14:46 UTC
Contributor

Out of interest, why choose 1 MiB as the limit, rather than something lower like u16::MAX?

mattsu2020 mattsu2020 commented on May 04, 2026 23:23 UTC
Author

Out of interest, why choose 1 MiB as the limit, rather than something lower like u16::MAX?

Since measurements using 64 KiB showed performance that was at least equivalent for the issue workload, we will change the threshold to u16::MAX.

xtqqczze xtqqczze commented on May 04, 2026 23:29 UTC
Contributor

@mattsu2020 Could you also add a benchmark (in separate PR)?

mattsu2020 mattsu2020 commented on May 04, 2026 23:32 UTC
Author

@mattsu2020 Could you also add a benchmark (in separate PR)?

Sure, I’ll keep this PR focused on the fix and open a separate PR adding a benchmark for long-line locale collation.

sylvestre sylvestre commented on May 23, 2026 07:56 UTC
Contributor

Codspeed is not happy

mattsu2020 mattsu2020 commented on May 23, 2026 10:00 UTC
Author

Codspeed is not happy

The memory usage is within expectations, but I'll look into the CPU.

sylvestre sylvestre commented on code on Nov 14, 2026 13:35 UTC
Code Review
.github/workflows/benchmarks.yml:1
@@ -116,6 +116,8 @@ jobs:
         uses: CodSpeedHQ/action@v5
         env:
           CODSPEED_LOG: debug
+          # The long-line sort benchmarks start a fresh process for each run.
+          CODSPEED_SIMULATION_TRACK_SUBPROCESS: ${{ matrix.package == 'uu_sort' && 'true' || 'false' }}

seems unrelated

sylvestre sylvestre commented on code on Nov 14, 2026 13:39 UTC
Code Review
src/uu/sort/benches/sort_locale_utf8_bench.rs:1
@@ -7,8 +7,13 @@
 //!
 //! Note: The locale is set in `main()` BEFORE any benchmark runs because
 //! the locale is cached on first access via `OnceLock` and cannot be changed afterwards.
+//!
+//! Subprocess benchmarks have distinct names from the former in-process versions:

seems unrelated

sylvestre sylvestre commented on code on Nov 14, 2026 13:39 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -4086,6 +4086,64 @@ fn test_sort_locale_punctuation() {
     }
 }
 
+#[test]
+fn test_locale_collation_long_lines() {
+    // Moderately long lines still reuse collation keys.
+    // Interleave them with short lines and exercise case and accent ordering.
+    const LONG: usize = 70_000;
+
+    let long_e_acute = "é".repeat(LONG / 2);
+    let long_upper_a = "A".repeat(LONG);
+    let long_lower_a = "a".repeat(LONG);
+    let input = format!("f\n{long_upper_a}\nb\n{long_lower_a}\n{long_e_acute}\na\n");
+    // Locale order: a < aa… < AA… < b < éé… < f.
+    // Byte order would instead yield AA… < a < aa… < b < f < éé….
+    let expected = format!("a\n{long_lower_a}\n{long_upper_a}\nb\n{long_e_acute}\nf\n");
+
+    new_ucmd!()
+        .env("LC_ALL", "en_US.UTF-8")
+        .pipe_in(input)
+        .succeeds()
+        .stdout_is(expected);
+}
+
+#[test]
+fn test_locale_collation_long_line_boundary() {

16 MiB + 16 MiB of input in a debug build, is this one really needed on top of the unit test that already checks the limit?

sylvestre sylvestre commented on code on Nov 14, 2026 13:39 UTC
Code Review
src/uu/sort/src/chunks.rs:1
@@ -24,9 +24,21 @@ use uucore::numeric_str_cmp::NumInfo;
 use crate::{GeneralBigDecimalParseResult, GlobalSettings, Line, SortError};
 
 const ALLOC_CHUNK_SIZE: usize = 64 * 1024;
+const COLLATION_KEY_SKIPPED: usize = 1usize << (usize::BITS - 1);

the high-bit tagging is a bit too clever, a separate Vec<bool> or an Option would be easier to read, no?

sylvestre sylvestre commented on code on Nov 14, 2026 13:39 UTC
Code Review
src/uu/sort/src/chunks.rs:1
@@ -314,6 +348,9 @@ fn parse_lines<'a>(
     if settings.precomputed.whole_line_numeric {
         line_data.line_num_floats.reserve(estimated);
     }
+    if settings.precomputed.fast_locale_collation {
+        line_data.collation_key_ends.reserve(estimated);

seems unrelated to the limit, please move it to another pr

sylvestre sylvestre commented on Nov 14, 2026 13:39 UTC
Contributor

thanks for the PR!
The benchmark rewrite and the workflow change are still in: please move them to a separate PR, as agreed with xtqqczze, and keep this one to the per-line limit.
CodSpeed is red too, please have a look.
Please also squash the commits into one.

sylvestre sylvestre commented on code on Nov 14, 2026 13:39 UTC
Code Review
src/uu/sort/benches/sort_locale_utf8_bench.rs:1
@@ -138,20 +136,46 @@ fn sort_long_common_prefix_utf8_locale(bencher: Bencher) {
         data.push(b'\n');
     }
     let file_path = setup_test_file(&data);
-    let output_file = NamedTempFile::new().unwrap();
-    let output_path = output_file.path().to_str().unwrap().to_string();
+    bench_sort_file_utf8(bencher, &file_path, "64M");
+}
 
-    let args = [
-        "--parallel",
-        "1",
-        "-o",
-        &output_path,
-        file_path.to_str().unwrap(),
-    ];
-    black_box(run_util_function(uumain, &args));
-    bencher.bench(|| {
-        black_box(run_util_function(uumain, &args));
-    });
+/// Long lines differing only in case have equal primary collation weights.
+/// Reuse keys even when the input exceeds the former 16 MiB chunk budget.
+#[divan::bench(args = [128, 512, 1024])]
+fn sort_long_case_variants_utf8_locale(bencher: Bencher, num_lines: u64) {
+    let mut data = Vec::new();
+    for i in 0..num_lines {
+        let pattern = i.wrapping_mul(0x9e37_79b9_7f4a_7c15);
+        for bit in 0..64 {
+            data.push(if pattern & (1 << bit) == 0 {
+                b'a'
+            } else {
+                b'A'
+            });
+        }
+        data.extend(std::iter::repeat_n(b'a', 70_000 - 64));
+        data.push(b'\n');
+    }
+    let file_path = setup_test_file(&data);
+    bench_sort_file_utf8(bencher, &file_path, "256M");
+}
+
+fn bench_sort_file_utf8(bencher: Bencher, file_path: &Path, buffer_size: &str) {
+    let output_file = NamedTempFile::new().unwrap();
+    // Each run needs fresh locale/collator initialization. Repeated calls to

seems unrelated

mattsu2020 mattsu2020 commented on code on Nov 15, 2026 14:58 UTC
Code Review
src/uu/sort/benches/sort_locale_utf8_bench.rs:1
@@ -138,20 +136,46 @@ fn sort_long_common_prefix_utf8_locale(bencher: Bencher) {
         data.push(b'\n');
     }
     let file_path = setup_test_file(&data);
-    let output_file = NamedTempFile::new().unwrap();
-    let output_path = output_file.path().to_str().unwrap().to_string();
+    bench_sort_file_utf8(bencher, &file_path, "64M");
+}
 
-    let args = [
-        "--parallel",
-        "1",
-        "-o",
-        &output_path,
-        file_path.to_str().unwrap(),
-    ];
-    black_box(run_util_function(uumain, &args));
-    bencher.bench(|| {
-        black_box(run_util_function(uumain, &args));
-    });
+/// Long lines differing only in case have equal primary collation weights.
+/// Reuse keys even when the input exceeds the former 16 MiB chunk budget.
+#[divan::bench(args = [128, 512, 1024])]
+fn sort_long_case_variants_utf8_locale(bencher: Bencher, num_lines: u64) {
+    let mut data = Vec::new();
+    for i in 0..num_lines {
+        let pattern = i.wrapping_mul(0x9e37_79b9_7f4a_7c15);
+        for bit in 0..64 {
+            data.push(if pattern & (1 << bit) == 0 {
+                b'a'
+            } else {
+                b'A'
+            });
+        }
+        data.extend(std::iter::repeat_n(b'a', 70_000 - 64));
+        data.push(b'\n');
+    }
+    let file_path = setup_test_file(&data);
+    bench_sort_file_utf8(bencher, &file_path, "256M");
+}
+
+fn bench_sort_file_utf8(bencher: Bencher, file_path: &Path, buffer_size: &str) {
+    let output_file = NamedTempFile::new().unwrap();
+    // Each run needs fresh locale/collator initialization. Repeated calls to

fixed it

mattsu2020 mattsu2020 commented on code on Nov 15, 2026 14:58 UTC
Code Review
src/uu/sort/benches/sort_locale_utf8_bench.rs:1
@@ -7,8 +7,13 @@
 //!
 //! Note: The locale is set in `main()` BEFORE any benchmark runs because
 //! the locale is cached on first access via `OnceLock` and cannot be changed afterwards.
+//!
+//! Subprocess benchmarks have distinct names from the former in-process versions:

fixed it

mattsu2020 mattsu2020 commented on code on Nov 15, 2026 14:59 UTC
Code Review
.github/workflows/benchmarks.yml:1
@@ -116,6 +116,8 @@ jobs:
         uses: CodSpeedHQ/action@v5
         env:
           CODSPEED_LOG: debug
+          # The long-line sort benchmarks start a fresh process for each run.
+          CODSPEED_SIMULATION_TRACK_SUBPROCESS: ${{ matrix.package == 'uu_sort' && 'true' || 'false' }}

fixed it

mattsu2020 mattsu2020 commented on code on Nov 16, 2026 11:17 UTC
Code Review
src/uu/sort/src/chunks.rs:1
@@ -314,6 +348,9 @@ fn parse_lines<'a>(
     if settings.precomputed.whole_line_numeric {
         line_data.line_num_floats.reserve(estimated);
     }
+    if settings.precomputed.fast_locale_collation {
+        line_data.collation_key_ends.reserve(estimated);

fixed it

mattsu2020 mattsu2020 commented on code on Nov 16, 2026 11:17 UTC
Code Review
src/uu/sort/src/chunks.rs:1
@@ -24,9 +24,21 @@ use uucore::numeric_str_cmp::NumInfo;
 use crate::{GeneralBigDecimalParseResult, GlobalSettings, Line, SortError};
 
 const ALLOC_CHUNK_SIZE: usize = 64 * 1024;
+const COLLATION_KEY_SKIPPED: usize = 1usize << (usize::BITS - 1);

fixed it

mattsu2020 mattsu2020 commented on code on Nov 16, 2026 11:17 UTC
Code Review
tests/by-util/test_sort.rs:1
@@ -4086,6 +4086,64 @@ fn test_sort_locale_punctuation() {
     }
 }
 
+#[test]
+fn test_locale_collation_long_lines() {
+    // Moderately long lines still reuse collation keys.
+    // Interleave them with short lines and exercise case and accent ordering.
+    const LONG: usize = 70_000;
+
+    let long_e_acute = "é".repeat(LONG / 2);
+    let long_upper_a = "A".repeat(LONG);
+    let long_lower_a = "a".repeat(LONG);
+    let input = format!("f\n{long_upper_a}\nb\n{long_lower_a}\n{long_e_acute}\na\n");
+    // Locale order: a < aa… < AA… < b < éé… < f.
+    // Byte order would instead yield AA… < a < aa… < b < f < éé….
+    let expected = format!("a\n{long_lower_a}\n{long_upper_a}\nb\n{long_e_acute}\nf\n");
+
+    new_ucmd!()
+        .env("LC_ALL", "en_US.UTF-8")
+        .pipe_in(input)
+        .succeeds()
+        .stdout_is(expected);
+}
+
+#[test]
+fn test_locale_collation_long_line_boundary() {

fixed it

sylvestre sylvestre commented on code on Nov 17, 2026 07:30 UTC
Code Review
src/uu/sort/src/sort.rs:1
@@ -125,6 +125,11 @@ const POSITIVE: &u8 = &b'+';
 const MIN_AUTOMATIC_BUF_SIZE: usize = 512 * 1024; // 512 KiB
 const FALLBACK_AUTOMATIC_BUF_SIZE: usize = 32 * 1024 * 1024; // 32 MiB
 const MAX_AUTOMATIC_BUF_SIZE: usize = 1024 * 1024 * 1024; // 1 GiB
+// Bound the work spent on any one line, without dropping reusable keys when a
+// chunk contains many moderately long lines. ICU keys can exceed their input
+// size, so this is an input-length limit rather than a memory limit.
+#[cfg(feature = "i18n-collator")]
+const MAX_COLLATION_KEY_INPUT_BYTES: usize = 16 * 1024 * 1024;

you said to xtqqczze you would switch to u16::MAX, why 16 MiB now?

sylvestre sylvestre commented on code on Nov 17, 2026 07:30 UTC
Code Review
src/uu/sort/src/sort.rs:1
@@ -3414,6 +3439,71 @@ mod tests {
 
     use super::*;
 
+    #[cfg(feature = "i18n-collator")]
+    #[test]
+    fn test_long_collation_keys_do_not_share_a_budget() {
+        use uucore::i18n::collator::{CollatorOptions, try_init_collator};
+
+        try_init_collator(CollatorOptions::default());
+        let mut settings = GlobalSettings::default();
+        settings.selectors.push(FieldSelector::new(
+            KeyPosition {
+                field: 1,
+                char: 1,
+                ignore_blanks: false,
+            },
+            None,
+            KeySettings::default(),
+        ));
+        settings.init_precomputed(true);
+        let mut data = LineData::default();
+        let mut tokens = Vec::new();
+        let enormous = vec![b'b'; MAX_COLLATION_KEY_INPUT_BYTES + 1];
+        let enormous_line = Line::create(&enormous, 0, &mut data, &mut tokens, &settings);
+        assert!(data.collation_key(0).is_none());
+        assert!(data.collation_key_buffer.is_empty());
+        // Exceed the per-line limit in total with moderately long lines. Every
+        // line must retain its key to avoid repeated full collation.
+        let line = vec![b'A'; 70_000];
+        let mut expected = Vec::new();
+        compute_sort_key_utf8(&line, &mut expected);
+        let count = MAX_COLLATION_KEY_INPUT_BYTES / line.len() + 2;

there is no shared budget anymore, is this loop over ~240 lines of 70k still needed?

sylvestre sylvestre commented on code on Nov 17, 2026 07:30 UTC
Code Review
src/uu/sort/src/sort.rs:1
@@ -3414,6 +3439,71 @@ mod tests {
 
     use super::*;
 
+    #[cfg(feature = "i18n-collator")]
+    #[test]
+    fn test_long_collation_keys_do_not_share_a_budget() {
+        use uucore::i18n::collator::{CollatorOptions, try_init_collator};
+
+        try_init_collator(CollatorOptions::default());
+        let mut settings = GlobalSettings::default();
+        settings.selectors.push(FieldSelector::new(
+            KeyPosition {
+                field: 1,
+                char: 1,
+                ignore_blanks: false,
+            },
+            None,
+            KeySettings::default(),
+        ));
+        settings.init_precomputed(true);
+        let mut data = LineData::default();
+        let mut tokens = Vec::new();
+        let enormous = vec![b'b'; MAX_COLLATION_KEY_INPUT_BYTES + 1];
+        let enormous_line = Line::create(&enormous, 0, &mut data, &mut tokens, &settings);
+        assert!(data.collation_key(0).is_none());
+        assert!(data.collation_key_buffer.is_empty());
+        // Exceed the per-line limit in total with moderately long lines. Every
+        // line must retain its key to avoid repeated full collation.
+        let line = vec![b'A'; 70_000];
+        let mut expected = Vec::new();
+        compute_sort_key_utf8(&line, &mut expected);
+        let count = MAX_COLLATION_KEY_INPUT_BYTES / line.len() + 2;
+        for index in 1..=count {
+            Line::create(&line, index, &mut data, &mut tokens, &settings);
+            assert!(
+                data.collation_key(index)
+                    .is_some_and(|key| key == expected.as_slice()),
+                "missing or incorrect collation key for line {index}"
+            );
+        }
+        // A skipped key must not disturb the following arena offsets.
+        Line::create(&enormous, count + 1, &mut data, &mut tokens, &settings);
+        assert!(data.collation_key(count + 1).is_none());
+        let small_line = Line::create(b"a", count + 2, &mut data, &mut tokens, &settings);
+        expected.clear();
+        compute_sort_key_utf8(b"a", &mut expected);
+        assert_eq!(data.collation_key(count + 2), Some(expected.as_slice()));
+
+        let at_limit = vec![b'a'; MAX_COLLATION_KEY_INPUT_BYTES];

this computes a 16 MiB ICU key in a debug build, same concern as for the integration test. could you please make the limit smaller under cfg(test) or drop this case?

sylvestre sylvestre commented on code on Nov 17, 2026 07:30 UTC
Code Review
src/uu/sort/src/chunks.rs:1
@@ -57,18 +57,41 @@ pub struct LineData<'a> {
     pub collation_key_buffer: Vec<u8>,
     /// End offsets into `collation_key_buffer` for each line's sort key.
     pub collation_key_ends: Vec<usize>,
+    /// Whether each line uses lazy collation instead of a precomputed key.
+    pub collation_key_skipped: Vec<bool>,
 }
 
 impl LineData<'_> {
     /// Get the collation sort key for a line at the given index.
-    pub fn collation_key(&self, index: usize) -> &[u8] {
+    pub fn collation_key(&self, index: usize) -> Option<&[u8]> {
+        if self.collation_key_skipped[index] {
+            return None;
+        }
         let start = if index == 0 {
             0
         } else {
             self.collation_key_ends[index - 1]
         };
         let end = self.collation_key_ends[index];
-        &self.collation_key_buffer[start..end]
+        Some(&self.collation_key_buffer[start..end])
+    }
+
+    /// Record that the current end of `collation_key_buffer` terminates the
+    /// precomputed collation key of the line being appended.
+    #[inline]
+    pub fn push_collation_key_end(&mut self) {
+        let end = self.collation_key_buffer.len();
+        self.collation_key_ends.push(end);
+        self.collation_key_skipped.push(false);
+    }
+
+    /// Record a line whose collation key was not precomputed; `collation_key`
+    /// returns `None` for it so it is compared lazily via the locale collator.
+    #[inline]
+    pub fn push_skipped_collation_key(&mut self) {

almost the same as push_collation_key_end, could be one function taking a bool, no?

mattsu2020 mattsu2020 commented on code on Nov 17, 2026 08:08 UTC
Code Review
src/uu/sort/src/sort.rs:1
@@ -125,6 +125,11 @@ const POSITIVE: &u8 = &b'+';
 const MIN_AUTOMATIC_BUF_SIZE: usize = 512 * 1024; // 512 KiB
 const FALLBACK_AUTOMATIC_BUF_SIZE: usize = 32 * 1024 * 1024; // 32 MiB
 const MAX_AUTOMATIC_BUF_SIZE: usize = 1024 * 1024 * 1024; // 1 GiB
+// Bound the work spent on any one line, without dropping reusable keys when a
+// chunk contains many moderately long lines. ICU keys can exceed their input
+// size, so this is an input-length limit rather than a memory limit.
+#[cfg(feature = "i18n-collator")]
+const MAX_COLLATION_KEY_INPUT_BYTES: usize = 16 * 1024 * 1024;

During performance testing with u16::MAX, the entire line was rescanned.

mattsu2020 mattsu2020 commented on code on Nov 17, 2026 08:17 UTC
Code Review
src/uu/sort/src/chunks.rs:1
@@ -57,18 +57,41 @@ pub struct LineData<'a> {
     pub collation_key_buffer: Vec<u8>,
     /// End offsets into `collation_key_buffer` for each line's sort key.
     pub collation_key_ends: Vec<usize>,
+    /// Whether each line uses lazy collation instead of a precomputed key.
+    pub collation_key_skipped: Vec<bool>,
 }
 
 impl LineData<'_> {
     /// Get the collation sort key for a line at the given index.
-    pub fn collation_key(&self, index: usize) -> &[u8] {
+    pub fn collation_key(&self, index: usize) -> Option<&[u8]> {
+        if self.collation_key_skipped[index] {
+            return None;
+        }
         let start = if index == 0 {
             0
         } else {
             self.collation_key_ends[index - 1]
         };
         let end = self.collation_key_ends[index];
-        &self.collation_key_buffer[start..end]
+        Some(&self.collation_key_buffer[start..end])
+    }
+
+    /// Record that the current end of `collation_key_buffer` terminates the
+    /// precomputed collation key of the line being appended.
+    #[inline]
+    pub fn push_collation_key_end(&mut self) {
+        let end = self.collation_key_buffer.len();
+        self.collation_key_ends.push(end);
+        self.collation_key_skipped.push(false);
+    }
+
+    /// Record a line whose collation key was not precomputed; `collation_key`
+    /// returns `None` for it so it is compared lazily via the locale collator.
+    #[inline]
+    pub fn push_skipped_collation_key(&mut self) {

fixed it

mattsu2020 mattsu2020 commented on code on Nov 17, 2026 08:17 UTC
Code Review
src/uu/sort/src/sort.rs:1
@@ -3414,6 +3439,71 @@ mod tests {
 
     use super::*;
 
+    #[cfg(feature = "i18n-collator")]
+    #[test]
+    fn test_long_collation_keys_do_not_share_a_budget() {
+        use uucore::i18n::collator::{CollatorOptions, try_init_collator};
+
+        try_init_collator(CollatorOptions::default());
+        let mut settings = GlobalSettings::default();
+        settings.selectors.push(FieldSelector::new(
+            KeyPosition {
+                field: 1,
+                char: 1,
+                ignore_blanks: false,
+            },
+            None,
+            KeySettings::default(),
+        ));
+        settings.init_precomputed(true);
+        let mut data = LineData::default();
+        let mut tokens = Vec::new();
+        let enormous = vec![b'b'; MAX_COLLATION_KEY_INPUT_BYTES + 1];
+        let enormous_line = Line::create(&enormous, 0, &mut data, &mut tokens, &settings);
+        assert!(data.collation_key(0).is_none());
+        assert!(data.collation_key_buffer.is_empty());
+        // Exceed the per-line limit in total with moderately long lines. Every
+        // line must retain its key to avoid repeated full collation.
+        let line = vec![b'A'; 70_000];
+        let mut expected = Vec::new();
+        compute_sort_key_utf8(&line, &mut expected);
+        let count = MAX_COLLATION_KEY_INPUT_BYTES / line.len() + 2;

it's unnecessary. I've removed it.

mattsu2020 mattsu2020 commented on code on Nov 17, 2026 08:18 UTC
Code Review
src/uu/sort/src/sort.rs:1
@@ -3414,6 +3439,71 @@ mod tests {
 
     use super::*;
 
+    #[cfg(feature = "i18n-collator")]
+    #[test]
+    fn test_long_collation_keys_do_not_share_a_budget() {
+        use uucore::i18n::collator::{CollatorOptions, try_init_collator};
+
+        try_init_collator(CollatorOptions::default());
+        let mut settings = GlobalSettings::default();
+        settings.selectors.push(FieldSelector::new(
+            KeyPosition {
+                field: 1,
+                char: 1,
+                ignore_blanks: false,
+            },
+            None,
+            KeySettings::default(),
+        ));
+        settings.init_precomputed(true);
+        let mut data = LineData::default();
+        let mut tokens = Vec::new();
+        let enormous = vec![b'b'; MAX_COLLATION_KEY_INPUT_BYTES + 1];
+        let enormous_line = Line::create(&enormous, 0, &mut data, &mut tokens, &settings);
+        assert!(data.collation_key(0).is_none());
+        assert!(data.collation_key_buffer.is_empty());
+        // Exceed the per-line limit in total with moderately long lines. Every
+        // line must retain its key to avoid repeated full collation.
+        let line = vec![b'A'; 70_000];
+        let mut expected = Vec::new();
+        compute_sort_key_utf8(&line, &mut expected);
+        let count = MAX_COLLATION_KEY_INPUT_BYTES / line.len() + 2;
+        for index in 1..=count {
+            Line::create(&line, index, &mut data, &mut tokens, &settings);
+            assert!(
+                data.collation_key(index)
+                    .is_some_and(|key| key == expected.as_slice()),
+                "missing or incorrect collation key for line {index}"
+            );
+        }
+        // A skipped key must not disturb the following arena offsets.
+        Line::create(&enormous, count + 1, &mut data, &mut tokens, &settings);
+        assert!(data.collation_key(count + 1).is_none());
+        let small_line = Line::create(b"a", count + 2, &mut data, &mut tokens, &settings);
+        expected.clear();
+        compute_sort_key_utf8(b"a", &mut expected);
+        assert_eq!(data.collation_key(count + 2), Some(expected.as_slice()));
+
+        let at_limit = vec![b'a'; MAX_COLLATION_KEY_INPUT_BYTES];

Fixed it

github-actions[bot] github-actions[bot] commented on Nov 17, 2026 17:56 UTC
Bot

<!-- size-comment-bot -->
Binary size comparison:

Individual binary size comparison VS main (threshold: >=5% AND >=4 KB).

Total size of compared binaries: 155.49 MB (+104 KB, +0.07%)

Significant per-binary changes:
  env     1.20 MB ->    1.28 MB  (+80 KB, +6.51%)

Reviewers
Assignees
mattsu2020 mattsu2020
Labels
risk: low confidence: 89.5% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 44.0% (MEDIUM) · Higher = larger blast radius
44.0%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 89.5% · Lower = rushed or shallow review
89.5%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 4.6% · Safe to merge
4.6%