Skip to content

sort: cap automatic buffer size on 32-bit targets - #16901

Open
ChrisX101010 wants to merge 7 commits into
uutils:mainfrom
ChrisX101010:fix/16850-sort-32bit-buffer
Open

ChrisX101010 wants to merge 7 commits into
uutils:mainfrom
ChrisX101010:fix/16850-sort-32bit-buffer

Conversation

@ChrisX101010

Copy link
Copy Markdown
Contributor

Cap MAX_AUTOMATIC_BUF_SIZE at 32 MiB on 32-bit targets to leave enough virtual address space for per-line metadata and sorting scratch space, preventing out-of-memory crashes on large inputs. Updated the buffer hint unit tests to verify the 32-bit clamping behavior.

Closes #16850

@oech3

oech3 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

It seems this approach is same with rejected one (see #10290 (comment)).

Maybe, repeat .try_with_capacity() until it succeeds?

@ChrisX101010

Copy link
Copy Markdown
Contributor Author

Thanks for the suggestion! I've updated the PR to dynamically scale down the buffer allocation on memory pressure instead of relying on a static cap, and verified it against short lines, numeric/key sorts, -u/-z, and oversized single-line inputs (which now cleanly exit with status 2).

Comment thread src/uu/sort/src/ext_sort/threaded.rs Outdated
// kick things off with two reads
for _ in 0..2 {
// Reserve space for one read-ahead block before the chunks compete for memory.
let mut carry_over = if cfg!(target_pointer_width = "32") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we need this cfg!?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch, thanks! You're right—the cfg isn't strictly needed just to avoid a 64 KiB upfront allocation on 64-bit. I've removed it to keep the code simpler, and the tests passed on both 32-bit and 64-bit.

@codspeed

codspeed Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will degrade performance by 17.95%

1 warning, 1 note

⚠️ 121 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

ℹ️ 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

⚡ 5 improved benchmarks
❌ 29 regressed benchmarks
✅ 381 untouched benchmarks
⏩ 70 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Mode Benchmark BASE HEAD Efficiency
❌ Memory sort_numeric_utf8_locale 4.1 MB 7.3 MB -44.7%
❌ CPU Simulation sort_numeric_utf8_locale 36.2 ms 61.6 ms -41.32%
❌ Memory sort_ascii_utf8_locale 52.4 MB 85.5 MB -38.74%
❌ Memory sort_general_numeric[200000] 16.9 MB 27.3 MB -38.19%
❌ Memory sort_numeric[500000] 43.5 MB 69.7 MB -37.64%
❌ Memory check_sorted_utf8_locale 749.4 KB 1,098.8 KB -31.79%
❌ Memory sort_dictionary_order[500000] 20.6 MB 30.1 MB -31.59%
❌ Memory sort_mixed_data[500000] 20.6 MB 30.1 MB -31.59%
❌ Memory sort_case_insensitive[500000] 16.1 MB 23 MB -29.9%
❌ Memory sort_case_sensitive[500000] 16.1 MB 23 MB -29.9%
❌ Memory sort_key_field[500000] 28.2 MB 39.7 MB -28.93%
❌ Memory sort_ascii_only[500000] 20.6 MB 28.9 MB -28.86%
❌ Memory sort_reverse_locale[500000] 20.6 MB 28.8 MB -28.45%
❌ Memory sort_accented_data[500000] 20.6 MB 28.8 MB -28.45%
❌ Memory sort_ascii_c_locale 82 MB 103.7 MB -20.94%
❌ Memory sort_spill_to_tmp_files_utf8_locale 3.9 MB 4.9 MB -20.79%
❌ Memory sort_unique_locale[500000] 32.1 MB 39.3 MB -18.33%
❌ CPU Simulation check_sorted_utf8_locale 19.1 ms 22.1 ms -13.68%
❌ Memory sort_german_c_locale 1.9 MB 2.1 MB -12.36%
❌ CPU Simulation sort_mixed_utf8_locale 82.7 ms 90 ms -8.07%
... ... ... ... ... ...

ℹ️ Only the first 20 benchmarks are displayed. Go to the app to view all benchmarks.

Tip

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


Comparing ChrisX101010:fix/16850-sort-32bit-buffer (3ddb58e) with main (8efadca)

Open in CodSpeed

Footnotes

  1. 70 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. ↩

Comment thread src/uu/sort/src/sort.rs Outdated
// sorting scratch space. Leave more headroom on 32-bit targets, even when the
// machine reports plenty of physical memory.
#[cfg(target_pointer_width = "32")]
const MAX_AUTOMATIC_BUF_SIZE: usize = 32 * 1024 * 1024; // 32 MiB

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

you said the static cap was replaced by the retry, but it is still here?
please keep only one of the two

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Apologies for the confusion in my previous comment—I inadvertently left the 32 MiB static cap in place while adding the retry logic. Thanks for the thorough review; I'm updating the PR now to remove the static cap and target_pointer_width guards so the retry path runs on 64-bit CI too, clean up the chunks.rs logic, split the stable sort change into a separate PR, and add an address-space-limited integration test.

Comment thread src/uu/sort/src/chunks.rs Outdated
if buffer.len() < carry_over.len() {
// Leave room for bookkeeping and temporary-file I/O while sizing this chunk.
let mut headroom = Vec::<u8>::new();
if cfg!(target_pointer_width = "32") {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

why only 32-bit? with cfg!(target_pointer_width = "32") everywhere, the retry path is never run on our CI

Comment thread src/uu/sort/src/chunks.rs Outdated
let count = memchr_iter(separator, scanned_bytes).count();
line_count += count;
if !reserve(line_count) {
return if reserved_end == 0 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

almost the same block 3 times, could be dedup, no?

Comment thread src/uu/sort/src/chunks.rs Outdated
.try_reserve_exact(ALLOC_CHUNK_SIZE.saturating_sub(carry_over.len()))
.map_err(|_| out_of_memory())?;
headroom
.try_reserve_exact(1024 * 1024)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

where does this 1 MiB come from? please use a named const

Comment thread src/uu/sort/src/chunks.rs Outdated
&& {
#[cfg(feature = "i18n-collator")]
if precomputed.fast_locale_collation {
return try_reserve(&mut self.collation_key_ends, count);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

a return inside the && chain is hard to follow, could you please use plain ifs?

Comment thread src/uu/sort/src/chunks.rs Outdated
};
}
if count != 0 {
reserved_end = scanned + memrchr(separator, scanned_bytes).unwrap() + 1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

could use if let Some(pos) = memrchr(...) instead of the count check + unwrap

Comment thread src/uu/sort/src/sort.rs Outdated
#[cfg(not(target_os = "wasi"))]
#[cfg(all(not(target_os = "wasi"), target_pointer_width = "32"))]
// Retain stable ordering without a second allocation proportional to the chunk.
unsorted.par_sort_unstable_by(|a, b| cmp(a, b).then(a.index.cmp(&b.index)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this looks like a separate change, please split it into another pr

Comment thread src/uu/sort/src/buffer_hint.rs Outdated

#[cfg(target_pointer_width = "32")]
#[test]
fn automatic_memory_hint_leaves_room_for_line_metadata() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

please add a test in tests/by-util/test_sort.rs too (e.g. under a limited address space)

@sylvestre

Copy link
Copy Markdown
Contributor

thanks for working on this!
codspeed reports 2 regressions, see the comment on the truncate.

Comment thread src/uu/sort/src/chunks.rs Outdated
let mut buffer = std::mem::take(&mut recycled_chunk.buffer);
let limit = max_buffer_size.unwrap_or(buffer.len());
// Reusing an allocation should not skip the capacity checks while filling it.
buffer.truncate(ALLOC_CHUNK_SIZE.max(carry_over.len()));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

this now zero-fills the whole recycled buffer again on every read, on 64-bit too
is it the cause of the codspeed regression?

Comment thread src/uu/sort/src/chunks.rs Outdated
/// The remaining bytes must be copied to the start of the buffer for the next invocation,
/// if another invocation is necessary, which is determined by the other return value.
/// * Whether this function should be called again.
#[allow(clippy::too_many_arguments)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

could we avoid the #[allow] here, e.g. by grouping the reserve closure and limit?

Comment thread src/uu/sort/src/chunks.rs
}
buffer.resize(next_end, 0);
}
read_target = &mut buffer[end..next_end];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

with this window, each read() gets at most 64 KiB, so filling a 1 GiB buffer from a regular file takes ~16k syscalls instead of a few
does codspeed still show the regression on this head?

Comment thread src/uu/sort/src/chunks.rs Outdated
separator,
)?;
if read != 0 {
let (fitted, line_count) = fit_line_capacity(&buffer[..read], separator, |count| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

read_to_buffer already counted and reserved the lines, do we really need a second full memchr pass here in the common case?

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

GNU testsuite comparison:

Congrats! The gnu test tests/env/env is no longer failing!

@sylvestre
sylvestre force-pushed the fix/16850-sort-32bit-buffer branch from 2b3db45 to c0bd40a Compare November 27, 2026 18:58
@ChrisX101010

ChrisX101010 commented Nov 27, 2026 via email

Copy link
Copy Markdown
Contributor Author

@ChrisX101010

ChrisX101010 commented Nov 27, 2026 via email

Copy link
Copy Markdown
Contributor Author

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

sort: aborts with "memory allocation failed" on 32-bit when reading stdin

3 participants