From fc22957ad73ff23c2a57a1d8703fa0483a3c0917 Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 11:39:22 +0100 Subject: [PATCH 1/7] sort: cap automatic buffer size on 32-bit targets --- src/uu/sort/src/buffer_hint.rs | 12 +++++++++--- src/uu/sort/src/sort.rs | 6 ++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/uu/sort/src/buffer_hint.rs b/src/uu/sort/src/buffer_hint.rs index a6780941f89..95a01c423f6 100644 --- a/src/uu/sort/src/buffer_hint.rs +++ b/src/uu/sort/src/buffer_hint.rs @@ -105,6 +105,12 @@ fn physical_memory_bytes() -> Option { mod tests { use super::*; + #[cfg(target_pointer_width = "32")] + #[test] + fn automatic_memory_hint_leaves_room_for_line_metadata() { + assert_eq!(clamp_hint(u128::MAX), 32 * 1024 * 1024); + } + #[test] fn desired_buffer_matches_total_when_small() { let six_mebibytes = 6 * 1024 * 1024; @@ -114,11 +120,11 @@ mod tests { } #[test] - fn desired_buffer_caps_at_max_for_large_inputs() { + fn file_buffer_hint_caps_at_max_for_large_inputs() { let large = 256 * 1024 * 1024; // 256 MiB assert_eq!( - desired_file_buffer_bytes(large as u128), - crate::MAX_AUTOMATIC_BUF_SIZE as u128 + clamp_hint(desired_file_buffer_bytes(large as u128)), + crate::MAX_AUTOMATIC_BUF_SIZE ); } } diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index cec38b32a24..537d6427195 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -124,6 +124,12 @@ const POSITIVE: &u8 = &b'+'; // reasonably large chunks for typical workloads. const MIN_AUTOMATIC_BUF_SIZE: usize = 512 * 1024; // 512 KiB const FALLBACK_AUTOMATIC_BUF_SIZE: usize = 32 * 1024 * 1024; // 32 MiB +// The byte buffers share the process address space with per-line metadata and +// 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 +#[cfg(not(target_pointer_width = "32"))] const MAX_AUTOMATIC_BUF_SIZE: usize = 1024 * 1024 * 1024; // 1 GiB #[derive(Debug, thiserror::Error)] From 39f57b6f6950d11a10544b6a3f9d78380edf941a Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 12:08:27 +0100 Subject: [PATCH 2/7] sort: retry smaller chunks under memory pressure on 32-bit --- src/uu/sort/src/chunks.rs | 212 ++++++++++++++++++++++++--- src/uu/sort/src/ext_sort/threaded.rs | 22 ++- src/uu/sort/src/sort.rs | 5 +- 3 files changed, 213 insertions(+), 26 deletions(-) diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index e71b4f12114..c17e6ea1688 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -16,14 +16,14 @@ use std::{ sync::mpsc::SyncSender, }; -use memchr::memchr_iter; +use memchr::{memchr, memchr_iter, memrchr}; use self_cell::self_cell; use uucore::error::UResult; use uucore::numeric_str_cmp::NumInfo; use crate::{GeneralBigDecimalParseResult, GlobalSettings, Line, SortError}; -const ALLOC_CHUNK_SIZE: usize = 64 * 1024; +pub(crate) const ALLOC_CHUNK_SIZE: usize = 64 * 1024; const MAX_TOKEN_BUFFER_BYTES: usize = 4 * 1024 * 1024; const MAX_TOKEN_BUFFER_ELEMS: usize = MAX_TOKEN_BUFFER_BYTES / size_of::>(); @@ -155,6 +155,31 @@ impl RecycledChunk { buffer: vec![0; capacity], } } + + fn try_reserve_lines(&mut self, count: usize, settings: &GlobalSettings) -> bool { + let precomputed = &settings.precomputed; + try_reserve(&mut self.lines, count) + && try_reserve( + &mut self.selections, + count.saturating_mul(precomputed.selections_per_line), + ) + && try_reserve( + &mut self.num_infos, + count.saturating_mul(precomputed.num_infos_per_line), + ) + && try_reserve( + &mut self.parsed_floats, + count.saturating_mul(precomputed.floats_per_line), + ) + && (!precomputed.whole_line_numeric || try_reserve(&mut self.line_num_floats, count)) + && { + #[cfg(feature = "i18n-collator")] + if precomputed.fast_locale_collation { + return try_reserve(&mut self.collation_key_ends, count); + } + true + } + } } /// Read a chunk, parse lines and send them. @@ -181,7 +206,7 @@ impl RecycledChunk { #[allow(clippy::too_many_arguments)] pub fn read( sender: &SyncSender, - recycled_chunk: RecycledChunk, + mut recycled_chunk: RecycledChunk, max_buffer_size: Option, carry_over: &mut Vec, file: &mut T, @@ -189,35 +214,79 @@ pub fn read( separator: u8, settings: &GlobalSettings, ) -> UResult { - let RecycledChunk { - lines, - selections, - num_infos, - parsed_floats, - line_num_floats, - collation_key_buffer, - collation_key_ends, - mut token_buffer, - mut line_count_hint, - mut buffer, - } = recycled_chunk; - if buffer.len() < carry_over.len() { + // Leave room for bookkeeping and temporary-file I/O while sizing this chunk. + let mut headroom = Vec::::new(); + if cfg!(target_pointer_width = "32") { + headroom + .try_reserve_exact(1024 * 1024) + .map_err(|_| out_of_memory())?; + } + + let mut buffer = std::mem::take(&mut recycled_chunk.buffer); + let max_buffer_size = if cfg!(target_pointer_width = "32") { + 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())); + Some(limit) + } else { + max_buffer_size + }; + if let Some(additional) = carry_over + .len() + .checked_sub(buffer.len()) + .filter(|&size| size > 0) + { + if cfg!(target_pointer_width = "32") && !try_reserve(&mut buffer, additional) { + return Err(out_of_memory().into()); + } // Separate carry_over and copy them to avoid cost of 0 fill buffer buffer.extend_from_slice(&carry_over[buffer.len()..]); } buffer[..carry_over.len()].copy_from_slice(carry_over); - let (read, should_continue) = read_to_buffer( + let (mut read, mut should_continue) = read_to_buffer( file, next_files, &mut buffer, + |count| recycled_chunk.try_reserve_lines(count, settings), max_buffer_size, carry_over.len(), separator, )?; + // At EOF, bytes after `read` are unused buffer space. Otherwise they + // include the partial record that must be carried into the next read. + let filled = if should_continue { buffer.len() } else { read }; + if read != 0 && cfg!(target_pointer_width = "32") { + let (fitted, line_count) = fit_line_capacity(&buffer[..read], separator, |count| { + recycled_chunk.try_reserve_lines(count, settings) + })?; + should_continue |= fitted < read; + read = fitted; + recycled_chunk.line_count_hint = line_count; + } carry_over.clear(); - carry_over.extend_from_slice(&buffer[read..]); + if should_continue { + carry_over + .try_reserve_exact(filled - read) + .map_err(|_| out_of_memory())?; + carry_over.extend_from_slice(&buffer[read..filled]); + } + + drop(headroom); if read != 0 { + let RecycledChunk { + lines, + selections, + num_infos, + parsed_floats, + line_num_floats, + collation_key_buffer, + collation_key_ends, + mut token_buffer, + line_count_hint, + .. + } = recycled_chunk; + let mut line_count_hint = line_count_hint; let payload: UResult = Chunk::try_new(buffer, |buffer| { let selections = unsafe { // SAFETY: It is safe to transmute to an empty vector of selections with shorter lifetime. @@ -259,6 +328,40 @@ pub fn read( Ok(should_continue) } +/// Find a prefix whose line descriptors fit, leaving whole records for the next read. +fn fit_line_capacity( + input: &[u8], + separator: u8, + mut reserve: impl FnMut(usize) -> bool, +) -> UResult<(usize, usize)> { + let mut end = input.len(); + loop { + let chunk = &input[..end]; + let contents = chunk.strip_suffix(&[separator]).unwrap_or(chunk); + let count = memchr_iter(separator, contents).count() + 1; + if reserve(count) { + return Ok((end, count)); + } + + // The last byte is excluded so each retry makes progress and the + // suffix can always begin at a record boundary. + let (before, after) = chunk[..end - 1].split_at((end - 1) / 2); + let split = memrchr(separator, before) + .or_else(|| memchr(separator, after).map(|index| before.len() + index)); + end = split.ok_or_else(out_of_memory)? + 1; + } +} + +fn try_reserve(buffer: &mut Vec, additional: usize) -> bool { + buffer.try_reserve(additional).is_ok() || buffer.try_reserve_exact(additional).is_ok() +} + +fn out_of_memory() -> SortError { + SortError::ChunkReadFailed { + error: ErrorKind::OutOfMemory.into(), + } +} + /// Split `read` into `Line`s, and add them to `lines`. fn parse_lines<'a>( read: &'a [u8], @@ -353,10 +456,12 @@ fn parse_lines<'a>( /// 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)] fn read_to_buffer( file: &mut T, next_files: &mut impl Iterator>, buffer: &mut Vec, + mut reserve: impl FnMut(usize) -> bool, max_buffer_size: Option, start_offset: usize, separator: u8, @@ -364,14 +469,46 @@ fn read_to_buffer( let mut read_target = &mut buffer[start_offset..]; let mut newline_search_offset = 0; let mut found_newline = false; + let mut scanned = 0; + let mut line_count = 0; + let mut reserved_end = 0; loop { match file.read(read_target) { Ok(0) => { if read_target.is_empty() { + // Reserve line descriptors before growing the byte buffer again. + // Under pressure, spill the prefix we already reserved rather + // than buffering a large suffix that would need another allocation. + if cfg!(target_pointer_width = "32") { + let scanned_bytes = &buffer[scanned..]; + let count = memchr_iter(separator, scanned_bytes).count(); + line_count += count; + if !reserve(line_count) { + return if reserved_end == 0 { + Err(out_of_memory().into()) + } else { + Ok((reserved_end, true)) + }; + } + if count != 0 { + reserved_end = scanned + memrchr(separator, scanned_bytes).unwrap() + 1; + } + scanned = buffer.len(); + } + // chunk is full if max_buffer_size.is_some_and(|max_buf_size| max_buf_size > buffer.len()) { // we can grow the buffer let prev_len = buffer.len(); + if cfg!(target_pointer_width = "32") + && !try_reserve(buffer, ALLOC_CHUNK_SIZE) + { + return if reserved_end == 0 { + Err(out_of_memory().into()) + } else { + Ok((reserved_end, true)) + }; + } buffer.resize(prev_len + ALLOC_CHUNK_SIZE, 0); read_target = &mut buffer[prev_len..]; continue; @@ -390,8 +527,15 @@ fn read_to_buffer( found_newline = true; } - // We need to read more lines + // We need to read more lines. let len = buffer.len(); + if cfg!(target_pointer_width = "32") && !try_reserve(buffer, ALLOC_CHUNK_SIZE) { + return if reserved_end == 0 { + Err(out_of_memory().into()) + } else { + Ok((reserved_end, true)) + }; + } buffer.resize(len + ALLOC_CHUNK_SIZE, 0); read_target = &mut buffer[len..]; } else { @@ -459,3 +603,33 @@ pub fn parse_into_chunk<'a>( line_count_hint, } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retry_uses_fewer_complete_records() { + for separator in [b'\n', b'\0'] { + let input = [b'b', separator, b'a', separator, b'c', separator, b'd']; + let mut attempts = Vec::new(); + let fitted = fit_line_capacity(&input, separator, |count| { + attempts.push(count); + count <= 2 + }) + .unwrap(); + + assert_eq!(attempts, [4, 1]); + assert_eq!(fitted, (2, 1)); + assert_eq!( + &input[fitted.0..], + &[b'a', separator, b'c', separator, b'd'] + ); + } + } + + #[test] + fn retry_keeps_an_indivisible_record_intact() { + assert!(fit_line_capacity(b"one record\n", b'\n', |_| false).is_err()); + } +} diff --git a/src/uu/sort/src/ext_sort/threaded.rs b/src/uu/sort/src/ext_sort/threaded.rs index 0c5706c10e8..8ca98410dc1 100644 --- a/src/uu/sort/src/ext_sort/threaded.rs +++ b/src/uu/sort/src/ext_sort/threaded.rs @@ -219,9 +219,20 @@ fn read_write_loop( ) -> UResult> { let mut file = files.next().unwrap()?; - let mut carry_over = vec![]; - // 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") { + Vec::with_capacity(chunks::ALLOC_CHUNK_SIZE) + } else { + Vec::new() + }; + // A 32-bit process spills the first full chunk before filling another so + // their byte buffers and line metadata do not compete for address space. + let in_memory_chunks = if cfg!(target_pointer_width = "32") { + 1 + } else { + 2 + }; + for _ in 0..in_memory_chunks { let should_continue = chunks::read( &sender, RecycledChunk::new(buffer_size.min(DEFAULT_BUF_SIZE)), @@ -235,9 +246,8 @@ fn read_write_loop( if !should_continue { drop(sender); - // We have already read the whole input. Since we are in our first two reads, - // this means that we can fit the whole input into memory. Bypass writing below and - // handle this case in a more straightforward way. + // The entire input fit into the initial chunks. Output it without + // writing temporary runs. return Ok(if let Ok(first_chunk) = receiver.recv() { if let Ok(second_chunk) = receiver.recv() { ReadResult::SortedTwoChunks([first_chunk, second_chunk]) diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 537d6427195..7581451aecd 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -2754,7 +2754,10 @@ fn sort_by<'a>(unsorted: &mut Vec>, settings: &GlobalSettings, line_dat // WASI does not support threads, so use non-parallel sort to avoid // rayon's thread pool which triggers an unreachable trap. if settings.stable || settings.unique { - #[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))); + #[cfg(all(not(target_os = "wasi"), not(target_pointer_width = "32")))] unsorted.par_sort_by(cmp); #[cfg(target_os = "wasi")] unsorted.sort_by(cmp); From 4e8155af4a7abe9c25489a42541ab7099f35b007 Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 12:20:08 +0100 Subject: [PATCH 3/7] sort: reserve carry-over space on all threaded targets --- src/uu/sort/src/ext_sort/threaded.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/uu/sort/src/ext_sort/threaded.rs b/src/uu/sort/src/ext_sort/threaded.rs index 8ca98410dc1..6acff329f32 100644 --- a/src/uu/sort/src/ext_sort/threaded.rs +++ b/src/uu/sort/src/ext_sort/threaded.rs @@ -220,11 +220,7 @@ fn read_write_loop( let mut file = files.next().unwrap()?; // Reserve space for one read-ahead block before the chunks compete for memory. - let mut carry_over = if cfg!(target_pointer_width = "32") { - Vec::with_capacity(chunks::ALLOC_CHUNK_SIZE) - } else { - Vec::new() - }; + let mut carry_over = Vec::with_capacity(chunks::ALLOC_CHUNK_SIZE); // A 32-bit process spills the first full chunk before filling another so // their byte buffers and line metadata do not compete for address space. let in_memory_chunks = if cfg!(target_pointer_width = "32") { From aba54064183a38b66321a581fd24d147f1397179 Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 14:09:25 +0100 Subject: [PATCH 4/7] sort: keep read-ahead reservation on the low-memory path --- src/uu/sort/src/chunks.rs | 16 +++++++++++----- src/uu/sort/src/ext_sort/threaded.rs | 3 +-- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index c17e6ea1688..f965f6a492a 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -23,7 +23,7 @@ use uucore::numeric_str_cmp::NumInfo; use crate::{GeneralBigDecimalParseResult, GlobalSettings, Line, SortError}; -pub(crate) const ALLOC_CHUNK_SIZE: usize = 64 * 1024; +const ALLOC_CHUNK_SIZE: usize = 64 * 1024; const MAX_TOKEN_BUFFER_BYTES: usize = 4 * 1024 * 1024; const MAX_TOKEN_BUFFER_ELEMS: usize = MAX_TOKEN_BUFFER_BYTES / size_of::>(); @@ -217,6 +217,10 @@ pub fn read( // Leave room for bookkeeping and temporary-file I/O while sizing this chunk. let mut headroom = Vec::::new(); if cfg!(target_pointer_width = "32") { + // Make space for a read-ahead block before sizing the input chunk. + carry_over + .try_reserve_exact(ALLOC_CHUNK_SIZE.saturating_sub(carry_over.len())) + .map_err(|_| out_of_memory())?; headroom .try_reserve_exact(1024 * 1024) .map_err(|_| out_of_memory())?; @@ -265,9 +269,11 @@ pub fn read( } carry_over.clear(); if should_continue { - carry_over - .try_reserve_exact(filled - read) - .map_err(|_| out_of_memory())?; + if cfg!(target_pointer_width = "32") { + carry_over + .try_reserve_exact(filled - read) + .map_err(|_| out_of_memory())?; + } carry_over.extend_from_slice(&buffer[read..filled]); } @@ -610,7 +616,7 @@ mod tests { #[test] fn retry_uses_fewer_complete_records() { - for separator in [b'\n', b'\0'] { + for &separator in b"\n\0" { let input = [b'b', separator, b'a', separator, b'c', separator, b'd']; let mut attempts = Vec::new(); let fitted = fit_line_capacity(&input, separator, |count| { diff --git a/src/uu/sort/src/ext_sort/threaded.rs b/src/uu/sort/src/ext_sort/threaded.rs index 6acff329f32..0bad349a69c 100644 --- a/src/uu/sort/src/ext_sort/threaded.rs +++ b/src/uu/sort/src/ext_sort/threaded.rs @@ -219,8 +219,7 @@ fn read_write_loop( ) -> UResult> { let mut file = files.next().unwrap()?; - // Reserve space for one read-ahead block before the chunks compete for memory. - let mut carry_over = Vec::with_capacity(chunks::ALLOC_CHUNK_SIZE); + let mut carry_over = Vec::new(); // A 32-bit process spills the first full chunk before filling another so // their byte buffers and line metadata do not compete for address space. let in_memory_chunks = if cfg!(target_pointer_width = "32") { From 2b124ed24e710cfb2e2baacfacae28e2e265637d Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 14:50:56 +0100 Subject: [PATCH 5/7] sort: make allocation retries independent of pointer width --- src/uu/sort/src/buffer_hint.rs | 12 +- src/uu/sort/src/check.rs | 10 +- src/uu/sort/src/chunks.rs | 208 +++++++++++++-------------- src/uu/sort/src/ext_sort/threaded.rs | 22 ++- src/uu/sort/src/merge.rs | 6 +- src/uu/sort/src/sort.rs | 11 +- tests/by-util/test_sort.rs | 23 +++ 7 files changed, 142 insertions(+), 150 deletions(-) diff --git a/src/uu/sort/src/buffer_hint.rs b/src/uu/sort/src/buffer_hint.rs index 95a01c423f6..a6780941f89 100644 --- a/src/uu/sort/src/buffer_hint.rs +++ b/src/uu/sort/src/buffer_hint.rs @@ -105,12 +105,6 @@ fn physical_memory_bytes() -> Option { mod tests { use super::*; - #[cfg(target_pointer_width = "32")] - #[test] - fn automatic_memory_hint_leaves_room_for_line_metadata() { - assert_eq!(clamp_hint(u128::MAX), 32 * 1024 * 1024); - } - #[test] fn desired_buffer_matches_total_when_small() { let six_mebibytes = 6 * 1024 * 1024; @@ -120,11 +114,11 @@ mod tests { } #[test] - fn file_buffer_hint_caps_at_max_for_large_inputs() { + fn desired_buffer_caps_at_max_for_large_inputs() { let large = 256 * 1024 * 1024; // 256 MiB assert_eq!( - clamp_hint(desired_file_buffer_bytes(large as u128)), - crate::MAX_AUTOMATIC_BUF_SIZE + desired_file_buffer_bytes(large as u128), + crate::MAX_AUTOMATIC_BUF_SIZE as u128 ); } } diff --git a/src/uu/sort/src/check.rs b/src/uu/sort/src/check.rs index 867df884186..05e46724a9f 100644 --- a/src/uu/sort/src/check.rs +++ b/src/uu/sort/src/check.rs @@ -7,7 +7,7 @@ use crate::{ GlobalSettings, SortError, - chunks::{self, Chunk, RecycledChunk}, + chunks::{self, Chunk, ReadStatus, RecycledChunk}, compare_by, open, }; use itertools::Itertools; @@ -168,7 +168,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { let mut line_idx = 0; loop { let recycled = RecycledChunk::new(buffer_size(settings)); - let should_continue = chunks::read( + let status = chunks::read( &sender, recycled, None, @@ -189,7 +189,7 @@ pub fn check(path: &OsStr, settings: &GlobalSettings) -> UResult<()> { )?; prev_chunk = Some(chunk); } - if !should_continue { + if status == ReadStatus::End { break; } } @@ -206,7 +206,7 @@ fn reader( ) -> UResult<()> { let mut carry_over = vec![]; for recycled_chunk in receiver { - let should_continue = chunks::read( + let status = chunks::read( sender, recycled_chunk, None, @@ -216,7 +216,7 @@ fn reader( settings.line_ending.into(), settings, )?; - if !should_continue { + if status == ReadStatus::End { break; } } diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index f965f6a492a..f784c21850a 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -24,6 +24,8 @@ use uucore::numeric_str_cmp::NumInfo; use crate::{GeneralBigDecimalParseResult, GlobalSettings, Line, SortError}; const ALLOC_CHUNK_SIZE: usize = 64 * 1024; +// Keep enough address space available for temporary-file I/O and bookkeeping. +const SPILL_HEADROOM_BYTES: usize = 1024 * 1024; const MAX_TOKEN_BUFFER_BYTES: usize = 4 * 1024 * 1024; const MAX_TOKEN_BUFFER_ELEMS: usize = MAX_TOKEN_BUFFER_BYTES / size_of::>(); @@ -158,37 +160,45 @@ impl RecycledChunk { fn try_reserve_lines(&mut self, count: usize, settings: &GlobalSettings) -> bool { let precomputed = &settings.precomputed; - try_reserve(&mut self.lines, count) - && try_reserve( + if !try_reserve(&mut self.lines, count) + || !try_reserve( &mut self.selections, count.saturating_mul(precomputed.selections_per_line), ) - && try_reserve( + || !try_reserve( &mut self.num_infos, count.saturating_mul(precomputed.num_infos_per_line), ) - && try_reserve( + || !try_reserve( &mut self.parsed_floats, count.saturating_mul(precomputed.floats_per_line), ) - && (!precomputed.whole_line_numeric || try_reserve(&mut self.line_num_floats, count)) - && { - #[cfg(feature = "i18n-collator")] - if precomputed.fast_locale_collation { - return try_reserve(&mut self.collation_key_ends, count); - } - true - } + { + return false; + } + if precomputed.whole_line_numeric && !try_reserve(&mut self.line_num_floats, count) { + return false; + } + #[cfg(feature = "i18n-collator")] + if precomputed.fast_locale_collation { + return try_reserve(&mut self.collation_key_ends, count); + } + true } } +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum ReadStatus { + End, + More, + Spill, +} + /// Read a chunk, parse lines and send them. /// -/// No empty chunk will be sent. If we reach the end of the input, `false` is returned. -/// However, if this function returns `true`, it is not guaranteed that there is still -/// input left: If the input fits _exactly_ into a buffer, we will only notice that there's -/// nothing more to read at the next invocation. In case there is no input left, nothing will -/// be sent. +/// No empty chunk will be sent. If the input fits exactly into a buffer, +/// the next call can discover EOF. A spill status tells the caller to write +/// the in-memory runs before reading another chunk. /// /// # Arguments /// @@ -213,66 +223,66 @@ pub fn read( next_files: &mut impl Iterator>, separator: u8, settings: &GlobalSettings, -) -> UResult { - // Leave room for bookkeeping and temporary-file I/O while sizing this chunk. +) -> UResult { let mut headroom = Vec::::new(); - if cfg!(target_pointer_width = "32") { - // Make space for a read-ahead block before sizing the input chunk. - carry_over - .try_reserve_exact(ALLOC_CHUNK_SIZE.saturating_sub(carry_over.len())) - .map_err(|_| out_of_memory())?; - headroom - .try_reserve_exact(1024 * 1024) - .map_err(|_| out_of_memory())?; - } - let mut buffer = std::mem::take(&mut recycled_chunk.buffer); - let max_buffer_size = if cfg!(target_pointer_width = "32") { - 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())); - Some(limit) - } else { - max_buffer_size - }; + 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())); if let Some(additional) = carry_over .len() .checked_sub(buffer.len()) .filter(|&size| size > 0) { - if cfg!(target_pointer_width = "32") && !try_reserve(&mut buffer, additional) { + if !try_reserve(&mut buffer, additional) { return Err(out_of_memory().into()); } // Separate carry_over and copy them to avoid cost of 0 fill buffer buffer.extend_from_slice(&carry_over[buffer.len()..]); } buffer[..carry_over.len()].copy_from_slice(carry_over); - let (mut read, mut should_continue) = read_to_buffer( + let start_offset = carry_over.len(); + let (mut read, mut status) = read_to_buffer( file, next_files, &mut buffer, - |count| recycled_chunk.try_reserve_lines(count, settings), - max_buffer_size, - carry_over.len(), + |count, bytes| { + // Avoid reserving spill space for small in-memory sorts. + if bytes >= SPILL_HEADROOM_BYTES && headroom.capacity() == 0 { + let read_ahead = ALLOC_CHUNK_SIZE.saturating_sub(carry_over.len()); + if carry_over.try_reserve_exact(read_ahead).is_err() + || headroom.try_reserve_exact(SPILL_HEADROOM_BYTES).is_err() + { + return false; + } + } + recycled_chunk.try_reserve_lines(count, settings) + }, + limit, + start_offset, separator, )?; // At EOF, bytes after `read` are unused buffer space. Otherwise they // include the partial record that must be carried into the next read. - let filled = if should_continue { buffer.len() } else { read }; - if read != 0 && cfg!(target_pointer_width = "32") { + let filled = if status == ReadStatus::End { + read + } else { + buffer.len() + }; + if read != 0 { let (fitted, line_count) = fit_line_capacity(&buffer[..read], separator, |count| { recycled_chunk.try_reserve_lines(count, settings) })?; - should_continue |= fitted < read; + if fitted < read { + status = ReadStatus::Spill; + } read = fitted; recycled_chunk.line_count_hint = line_count; } carry_over.clear(); - if should_continue { - if cfg!(target_pointer_width = "32") { - carry_over - .try_reserve_exact(filled - read) - .map_err(|_| out_of_memory())?; + if status != ReadStatus::End { + if !try_reserve(carry_over, filled - read) { + return Err(out_of_memory().into()); } carry_over.extend_from_slice(&buffer[read..filled]); } @@ -331,7 +341,7 @@ pub fn read( }); sender.send(payload?).unwrap(); } - Ok(should_continue) + Ok(status) } /// Find a prefix whose line descriptors fit, leaving whole records for the next read. @@ -362,6 +372,13 @@ fn try_reserve(buffer: &mut Vec, additional: usize) -> bool { buffer.try_reserve(additional).is_ok() || buffer.try_reserve_exact(additional).is_ok() } +fn spillable_prefix(end: usize) -> UResult<(usize, ReadStatus)> { + if end == 0 { + return Err(out_of_memory().into()); + } + Ok((end, ReadStatus::Spill)) +} + fn out_of_memory() -> SortError { SortError::ChunkReadFailed { error: ErrorKind::OutOfMemory.into(), @@ -451,7 +468,7 @@ fn parse_lines<'a>( /// and this function continues reading. /// * `buffer`: The buffer that is filled with bytes. Its contents will mostly be overwritten (see `start_offset` /// as well). It will be grown up to `max_buffer_size` if necessary, but it will always grow to read at least two lines. -/// * `max_buffer_size`: Grow the buffer to at most this length. If None, the buffer will not grow, unless needed to read at least two lines. +/// * `max_buffer_size`: Target length of the byte buffer. It can grow past this limit to read at least two lines. /// * `start_offset`: The amount of bytes at the start of `buffer` that were carried over /// from the previous read and should not be overwritten. /// * `separator`: The byte that separates lines. @@ -467,11 +484,11 @@ fn read_to_buffer( file: &mut T, next_files: &mut impl Iterator>, buffer: &mut Vec, - mut reserve: impl FnMut(usize) -> bool, - max_buffer_size: Option, + mut reserve: impl FnMut(usize, usize) -> bool, + max_buffer_size: usize, start_offset: usize, separator: u8, -) -> UResult<(usize, bool)> { +) -> UResult<(usize, ReadStatus)> { let mut read_target = &mut buffer[start_offset..]; let mut newline_search_offset = 0; let mut found_newline = false; @@ -482,65 +499,36 @@ fn read_to_buffer( match file.read(read_target) { Ok(0) => { if read_target.is_empty() { - // Reserve line descriptors before growing the byte buffer again. - // Under pressure, spill the prefix we already reserved rather - // than buffering a large suffix that would need another allocation. - if cfg!(target_pointer_width = "32") { - let scanned_bytes = &buffer[scanned..]; - let count = memchr_iter(separator, scanned_bytes).count(); - line_count += count; - if !reserve(line_count) { - return if reserved_end == 0 { - Err(out_of_memory().into()) - } else { - Ok((reserved_end, true)) - }; - } - if count != 0 { - reserved_end = scanned + memrchr(separator, scanned_bytes).unwrap() + 1; - } - scanned = buffer.len(); + // Reserve metadata before growing again so the last fitting + // prefix can be spilled without allocating a large read-ahead. + let len = buffer.len(); + let scanned_bytes = &buffer[scanned..]; + line_count += memchr_iter(separator, scanned_bytes).count(); + if !reserve(line_count, len) { + return spillable_prefix(reserved_end); } - - // chunk is full - if max_buffer_size.is_some_and(|max_buf_size| max_buf_size > buffer.len()) { - // we can grow the buffer - let prev_len = buffer.len(); - if cfg!(target_pointer_width = "32") - && !try_reserve(buffer, ALLOC_CHUNK_SIZE) - { - return if reserved_end == 0 { - Err(out_of_memory().into()) - } else { - Ok((reserved_end, true)) - }; - } - buffer.resize(prev_len + ALLOC_CHUNK_SIZE, 0); - read_target = &mut buffer[prev_len..]; - continue; + if let Some(pos) = memrchr(separator, scanned_bytes) { + reserved_end = scanned + pos + 1; } - - let search_start = newline_search_offset; - let mut sep_iter = - memchr_iter(separator, &buffer[search_start..buffer.len()]).rev(); - newline_search_offset = buffer.len(); - if let Some(last_line_end) = sep_iter.next() { - if found_newline || sep_iter.next().is_some() { - // We read enough lines. - // We want to include the separator here, because it shouldn't be carried over. - return Ok((search_start + last_line_end + 1, true)); + scanned = len; + + if len >= max_buffer_size { + let mut separators = + memchr_iter(separator, &buffer[newline_search_offset..]).rev(); + if let Some(last_line_end) = separators.next() { + if found_newline || separators.next().is_some() { + return Ok(( + newline_search_offset + last_line_end + 1, + ReadStatus::More, + )); + } + found_newline = true; } - found_newline = true; + newline_search_offset = len; } - // We need to read more lines. - let len = buffer.len(); - if cfg!(target_pointer_width = "32") && !try_reserve(buffer, ALLOC_CHUNK_SIZE) { - return if reserved_end == 0 { - Err(out_of_memory().into()) - } else { - Ok((reserved_end, true)) - }; + if !try_reserve(buffer, ALLOC_CHUNK_SIZE) { + return spillable_prefix(reserved_end); } buffer.resize(len + ALLOC_CHUNK_SIZE, 0); read_target = &mut buffer[len..]; @@ -564,7 +552,7 @@ fn read_to_buffer( } else { // This was the last file. let read_len = buffer.len() - leftover_len; - return Ok((read_len, false)); + return Ok((read_len, ReadStatus::End)); } } } diff --git a/src/uu/sort/src/ext_sort/threaded.rs b/src/uu/sort/src/ext_sort/threaded.rs index 0bad349a69c..d4cb0d57204 100644 --- a/src/uu/sort/src/ext_sort/threaded.rs +++ b/src/uu/sort/src/ext_sort/threaded.rs @@ -17,7 +17,7 @@ use itertools::Itertools; use uucore::error::{UResult, strip_errno}; use crate::Output; -use crate::chunks::RecycledChunk; +use crate::chunks::{ReadStatus, RecycledChunk}; use crate::merge::WriteableCompressedTmpFile; use crate::merge::WriteablePlainTmpFile; use crate::merge::WriteableTmpFile; @@ -220,15 +220,8 @@ fn read_write_loop( let mut file = files.next().unwrap()?; let mut carry_over = Vec::new(); - // A 32-bit process spills the first full chunk before filling another so - // their byte buffers and line metadata do not compete for address space. - let in_memory_chunks = if cfg!(target_pointer_width = "32") { - 1 - } else { - 2 - }; - for _ in 0..in_memory_chunks { - let should_continue = chunks::read( + for _ in 0..2 { + let status = chunks::read( &sender, RecycledChunk::new(buffer_size.min(DEFAULT_BUF_SIZE)), Some(buffer_size), @@ -239,7 +232,10 @@ fn read_write_loop( settings, )?; - if !should_continue { + if status == ReadStatus::Spill { + break; + } + if status == ReadStatus::End { drop(sender); // The entire input fit into the initial chunks. Output it without // writing temporary runs. @@ -273,7 +269,7 @@ fn read_write_loop( let recycled_chunk = chunk.recycle(); if let Some(sender) = &sender_option { - let should_continue = chunks::read( + let status = chunks::read( sender, recycled_chunk, None, @@ -283,7 +279,7 @@ fn read_write_loop( separator, settings, )?; - if !should_continue { + if status == ReadStatus::End { sender_option = None; } } diff --git a/src/uu/sort/src/merge.rs b/src/uu/sort/src/merge.rs index 79fab4b86e2..591de614379 100644 --- a/src/uu/sort/src/merge.rs +++ b/src/uu/sort/src/merge.rs @@ -31,7 +31,7 @@ use uucore::fs::FileInformation; use crate::{ GlobalSettings, Output, SortError, - chunks::{self, Chunk, RecycledChunk}, + chunks::{self, Chunk, ReadStatus, RecycledChunk}, current_open_fd_count, fd_soft_limit, merge_compare, open, tmp_dir::{TmpDirWrapper, TmpPath}, }; @@ -267,7 +267,7 @@ fn reader( carry_over, }) = &mut files[file_idx] { - let should_continue = chunks::read( + let status = chunks::read( sender, recycled_chunk, None, @@ -277,7 +277,7 @@ fn reader( separator, settings, )?; - if !should_continue { + if status == ReadStatus::End { // Remove the file from the list by replacing it with `None`. let ReaderFile { file, .. } = files[file_idx].take().unwrap(); // Depending on the kind of the `MergeInput`, this may delete the file: diff --git a/src/uu/sort/src/sort.rs b/src/uu/sort/src/sort.rs index 7581451aecd..cec38b32a24 100644 --- a/src/uu/sort/src/sort.rs +++ b/src/uu/sort/src/sort.rs @@ -124,12 +124,6 @@ const POSITIVE: &u8 = &b'+'; // reasonably large chunks for typical workloads. const MIN_AUTOMATIC_BUF_SIZE: usize = 512 * 1024; // 512 KiB const FALLBACK_AUTOMATIC_BUF_SIZE: usize = 32 * 1024 * 1024; // 32 MiB -// The byte buffers share the process address space with per-line metadata and -// 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 -#[cfg(not(target_pointer_width = "32"))] const MAX_AUTOMATIC_BUF_SIZE: usize = 1024 * 1024 * 1024; // 1 GiB #[derive(Debug, thiserror::Error)] @@ -2754,10 +2748,7 @@ fn sort_by<'a>(unsorted: &mut Vec>, settings: &GlobalSettings, line_dat // WASI does not support threads, so use non-parallel sort to avoid // rayon's thread pool which triggers an unreachable trap. if settings.stable || settings.unique { - #[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))); - #[cfg(all(not(target_os = "wasi"), not(target_pointer_width = "32")))] + #[cfg(not(target_os = "wasi"))] unsorted.par_sort_by(cmp); #[cfg(target_os = "wasi")] unsorted.sort_by(cmp); diff --git a/tests/by-util/test_sort.rs b/tests/by-util/test_sort.rs index 7f63dcec076..27b2feffec2 100644 --- a/tests/by-util/test_sort.rs +++ b/tests/by-util/test_sort.rs @@ -100,6 +100,29 @@ fn test_buffer_size_limits_both_chunks() { } } +#[test] +#[cfg(target_os = "linux")] +fn test_sort_retries_smaller_chunks_under_address_space_limit() { + const PAIRS: usize = 6 * 1024 * 1024; + let memory_limit = if env::var_os("LLVM_PROFILE_FILE").is_some() { + 128 * 1024 * 1024 + } else { + 96 * 1024 * 1024 + }; + let mut expected = b"a\n".repeat(PAIRS); + expected.extend(b"z\n".repeat(PAIRS)); + + new_ucmd!() + .args(&["--parallel=1", "--buffer-size=512M"]) + .env("MALLOC_ARENA_MAX", "1") + .limit(Resource::AS, memory_limit, memory_limit) + .limit(Resource::CORE, 0, 0) + .timeout(Duration::from_secs(120)) + .pipe_in(b"z\na\n".repeat(PAIRS)) + .succeeds() + .stdout_only_bytes(expected); +} + #[test] fn test_buffer_size_trailing_whitespace_is_rejected() { for size in [" 1 ", "1 ", "1M ", "50% "] { From c0bd40abe10bf36161f623805f3b8b59123c5c8d Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 15:23:15 +0100 Subject: [PATCH 6/7] sort: keep the recycled read buffer initialized --- src/uu/sort/src/chunks.rs | 180 +++++++++++++++++++++----------------- 1 file changed, 102 insertions(+), 78 deletions(-) diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index f784c21850a..3b66cbc0e41 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -202,11 +202,10 @@ pub enum ReadStatus { /// /// # Arguments /// -/// (see also `read_to_chunk` for a more detailed documentation) +/// (see also `read_to_buffer` for a more detailed documentation) /// /// * `sender`: The sender to send the lines to the sorter. /// * `recycled_chunk`: The recycled chunk, as returned by `Chunk::recycle`. -/// (i.e. `buffer.len()` should be equal to `buffer.capacity()`) /// * `max_buffer_size`: How big `buffer` can be. /// * `carry_over`: The bytes that must be carried over in between invocations. /// * `file`: The current file. @@ -227,8 +226,6 @@ pub fn read( let mut headroom = Vec::::new(); 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())); if let Some(additional) = carry_over .len() .checked_sub(buffer.len()) @@ -242,33 +239,32 @@ pub fn read( } buffer[..carry_over.len()].copy_from_slice(carry_over); let start_offset = carry_over.len(); - let (mut read, mut status) = read_to_buffer( + let BufferRead { + mut read, + filled, + mut status, + } = read_to_buffer( file, next_files, &mut buffer, - |count, bytes| { - // Avoid reserving spill space for small in-memory sorts. - if bytes >= SPILL_HEADROOM_BYTES && headroom.capacity() == 0 { - let read_ahead = ALLOC_CHUNK_SIZE.saturating_sub(carry_over.len()); - if carry_over.try_reserve_exact(read_ahead).is_err() - || headroom.try_reserve_exact(SPILL_HEADROOM_BYTES).is_err() - { - return false; + ReadBudget { + limit, + reserve: |count, bytes| { + // Avoid reserving spill space for small in-memory sorts. + if bytes >= SPILL_HEADROOM_BYTES && headroom.capacity() == 0 { + let read_ahead = ALLOC_CHUNK_SIZE.saturating_sub(carry_over.len()); + if carry_over.try_reserve_exact(read_ahead).is_err() + || headroom.try_reserve_exact(SPILL_HEADROOM_BYTES).is_err() + { + return false; + } } - } - recycled_chunk.try_reserve_lines(count, settings) + recycled_chunk.try_reserve_lines(count, settings) + }, }, - limit, start_offset, separator, )?; - // At EOF, bytes after `read` are unused buffer space. Otherwise they - // include the partial record that must be carried into the next read. - let filled = if status == ReadStatus::End { - read - } else { - buffer.len() - }; if read != 0 { let (fitted, line_count) = fit_line_capacity(&buffer[..read], separator, |count| { recycled_chunk.try_reserve_lines(count, settings) @@ -372,11 +368,15 @@ fn try_reserve(buffer: &mut Vec, additional: usize) -> bool { buffer.try_reserve(additional).is_ok() || buffer.try_reserve_exact(additional).is_ok() } -fn spillable_prefix(end: usize) -> UResult<(usize, ReadStatus)> { - if end == 0 { +fn spillable_prefix(read: usize, filled: usize) -> UResult { + if read == 0 { return Err(out_of_memory().into()); } - Ok((end, ReadStatus::Spill)) + Ok(BufferRead { + read, + filled, + status: ReadStatus::Spill, + }) } fn out_of_memory() -> SortError { @@ -453,43 +453,35 @@ fn parse_lines<'a>( *line_count_hint = exact_line_count.unwrap_or(index + 1); } -/// Read from `file` into `buffer`. -/// -/// This function makes sure that at least two lines are read (unless we reach EOF and there's no next file), -/// growing the buffer if necessary. -/// The last line is likely to not have been fully read into the buffer. Its bytes must be copied to -/// the front of the buffer for the next invocation so that it can be continued to be read -/// (see the return values and `start_offset`). -/// -/// # Arguments -/// -/// * `file`: The file to start reading from. -/// * `next_files`: When `file` reaches EOF, it is updated to `next_files.next()` if that is `Some`, -/// and this function continues reading. -/// * `buffer`: The buffer that is filled with bytes. Its contents will mostly be overwritten (see `start_offset` -/// as well). It will be grown up to `max_buffer_size` if necessary, but it will always grow to read at least two lines. -/// * `max_buffer_size`: Target length of the byte buffer. It can grow past this limit to read at least two lines. -/// * `start_offset`: The amount of bytes at the start of `buffer` that were carried over -/// from the previous read and should not be overwritten. -/// * `separator`: The byte that separates lines. -/// -/// # Returns -/// -/// * The amount of bytes in `buffer` that can now be interpreted as lines. -/// 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)] +struct ReadBudget { + limit: usize, + reserve: F, +} + +struct BufferRead { + // Bytes forming complete records and ready to sort. + read: usize, + // End of the input actually read. Bytes between read and filled + // must be carried over, while bytes after filled may be stale. + filled: usize, + status: ReadStatus, +} + +/// Fill the initialized buffer in stages so each stage can check its memory +/// budget. The read window can grow past the budget to complete long records. fn read_to_buffer( file: &mut T, next_files: &mut impl Iterator>, buffer: &mut Vec, - mut reserve: impl FnMut(usize, usize) -> bool, - max_buffer_size: usize, + budget: ReadBudget bool>, start_offset: usize, separator: u8, -) -> UResult<(usize, ReadStatus)> { - let mut read_target = &mut buffer[start_offset..]; +) -> UResult { + let ReadBudget { limit, mut reserve } = budget; + // Keep the initialized bytes of recycled buffers. Advance a separate + // read window so that reusing them does not zero-fill the same bytes again. + let mut end = buffer.len().min(ALLOC_CHUNK_SIZE.max(start_offset)); + let mut read_target = &mut buffer[start_offset..end]; let mut newline_search_offset = 0; let mut found_newline = false; let mut scanned = 0; @@ -501,58 +493,66 @@ fn read_to_buffer( if read_target.is_empty() { // Reserve metadata before growing again so the last fitting // prefix can be spilled without allocating a large read-ahead. - let len = buffer.len(); - let scanned_bytes = &buffer[scanned..]; + let scanned_bytes = &buffer[scanned..end]; line_count += memchr_iter(separator, scanned_bytes).count(); - if !reserve(line_count, len) { - return spillable_prefix(reserved_end); + if !reserve(line_count, end) { + return spillable_prefix(reserved_end, end); } if let Some(pos) = memrchr(separator, scanned_bytes) { reserved_end = scanned + pos + 1; } - scanned = len; + scanned = end; - if len >= max_buffer_size { + if end >= limit { let mut separators = - memchr_iter(separator, &buffer[newline_search_offset..]).rev(); + memchr_iter(separator, &buffer[newline_search_offset..end]).rev(); if let Some(last_line_end) = separators.next() { if found_newline || separators.next().is_some() { - return Ok(( - newline_search_offset + last_line_end + 1, - ReadStatus::More, - )); + return Ok(BufferRead { + read: newline_search_offset + last_line_end + 1, + filled: end, + status: ReadStatus::More, + }); } found_newline = true; } - newline_search_offset = len; + newline_search_offset = end; } - if !try_reserve(buffer, ALLOC_CHUNK_SIZE) { - return spillable_prefix(reserved_end); + let next_end = end + ALLOC_CHUNK_SIZE; + if next_end > buffer.len() { + if !try_reserve(buffer, next_end - buffer.len()) { + return spillable_prefix(reserved_end, end); + } + buffer.resize(next_end, 0); } - buffer.resize(len + ALLOC_CHUNK_SIZE, 0); - read_target = &mut buffer[len..]; + read_target = &mut buffer[end..next_end]; + end = next_end; } else { // This file has been fully read. let mut leftover_len = read_target.len(); // Decide from buffered bytes: a file may span calls, so a 0-byte read can // still leave an unterminated tail that must be separated from the next file. - let read_len = buffer.len() - leftover_len; + let read_len = end - leftover_len; if read_len > 0 && buffer[read_len - 1] != separator { // The data so far does not end with a separator. We have to insert one. // `read_target` is non-empty here, so `buffer[read_len]` is in bounds. buffer[read_len] = separator; leftover_len -= 1; } - let read_len = buffer.len() - leftover_len; - read_target = &mut buffer[read_len..]; + let read_len = end - leftover_len; + read_target = &mut buffer[read_len..end]; if let Some(next_file) = next_files.next() { // There is another file. *file = next_file?; } else { // This was the last file. - let read_len = buffer.len() - leftover_len; - return Ok((read_len, ReadStatus::End)); + let read_len = end - leftover_len; + return Ok(BufferRead { + read: read_len, + filled: read_len, + status: ReadStatus::End, + }); } } } @@ -602,6 +602,30 @@ pub fn parse_into_chunk<'a>( mod tests { use super::*; + #[test] + fn recycled_buffer_leaves_unused_initialized_bytes_untouched() { + let mut buffer = vec![0xff; 2 * ALLOC_CHUNK_SIZE]; + let input = b"x\n".repeat(3 * ALLOC_CHUNK_SIZE / 4); + let result = read_to_buffer( + &mut input.as_slice(), + &mut std::iter::empty(), + &mut buffer, + ReadBudget { + limit: 2 * ALLOC_CHUNK_SIZE, + reserve: |_, _| true, + }, + 0, + b'\n', + ) + .unwrap(); + + assert!(result.status == ReadStatus::End); + assert_eq!(result.read, input.len()); + assert_eq!(result.filled, input.len()); + assert_eq!(&buffer[..result.read], input.as_slice()); + assert!(buffer[result.filled..].iter().all(|&byte| byte == 0xff)); + } + #[test] fn retry_uses_fewer_complete_records() { for &separator in b"\n\0" { From 3ddb58e6c305d5ccbd83cb4bfba113a3a8c38e19 Mon Sep 17 00:00:00 2001 From: ChrisX001001 Date: Fri, 27 Nov 2026 21:20:59 +0100 Subject: [PATCH 7/7] sort: reuse record counts from buffer reads --- src/uu/sort/src/chunks.rs | 101 +++++++++++++++++++++++++++++--------- 1 file changed, 78 insertions(+), 23 deletions(-) diff --git a/src/uu/sort/src/chunks.rs b/src/uu/sort/src/chunks.rs index 3b66cbc0e41..1b184e69fc9 100644 --- a/src/uu/sort/src/chunks.rs +++ b/src/uu/sort/src/chunks.rs @@ -243,6 +243,7 @@ pub fn read( mut read, filled, mut status, + mut line_count, } = read_to_buffer( file, next_files, @@ -265,16 +266,22 @@ pub fn read( start_offset, separator, )?; - if read != 0 { - let (fitted, line_count) = fit_line_capacity(&buffer[..read], separator, |count| { + // Full read windows have already reserved their metadata. At EOF only + // the final partial window may still need space. + if read != 0 + && status == ReadStatus::End + && !recycled_chunk.try_reserve_lines(line_count, settings) + { + let (fitted, fitted_line_count) = fit_line_capacity(&buffer[..read], separator, |count| { recycled_chunk.try_reserve_lines(count, settings) })?; if fitted < read { status = ReadStatus::Spill; } read = fitted; - recycled_chunk.line_count_hint = line_count; + line_count = fitted_line_count; } + recycled_chunk.line_count_hint = line_count; carry_over.clear(); if status != ReadStatus::End { if !try_reserve(carry_over, filled - read) { @@ -368,7 +375,7 @@ fn try_reserve(buffer: &mut Vec, additional: usize) -> bool { buffer.try_reserve(additional).is_ok() || buffer.try_reserve_exact(additional).is_ok() } -fn spillable_prefix(read: usize, filled: usize) -> UResult { +fn spillable_prefix(read: usize, filled: usize, line_count: usize) -> UResult { if read == 0 { return Err(out_of_memory().into()); } @@ -376,6 +383,7 @@ fn spillable_prefix(read: usize, filled: usize) -> UResult { read, filled, status: ReadStatus::Spill, + line_count, }) } @@ -395,8 +403,6 @@ fn parse_lines<'a>( separator: u8, settings: &GlobalSettings, ) { - const SMALL_CHUNK_BYTES: usize = 64 * 1024; - let read = read.strip_suffix(&[separator]).unwrap_or(read); assert!(lines.is_empty()); @@ -407,20 +413,11 @@ fn parse_lines<'a>( assert!(line_data.collation_key_buffer.is_empty()); assert!(line_data.collation_key_ends.is_empty()); token_buffer.clear(); - let mut estimated = (*line_count_hint).max(1); - let mut exact_line_count = None; - if *line_count_hint == 0 || read.len() <= SMALL_CHUNK_BYTES { - let count = if read.is_empty() { - 1 - } else { - memchr_iter(separator, read).count() + 1 - }; - exact_line_count = Some(count); - estimated = count; - } else if estimated == 1 { - const LINE_LEN_HINT: usize = 128; - estimated = (read.len() / LINE_LEN_HINT).clamp(1, 1024); - } + let estimated = if *line_count_hint == 0 { + memchr_iter(separator, read).count() + 1 + } else { + *line_count_hint + }; lines.reserve(estimated); if settings.precomputed.selections_per_line > 0 { line_data @@ -450,7 +447,7 @@ fn parse_lines<'a>( } let line = &read[start..]; lines.push(Line::create(line, index, line_data, token_buffer, settings)); - *line_count_hint = exact_line_count.unwrap_or(index + 1); + *line_count_hint = index + 1; } struct ReadBudget { @@ -465,6 +462,7 @@ struct BufferRead { // must be carried over, while bytes after filled may be stale. filled: usize, status: ReadStatus, + line_count: usize, } /// Fill the initialized buffer in stages so each stage can check its memory @@ -487,6 +485,7 @@ fn read_to_buffer( let mut scanned = 0; let mut line_count = 0; let mut reserved_end = 0; + let mut reserved_line_count = 0; loop { match file.read(read_target) { Ok(0) => { @@ -496,10 +495,11 @@ fn read_to_buffer( let scanned_bytes = &buffer[scanned..end]; line_count += memchr_iter(separator, scanned_bytes).count(); if !reserve(line_count, end) { - return spillable_prefix(reserved_end, end); + return spillable_prefix(reserved_end, end, reserved_line_count); } if let Some(pos) = memrchr(separator, scanned_bytes) { reserved_end = scanned + pos + 1; + reserved_line_count = line_count; } scanned = end; @@ -512,6 +512,7 @@ fn read_to_buffer( read: newline_search_offset + last_line_end + 1, filled: end, status: ReadStatus::More, + line_count, }); } found_newline = true; @@ -522,7 +523,7 @@ fn read_to_buffer( let next_end = end + ALLOC_CHUNK_SIZE; if next_end > buffer.len() { if !try_reserve(buffer, next_end - buffer.len()) { - return spillable_prefix(reserved_end, end); + return spillable_prefix(reserved_end, end, reserved_line_count); } buffer.resize(next_end, 0); } @@ -548,10 +549,12 @@ fn read_to_buffer( } else { // This was the last file. let read_len = end - leftover_len; + line_count += memchr_iter(separator, &buffer[scanned..read_len]).count(); return Ok(BufferRead { read: read_len, filled: read_len, status: ReadStatus::End, + line_count, }); } } @@ -620,12 +623,64 @@ mod tests { .unwrap(); assert!(result.status == ReadStatus::End); + assert_eq!(result.line_count, input.len() / 2); assert_eq!(result.read, input.len()); assert_eq!(result.filled, input.len()); assert_eq!(&buffer[..result.read], input.as_slice()); assert!(buffer[result.filled..].iter().all(|&byte| byte == 0xff)); } + #[test] + fn complete_prefix_reports_only_its_reserved_records() { + let mut input = b"x\n".repeat(ALLOC_CHUNK_SIZE); + input[ALLOC_CHUNK_SIZE - 1] = b'x'; + let line_count = ALLOC_CHUNK_SIZE / 2 - 1; + + for (limit, status) in [ + (ALLOC_CHUNK_SIZE, ReadStatus::More), + (2 * ALLOC_CHUNK_SIZE, ReadStatus::Spill), + ] { + let mut buffer = vec![0; 2 * ALLOC_CHUNK_SIZE]; + let result = read_to_buffer( + &mut input.as_slice(), + &mut std::iter::empty(), + &mut buffer, + ReadBudget { + limit, + reserve: |count, _| count <= line_count, + }, + 0, + b'\n', + ) + .unwrap(); + + assert!(result.status == status); + assert_eq!(result.read, ALLOC_CHUNK_SIZE - 2); + assert_eq!(result.line_count, line_count); + } + } + + #[test] + fn eof_counts_an_unterminated_record_once() { + let mut buffer = vec![0; ALLOC_CHUNK_SIZE]; + let result = read_to_buffer( + &mut b"b\na".as_slice(), + &mut std::iter::empty(), + &mut buffer, + ReadBudget { + limit: ALLOC_CHUNK_SIZE, + reserve: |_, _| true, + }, + 0, + b'\n', + ) + .unwrap(); + + assert!(result.status == ReadStatus::End); + assert_eq!(result.line_count, 2); + assert_eq!(&buffer[..result.read], b"b\na\n"); + } + #[test] fn retry_uses_fewer_complete_records() { for &separator in b"\n\0" {