diff --git a/crates/bashkit/docs/threat-model.md b/crates/bashkit/docs/threat-model.md index 7614b2217..e605d5735 100644 --- a/crates/bashkit/docs/threat-model.md +++ b/crates/bashkit/docs/threat-model.md @@ -34,7 +34,7 @@ through configurable limits. | Width-derived allocation (TM-DOS-103) | `printf x \| od -w1152921504606846976` | Reject widths above 65,536 bytes; stack-pad one numeric field; budget output capacity before fallible growth | MITIGATED | | Pagination amplification (TM-DOS-137) | Long `pr -h` headers repeated on many short pages | Check the 16 MiB cap before every append; lease input, rows and output capacity before growth; borrow cells/page slices and retain date timestamps; charge input/work and poll cancellation/deadlines, including skipped pages | MITIGATED | | Embedded CLI limit escalation (TM-DOS-139) | `markkit extract x --max-input-size 99999999999` | `markkit` limits can only be lowered below their defaults; `fetchkit` bodies capped by HTTP limits; `--ocr` refused | MITIGATED | -| Tree-walk memory (TM-DOS-140) | `find`, `du` or `rg` over a tree with millions of files | `FileSystem::walk` answers are bounded batches (10k entries) refilled as `find`/`du` descend; `rg` charges each file to the aggregate-input budget as it reads, stops at the first refusal and streams its walk; `ls -R` stops at the stdout limit | MITIGATED | +| Tree-walk memory (TM-DOS-140) | `find`, `du` or `rg` over a tree with millions of files | `FileSystem::walk` answers are bounded batches (10k entries) refilled as `find`/`du` descend; `rg` searches each file as it reads it without holding the text, charges it to the aggregate-input budget, stops at the first refusal and streams its walk; `ls -R` stops at the stdout limit | MITIGATED | | Variable explosion (TM-DOS-003) | `x=$(cat /dev/urandom)` | /dev/urandom returns bounded 8KB | MITIGATED | | Array growth (TM-DOS-004) | `arr+=(element)` in loop | Command limit | MITIGATED | diff --git a/crates/bashkit/src/builtins/rg/mod.rs b/crates/bashkit/src/builtins/rg/mod.rs index 35c2aa81a..7ce1af466 100644 --- a/crates/bashkit/src/builtins/rg/mod.rs +++ b/crates/bashkit/src/builtins/rg/mod.rs @@ -3014,20 +3014,21 @@ async fn collect_rg_inputs( ctx: Context<'_>, opts: &RgOptions, budget: &mut RgReadBudget, -) -> std::result::Result { + out: &mut RgSearch<'_>, +) -> std::result::Result<(), ExecResult> { if opts.paths.is_empty() { if !opts.stdin_consumed_for_patterns && let Some(stdin) = ctx.stdin { let stdin = stdin.to_string(); budget.charge(stdin.len()); - return Ok(RgCollectedInputs::new(vec![RgInput::explicit( - "(stdin)", stdin, - )])); + out.push(RgInput::explicit("(stdin)", stdin)); + return Ok(()); } if let Some(inputs) = try_indexed_search(&*ctx.fs, opts, ctx.cwd, budget).await { - return Ok(RgCollectedInputs::new(inputs)); + inputs.into_iter().for_each(|input| out.push(input)); + return Ok(()); } let root = RgSearchRoot { @@ -3035,14 +3036,15 @@ async fn collect_rg_inputs( actual: ctx.cwd.to_path_buf(), display_hint: RgDisplayHint::None, }; - return Ok(stream_rg_root(&*ctx.fs, root, opts, ctx.cwd, budget).await); + stream_rg_roots(&*ctx.fs, vec![root], opts, ctx.cwd, budget, out).await; + return Ok(()); } if let Some(inputs) = try_indexed_search(&*ctx.fs, opts, ctx.cwd, budget).await { - return Ok(RgCollectedInputs::new(inputs)); + inputs.into_iter().for_each(|input| out.push(input)); + return Ok(()); } - let mut collected = RgCollectedInputs::default(); let mut candidates = Vec::new(); let mut roots = Vec::new(); for p in &opts.paths { @@ -3066,62 +3068,41 @@ async fn collect_rg_inputs( }); } None => { - if budget.exhausted() { + if budget.exhausted() || out.stopped() { break; } - let text = match read_rg_text_file(&*ctx.fs, &path, ctx.cwd, p, opts).await { - Ok(t) => t, - Err(e) => { - collected.had_errors = true; - if opts.messages { - collected.stderr.push_str(&e.stderr); - } - continue; + match read_rg_text_file(&*ctx.fs, &path, ctx.cwd, p, opts).await { + Ok(text) => { + budget.charge(text.len()); + out.push(RgInput::explicit( + apply_path_separator_to_display(p, opts), + text, + )); } - }; - budget.charge(text.len()); - collected.inputs.push(RgInput::explicit( - apply_path_separator_to_display(p, opts), - text, - )); + Err(e) => out.error(&e.stderr), + } } } } - let path_order = opts.sort == RgSort::Path && !opts.sort_reverse; - if path_order - && roots.len() == 1 - && let Some(root) = roots.pop() - { - // Explicit files come first, then the one root's walk in path order: - // read them as found instead of holding every candidate. - let read = read_rg_files(&*ctx.fs, candidates, ctx.cwd, opts, budget).await; - collected.had_errors |= read.had_errors; - collected.stderr.push_str(&read.stderr); - collected.inputs.extend(read.inputs); - let read = stream_rg_root(&*ctx.fs, root, opts, ctx.cwd, budget).await; - collected.had_errors |= read.had_errors; - collected.stderr.push_str(&read.stderr); - collected.inputs.extend(read.inputs); - return Ok(collected); + if opts.sort == RgSort::Path && !opts.sort_reverse { + // Explicit files come first, then the roots' walks in path order. + read_rg_files(&*ctx.fs, candidates, ctx.cwd, opts, budget, out).await; + stream_rg_roots(&*ctx.fs, roots, opts, ctx.cwd, budget, out).await; + return Ok(()); } if !roots.is_empty() { candidates.extend(collect_rg_files_recursive(&*ctx.fs, &roots, opts, ctx.cwd).await); } - if !path_order { - sort_rg_candidates(&mut candidates, opts); - } - let read = read_rg_files(&*ctx.fs, candidates, ctx.cwd, opts, budget).await; - collected.had_errors |= read.had_errors; - collected.stderr.push_str(&read.stderr); - collected.inputs.extend(read.inputs); - Ok(collected) + sort_rg_candidates(&mut candidates, opts); + read_rg_files(&*ctx.fs, candidates, ctx.cwd, opts, budget, out).await; + Ok(()) } /// Charges file contents to the execution budget as they are read. /// -/// THREAT[TM-DOS-140]: rg holds every searched file's text until output is -/// built, so a tree bigger than the input budget must stop at the budget, -/// not load everything first and fail after. Reading stops at the first +/// THREAT[TM-DOS-140]: rg searches each file as it reads it (`RgSearch`), but +/// the budget still bounds the total read, so a tree bigger than it stops at +/// the budget instead of reading everything. Reading stops at the first /// refused charge; the caller turns it into the limit error. struct RgReadBudget { budget: Option, @@ -3164,13 +3145,6 @@ impl RgReadBudget { } } -#[derive(Default)] -struct RgCollectedInputs { - inputs: Vec, - stderr: String, - had_errors: bool, -} - struct RgInput { display: String, content: String, @@ -3195,15 +3169,6 @@ impl RgInput { } } -impl RgCollectedInputs { - fn new(inputs: Vec) -> Self { - Self { - inputs, - ..Default::default() - } - } -} - async fn load_rg_pattern_files( fs: &dyn crate::fs::FileSystem, cwd: &Path, @@ -3787,7 +3752,7 @@ async fn collect_rg_files_recursive( } /// Where the walk hands each file it accepts. -enum RgSink<'a> { +enum RgSink<'a, 'b> { /// Keep candidates for the caller to sort or list. Collect(Vec), /// Read each file as it is found. THREAT[TM-DOS-140]: on a huge tree the @@ -3797,11 +3762,11 @@ enum RgSink<'a> { Read { cwd: &'a Path, budget: &'a mut RgReadBudget, - out: RgCollectedInputs, + out: &'a mut RgSearch<'b>, }, } -impl RgSink<'_> { +impl RgSink<'_, '_> { async fn push( &mut self, fs: &dyn crate::fs::FileSystem, @@ -3817,7 +3782,7 @@ impl RgSink<'_> { } fn stopped(&self) -> bool { - matches!(self, Self::Read { budget, .. } if budget.exhausted()) + matches!(self, Self::Read { budget, out, .. } if budget.exhausted() || out.stopped()) } } @@ -3838,7 +3803,7 @@ async fn enter_rg_walk_item( opts: &RgOptions, cwd: &Path, stack: &mut Vec, - sink: &mut RgSink<'_>, + sink: &mut RgSink<'_, '_>, ) { // List first: the listing says which ignore files exist, so missing // ones cost no lookup (one `read_dir` per directory on remote VFSes). @@ -3903,7 +3868,7 @@ async fn walk_rg_files( roots: &[RgSearchRoot], opts: &RgOptions, cwd: &Path, - sink: &mut RgSink<'_>, + sink: &mut RgSink<'_, '_>, ) { let mut stack: Vec = Vec::new(); for root in roots { @@ -4107,64 +4072,67 @@ async fn read_rg_files( cwd: &Path, opts: &RgOptions, budget: &mut RgReadBudget, -) -> RgCollectedInputs { - let mut collected = RgCollectedInputs::default(); + out: &mut RgSearch<'_>, +) { for file in files { - if budget.exhausted() { + if budget.exhausted() || out.stopped() { break; } - read_rg_candidate(fs, file, cwd, opts, budget, &mut collected).await; + read_rg_candidate(fs, file, cwd, opts, budget, out).await; } - collected } -/// Walk one root in path order, reading each file as it is found. -async fn stream_rg_root( +/// Walk roots in path order, searching each file as it is found. +/// +/// THREAT[TM-DOS-140]: neither the candidate list nor the searched text is +/// held; memory stays at the output plus the walk's open directories. +/// Roots are walked one after another in path order, which equals the +/// global path sort unless one root lies inside another (or repeats); that +/// case keeps the collected, globally sorted list. +async fn stream_rg_roots( fs: &dyn crate::fs::FileSystem, - root: RgSearchRoot, + mut roots: Vec, opts: &RgOptions, cwd: &Path, budget: &mut RgReadBudget, -) -> RgCollectedInputs { - if opts.sort != RgSort::Path || opts.sort_reverse { - let files = collect_rg_files_recursive(fs, &[root], opts, cwd).await; - return read_rg_files(fs, files, cwd, opts, budget).await; + out: &mut RgSearch<'_>, +) { + roots.sort_by(|a, b| a.logical.cmp(&b.logical)); + let nested = roots + .windows(2) + .any(|w| w[1].logical.starts_with(&w[0].logical)); + if nested { + let files = collect_rg_files_recursive(fs, &roots, opts, cwd).await; + read_rg_files(fs, files, cwd, opts, budget, out).await; + return; } - let mut sink = RgSink::Read { - cwd, - budget, - out: RgCollectedInputs::default(), - }; - walk_rg_files(fs, &[root], opts, cwd, &mut sink).await; - match sink { - RgSink::Read { out, .. } => out, - RgSink::Collect(_) => RgCollectedInputs::default(), + let mut sink = RgSink::Read { cwd, budget, out }; + for root in roots { + walk_rg_files(fs, std::slice::from_ref(&root), opts, cwd, &mut sink).await; + if sink.stopped() { + break; + } } } -/// Read one candidate into `out`, charging `budget` (nothing once spent). +/// Read and search one candidate, charging `budget` (nothing once spent). async fn read_rg_candidate( fs: &dyn crate::fs::FileSystem, file: RgFileCandidate, cwd: &Path, opts: &RgOptions, budget: &mut RgReadBudget, - out: &mut RgCollectedInputs, + out: &mut RgSearch<'_>, ) { - if budget.exhausted() { + if budget.exhausted() || out.stopped() { return; } let display = candidate_display_path(&file, cwd, opts); match read_rg_text_file(fs, &file.actual, cwd, &display, opts).await { Ok(text) if !budget.charge(text.len()) => {} - Ok(text) if file.explicit => out.inputs.push(RgInput::explicit(display, text)), - Ok(text) => out.inputs.push(RgInput::discovered(display, text)), - Err(e) => { - out.had_errors = true; - if opts.messages { - out.stderr.push_str(&e.stderr); - } - } + Ok(text) if file.explicit => out.push(RgInput::explicit(display, text)), + Ok(text) => out.push(RgInput::discovered(display, text)), + Err(e) => out.error(&e.stderr), } } @@ -5772,21 +5740,12 @@ impl Builtin for Rg { .execution_budget() .and_then(|budget| budget.try_with(Clone::clone).ok()); let mut read_budget = RgReadBudget::new(execution_budget); - let collected_inputs = match collect_rg_inputs(ctx, &opts, &mut read_budget).await { - Ok(inputs) => inputs, - Err(result) => return Ok(result), - }; - if let Some(exceeded) = read_budget.exceeded { - return Err(exceeded.into()); - } - let inputs = collected_inputs.inputs; - let show_filename = if opts.no_filename { false } else if opts.show_filename { true } else { - recursive_output || inputs.len() > 1 || opts.paths.len() > 1 + recursive_output || opts.paths.len() > 1 }; let has_context = opts.before_context > 0 || opts.after_context > 0; let json_output = opts.json @@ -5795,16 +5754,159 @@ impl Builtin for Rg { && !opts.files_with_matches && !opts.files_without_matches; - let mut output = String::new(); - let mut any_match = false; - let mut json_bytes_searched = 0usize; - let mut json_matched_lines = 0usize; - let mut json_matches = 0usize; - let mut json_searches = 0usize; - let mut json_searches_with_match = 0usize; - let mut stats = RgSearchStats::default(); - - for input in &inputs { + let mut search = RgSearch { + opts: &opts, + regex: ®ex, + output_limit, + show_filename, + has_context, + json_output, + output: String::new(), + any_match: false, + json_bytes_searched: 0, + json_matched_lines: 0, + json_matches: 0, + json_searches: 0, + json_searches_with_match: 0, + stats: RgSearchStats::default(), + stderr: String::new(), + had_errors: false, + done: None, + }; + if let Err(result) = collect_rg_inputs(ctx, &opts, &mut read_budget, &mut search).await { + return Ok(result); + } + if let Some(result) = search.done { + return Ok(result); + } + if let Some(exceeded) = read_budget.exceeded { + return Err(exceeded.into()); + } + let RgSearch { + mut output, + any_match, + json_bytes_searched, + json_matched_lines, + json_matches, + json_searches, + json_searches_with_match, + stats, + stderr, + had_errors, + .. + } = search; + + if json_output { + write_rg_json_summary( + &mut output, + json_bytes_searched, + json_matched_lines, + json_matches, + json_searches, + json_searches_with_match, + ); + } else if opts.stats { + let bytes_printed = if opts.count_only + || opts.count_matches + || opts.files_with_matches + || opts.files_without_matches + || opts.quiet + { + 0 + } else { + output.len() + }; + append_rg_stats(&mut output, &stats, bytes_printed); + } + + truncate_rg_output(&mut output, output_limit); + + let exit_code = if had_errors { + 2 + } else if any_match { + 0 + } else { + 1 + }; + Ok(ExecResult { + stdout: output.into(), + stderr: stderr.into(), + exit_code, + ..Default::default() + }) + } +} + +/// Search state for one rg run. Inputs are searched as they are read and +/// dropped right after, so memory holds the output, not the searched text. +/// +/// THREAT[TM-DOS-140]: a search over millions of files must not keep every +/// file's text until output is built. +struct RgSearch<'a> { + opts: &'a RgOptions, + regex: &'a RgMatcher, + output_limit: usize, + show_filename: bool, + has_context: bool, + json_output: bool, + output: String, + any_match: bool, + json_bytes_searched: usize, + json_matched_lines: usize, + json_matches: usize, + json_searches: usize, + json_searches_with_match: usize, + stats: RgSearchStats, + stderr: String, + had_errors: bool, + /// Set when a mode such as `-q` decided the result early; reading stops. + done: Option, +} + +impl RgSearch<'_> { + /// Search one input now (nothing once a result is decided). + fn push(&mut self, input: RgInput) { + if self.done.is_none() { + self.done = self.search(&input); + } + } + + fn error(&mut self, stderr: &str) { + self.had_errors = true; + if self.opts.messages { + self.stderr.push_str(stderr); + } + } + + fn stopped(&self) -> bool { + self.done.is_some() + } + + #[allow(clippy::never_loop)] + fn search(&mut self, input: &RgInput) -> Option { + let Self { + opts, + regex, + output_limit, + show_filename, + has_context, + json_output, + output, + any_match, + json_bytes_searched, + json_matched_lines, + json_matches, + json_searches, + json_searches_with_match, + stats, + stderr, + .. + } = self; + let (opts, regex) = (*opts, *regex); + let (output_limit, show_filename, has_context, json_output) = + (*output_limit, *show_filename, *has_context, *json_output); + // One pass; `continue` ends this input like the old per-input loop. + for input in std::iter::once(input) { let filename = input.display.as_str(); let content = input.content.as_str(); let mut match_count = 0usize; @@ -5814,7 +5916,7 @@ impl Builtin for Rg { let binary_offset = first_nul_offset(content).filter(|_| !opts.text); let json_binary_search = binary_offset.is_some() && json_output; if json_binary_search { - json_searches += 1; + *json_searches += 1; if !opts.binary && !input.explicit { continue; } @@ -5831,22 +5933,20 @@ impl Builtin for Rg { let matched = if opts.invert_match { !matched } else { matched }; if !matched { if opts.quiet { - if let Some(result) = - rg_quiet_result(&opts, 0, &mut any_match, &collected_inputs.stderr) - { - return Ok(result); + if let Some(result) = rg_quiet_result(opts, 0, any_match, stderr.as_str()) { + return Some(result); } continue; } if opts.files_without_matches { - any_match = true; + *any_match = true; output.push_str(&color_path( filename, opts.color_enabled(), &opts.color_scheme, )); output.push(if opts.null { '\0' } else { '\n' }); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } else if (opts.count_only || opts.count_matches) && opts.include_zero { if show_filename { output.push_str(&color_path( @@ -5861,15 +5961,13 @@ impl Builtin for Rg { continue; } - any_match = true; + *any_match = true; stats.matches += 1; stats.matched_lines += 1; stats.files_with_matches += 1; if opts.quiet { - if let Some(result) = - rg_quiet_result(&opts, 1, &mut any_match, &collected_inputs.stderr) - { - return Ok(result); + if let Some(result) = rg_quiet_result(opts, 1, any_match, stderr.as_str()) { + return Some(result); } continue; } @@ -5883,7 +5981,7 @@ impl Builtin for Rg { &opts.color_scheme, )); output.push(if opts.null { '\0' } else { '\n' }); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } if opts.count_only || opts.count_matches { @@ -5928,7 +6026,7 @@ impl Builtin for Rg { let search_lines = split_rg_lines(search_content, opts.crlf, opts.null_data); let display_lines = split_rg_lines(content, opts.crlf, opts.null_data); let mut file_matches = 0usize; - json_bytes_searched += nul_offset; + *json_bytes_searched += nul_offset; stats.bytes_searched += nul_offset; for (line_idx, line) in search_lines.iter().enumerate() { @@ -5950,45 +6048,45 @@ impl Builtin for Rg { 1 }; file_matches += matches_on_line; - json_matches += matches_on_line; - json_matched_lines += 1; + *json_matches += matches_on_line; + *json_matched_lines += 1; stats.matches += matches_on_line; stats.matched_lines += 1; match_lines.push(line_idx); - any_match = true; + *any_match = true; } if match_count > 0 { stats.files_with_matches += 1; - write_rg_json_begin(&mut output, filename); + write_rg_json_begin(output, filename); for &line_idx in &match_lines { let display_line = display_lines .get(line_idx) .copied() .unwrap_or(search_lines[line_idx]); write_rg_json_match_with_text( - &mut output, + output, filename, display_line, line_idx, - ®ex, + regex, opts.replacement.as_deref(), search_lines[line_idx].match_text, ); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); if output.len() >= output_limit { break; } } write_rg_json_end( - &mut output, + output, filename, binary_offset, nul_offset, match_count, file_matches, ); - json_searches_with_match += 1; + *json_searches_with_match += 1; } continue; } @@ -5999,10 +6097,10 @@ impl Builtin for Rg { } else { content }; - let record_terminator = rg_record_terminator(&opts); - json_bytes_searched += content.len(); + let record_terminator = rg_record_terminator(opts); + *json_bytes_searched += content.len(); if !json_binary_search { - json_searches += 1; + *json_searches += 1; } stats.bytes_searched += content.len(); @@ -6022,18 +6120,15 @@ impl Builtin for Rg { stats.matched_lines += 1; stats.files_with_matches += 1; if !opts.files_without_matches { - any_match = true; + *any_match = true; } } if opts.quiet { - if let Some(result) = rg_quiet_result( - &opts, - match_count, - &mut any_match, - &collected_inputs.stderr, - ) { - return Ok(result); + if let Some(result) = + rg_quiet_result(opts, match_count, any_match, stderr.as_str()) + { + return Some(result); } continue; } @@ -6052,7 +6147,7 @@ impl Builtin for Rg { } if opts.files_without_matches { if !matched { - any_match = true; + *any_match = true; output.push_str(&color_path( filename, opts.color_enabled(), @@ -6116,7 +6211,7 @@ impl Builtin for Rg { stats.matches += matches_on_line; stats.matched_lines += 1; if !opts.files_without_matches { - any_match = true; + *any_match = true; } if (opts.files_with_matches || opts.files_without_matches || opts.quiet) @@ -6131,13 +6226,10 @@ impl Builtin for Rg { } if opts.quiet { - if let Some(result) = rg_quiet_result( - &opts, - match_count, - &mut any_match, - &collected_inputs.stderr, - ) { - return Ok(result); + if let Some(result) = + rg_quiet_result(opts, match_count, any_match, stderr.as_str()) + { + return Some(result); } continue; } @@ -6156,7 +6248,7 @@ impl Builtin for Rg { } if opts.files_without_matches { if match_count == 0 { - any_match = true; + *any_match = true; output.push_str(&color_path( filename, opts.color_enabled(), @@ -6184,7 +6276,7 @@ impl Builtin for Rg { } output.push_str(&count_value.to_string()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } } @@ -6203,7 +6295,7 @@ impl Builtin for Rg { } else { opts.max_count }; - let matches = collect_rg_multiline_matches(®ex, content, &lines, collect_limit); + let matches = collect_rg_multiline_matches(regex, content, &lines, collect_limit); let match_line_indices = rg_multiline_match_lines(&matches); let context_match_lines = rg_unique_sorted_lines(&match_line_indices); @@ -6229,25 +6321,22 @@ impl Builtin for Rg { } else { 0 }; - json_matched_lines += inverted_match_lines.len(); + *json_matched_lines += inverted_match_lines.len(); stats.matches += inverted_matches; stats.matched_lines += inverted_match_lines.len(); if match_count > 0 { stats.files_with_matches += 1; if !opts.files_without_matches { - any_match = true; + *any_match = true; } } if opts.quiet { - if let Some(result) = rg_quiet_result( - &opts, - match_count, - &mut any_match, - &collected_inputs.stderr, - ) { - return Ok(result); + if let Some(result) = + rg_quiet_result(opts, match_count, any_match, stderr.as_str()) + { + return Some(result); } continue; } @@ -6266,7 +6355,7 @@ impl Builtin for Rg { } if opts.files_without_matches { if match_count == 0 { - any_match = true; + *any_match = true; output.push_str(&color_path( filename, opts.color_enabled(), @@ -6282,30 +6371,30 @@ impl Builtin for Rg { } if json_output { if match_count > 0 { - write_rg_json_begin(&mut output, filename); + write_rg_json_begin(output, filename); for &line_idx in &inverted_match_lines { write_rg_json_match( - &mut output, + output, filename, lines[line_idx], line_idx, - ®ex, + regex, opts.replacement.as_deref(), ); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); if output.len() >= output_limit { break; } } write_rg_json_end( - &mut output, + output, filename, binary_offset, content.len(), inverted_match_lines.len(), 0, ); - json_searches_with_match += 1; + *json_searches_with_match += 1; } continue; } @@ -6323,7 +6412,7 @@ impl Builtin for Rg { } output.push_str(&count_value.to_string()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } if opts.quiet { @@ -6333,7 +6422,7 @@ impl Builtin for Rg { let line_show_filename = if opts.heading && show_filename && match_count > 0 { if !output.is_empty() { output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } output.push_str(&color_path( filename, @@ -6341,7 +6430,7 @@ impl Builtin for Rg { &opts.color_scheme, )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); false } else { show_filename @@ -6354,22 +6443,22 @@ impl Builtin for Rg { { output.push_str(&opts.context_separator); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } write_rg_context( - &mut output, + output, filename, - ®ex, + regex, &lines, &inverted_match_lines, - &opts, + opts, line_show_filename, output_limit, ); } else { for &line_idx in &inverted_match_lines { write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -6391,13 +6480,13 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( lines[line_idx].text, lines[line_idx].match_text, - ®ex, - &opts, + regex, + opts, true, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } } continue; @@ -6405,26 +6494,23 @@ impl Builtin for Rg { match_count = matches.len(); count_value = matches.len(); - json_matches += matches.len(); - json_matched_lines += match_line_indices.len(); + *json_matches += matches.len(); + *json_matched_lines += match_line_indices.len(); stats.matches += matches.len(); stats.matched_lines += match_line_indices.len(); if match_count > 0 { stats.files_with_matches += 1; if !opts.files_without_matches { - any_match = true; + *any_match = true; } } if opts.quiet { - if let Some(result) = rg_quiet_result( - &opts, - match_count, - &mut any_match, - &collected_inputs.stderr, - ) { - return Ok(result); + if let Some(result) = + rg_quiet_result(opts, match_count, any_match, stderr.as_str()) + { + return Some(result); } continue; } @@ -6443,7 +6529,7 @@ impl Builtin for Rg { } if opts.files_without_matches { if match_count == 0 { - any_match = true; + *any_match = true; output.push_str(&color_path( filename, opts.color_enabled(), @@ -6459,7 +6545,7 @@ impl Builtin for Rg { } if json_output { if match_count > 0 { - write_rg_json_begin(&mut output, filename); + write_rg_json_begin(output, filename); let match_line_set: HashSet = context_match_lines.iter().copied().collect(); let context_lines = if opts.passthru { @@ -6478,7 +6564,7 @@ impl Builtin for Rg { Vec::new() }; if context_lines.len() > RG_MAX_JSON_CONTEXT_EVENTS { - return Ok(ExecResult::err( + return Some(ExecResult::err( "rg: too many JSON context events (output capped)\n".to_string(), 2, )); @@ -6486,14 +6572,14 @@ impl Builtin for Rg { if context_lines.is_empty() { for &mat in &matches { write_rg_json_multiline_match( - &mut output, + output, filename, &lines, mat, - ®ex, + regex, opts.replacement.as_deref(), ); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); if output.len() >= output_limit { break; } @@ -6509,36 +6595,36 @@ impl Builtin for Rg { for line_idx in event_lines { if let Some(mat) = match_by_start_line.get(&line_idx).copied() { write_rg_json_multiline_match( - &mut output, + output, filename, &lines, mat, - ®ex, + regex, opts.replacement.as_deref(), ); } else { write_rg_json_context( - &mut output, + output, filename, lines[line_idx], line_idx, ); } - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); if output.len() >= output_limit { break; } } } write_rg_json_end( - &mut output, + output, filename, binary_offset, content.len(), match_line_indices.len(), matches.len(), ); - json_searches_with_match += 1; + *json_searches_with_match += 1; } continue; } @@ -6556,7 +6642,7 @@ impl Builtin for Rg { } output.push_str(&count_value.to_string()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } if opts.quiet { @@ -6566,7 +6652,7 @@ impl Builtin for Rg { let line_show_filename = if opts.heading && show_filename && match_count > 0 { if !output.is_empty() { output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } output.push_str(&color_path( filename, @@ -6574,7 +6660,7 @@ impl Builtin for Rg { &opts.color_scheme, )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); false } else { show_filename @@ -6606,9 +6692,9 @@ impl Builtin for Rg { continue; } for &mat in line_matches { - let segments = rg_multiline_match_segments(mat, ®ex, &opts); + let segments = rg_multiline_match_segments(mat, regex, opts); write_rg_multiline_match_segments( - &mut output, + output, mat, &segments, RgMultilineMatchPrefix { @@ -6641,7 +6727,7 @@ impl Builtin for Rg { opts.field_context_separator.as_str() }; write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -6663,21 +6749,21 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( line.text, line.match_text, - ®ex, - &opts, + regex, + opts, matched, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); line_idx += 1; } } else if opts.vimgrep { for mat in &matches { if opts.only_matching { - let segments = rg_multiline_match_segments(*mat, ®ex, &opts); + let segments = rg_multiline_match_segments(*mat, regex, opts); write_rg_multiline_match_segments( - &mut output, + output, *mat, &segments, RgMultilineMatchPrefix { @@ -6698,7 +6784,7 @@ impl Builtin for Rg { continue; } write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: true, @@ -6716,19 +6802,19 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( lines[mat.line_idx].text, lines[mat.line_idx].match_text, - ®ex, - &opts, + regex, + opts, true, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } } else if opts.only_matching { for mat in &matches { - let segments = rg_multiline_match_segments(*mat, ®ex, &opts); + let segments = rg_multiline_match_segments(*mat, regex, opts); write_rg_multiline_match_segments( - &mut output, + output, *mat, &segments, RgMultilineMatchPrefix { @@ -6755,22 +6841,22 @@ impl Builtin for Rg { { output.push_str(&opts.context_separator); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } write_rg_context( - &mut output, + output, filename, - ®ex, + regex, &lines, &context_match_lines, - &opts, + opts, line_show_filename, output_limit, ); } else if let Some(replacement) = &opts.replacement { for mat in &matches { write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -6790,13 +6876,13 @@ impl Builtin for Rg { }, ); output.push_str(&format_rg_multiline_replacement( - ®ex, + regex, &lines, *mat, replacement, )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } } else { let mut seen_line_indices = HashSet::new(); @@ -6811,7 +6897,7 @@ impl Builtin for Rg { continue; } write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -6833,13 +6919,13 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( line.text, line.match_text, - ®ex, - &opts, + regex, + opts, true, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } } } @@ -6879,13 +6965,13 @@ impl Builtin for Rg { count_value += 1; } if !opts.invert_match { - json_matches += matches_on_line; + *json_matches += matches_on_line; } stats.matches += matches_on_line; stats.matched_lines += 1; match_lines.push(line_idx); if !opts.files_without_matches { - any_match = true; + *any_match = true; } if (opts.files_with_matches || opts.files_without_matches || opts.quiet) @@ -6900,10 +6986,9 @@ impl Builtin for Rg { } if opts.quiet { - if let Some(result) = - rg_quiet_result(&opts, match_count, &mut any_match, &collected_inputs.stderr) + if let Some(result) = rg_quiet_result(opts, match_count, any_match, stderr.as_str()) { - return Ok(result); + return Some(result); } continue; } @@ -6922,7 +7007,7 @@ impl Builtin for Rg { } if opts.files_without_matches { if match_count == 0 { - any_match = true; + *any_match = true; output.push_str(&color_path( filename, opts.color_enabled(), @@ -6938,7 +7023,7 @@ impl Builtin for Rg { } if json_output { if match_count > 0 { - write_rg_json_begin(&mut output, filename); + write_rg_json_begin(output, filename); let match_line_set: HashSet = match_lines.iter().copied().collect(); let context_lines = if opts.passthru { (0..lines.len()) @@ -6956,7 +7041,7 @@ impl Builtin for Rg { Vec::new() }; if context_lines.len() > RG_MAX_JSON_CONTEXT_EVENTS { - return Ok(ExecResult::err( + return Some(ExecResult::err( "rg: too many JSON context events (output capped)\n".to_string(), 2, )); @@ -6964,14 +7049,14 @@ impl Builtin for Rg { if context_lines.is_empty() { for &line_idx in &match_lines { write_rg_json_match( - &mut output, + output, filename, lines[line_idx], line_idx, - ®ex, + regex, opts.replacement.as_deref(), ); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); if output.len() >= output_limit { break; } @@ -6982,29 +7067,24 @@ impl Builtin for Rg { for line_idx in event_lines { if match_line_set.contains(&line_idx) { write_rg_json_match( - &mut output, + output, filename, lines[line_idx], line_idx, - ®ex, + regex, opts.replacement.as_deref(), ); } else { - write_rg_json_context( - &mut output, - filename, - lines[line_idx], - line_idx, - ); + write_rg_json_context(output, filename, lines[line_idx], line_idx); } - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); if output.len() >= output_limit { break; } } } write_rg_json_end( - &mut output, + output, filename, binary_offset, content.len(), @@ -7014,8 +7094,8 @@ impl Builtin for Rg { .map(|&line_idx| regex.count_matches(lines[line_idx].match_text)) .sum(), ); - json_matched_lines += match_lines.len(); - json_searches_with_match += 1; + *json_matched_lines += match_lines.len(); + *json_searches_with_match += 1; } continue; } @@ -7033,7 +7113,7 @@ impl Builtin for Rg { } output.push_str(&count_value.to_string()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } if opts.quiet { @@ -7043,7 +7123,7 @@ impl Builtin for Rg { let line_show_filename = if opts.heading && show_filename && match_count > 0 { if !output.is_empty() { output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } output.push_str(&color_path( filename, @@ -7051,7 +7131,7 @@ impl Builtin for Rg { &opts.color_scheme, )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); false } else { show_filename @@ -7069,12 +7149,12 @@ impl Builtin for Rg { { output.push_str(&rg_replacement_cap_marker()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } regex.for_each_match(line.match_text, |mat| { write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -7097,7 +7177,7 @@ impl Builtin for Rg { hyperlink_format: opts.hyperlink_format.as_deref(), }, ); - output.push_str(&format_rg_match_text(mat.as_str(), ®ex, &opts)); + output.push_str(&format_rg_match_text(mat.as_str(), regex, opts)); output.push(record_terminator); true }); @@ -7109,7 +7189,7 @@ impl Builtin for Rg { opts.field_context_separator.as_str() }; write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -7135,13 +7215,13 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( line.text, line.match_text, - ®ex, - &opts, + regex, + opts, matched, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } } else if opts.vimgrep && !opts.invert_match { for &line_idx in &match_lines { @@ -7154,7 +7234,7 @@ impl Builtin for Rg { { output.push_str(&rg_replacement_cap_marker()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } let mut output_col_offset: usize = 0; @@ -7165,7 +7245,7 @@ impl Builtin for Rg { mat.start() + 1 }; write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: true, @@ -7181,7 +7261,7 @@ impl Builtin for Rg { }, ); if opts.only_matching { - let formatted = format_rg_match_text(mat.as_str(), ®ex, &opts); + let formatted = format_rg_match_text(mat.as_str(), regex, opts); if opts.replacement.is_some() { let orig_len = mat.as_str().len(); let repl_len = formatted.len(); @@ -7197,14 +7277,14 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( lines[line_idx].text, lines[line_idx].match_text, - ®ex, - &opts, + regex, + opts, true, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); } output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); true }); } @@ -7218,12 +7298,12 @@ impl Builtin for Rg { { output.push_str(&rg_replacement_cap_marker()); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); continue; } regex.for_each_match(lines[line_idx].match_text, |mat| { write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -7250,10 +7330,10 @@ impl Builtin for Rg { output .push_str(®ex.replace_first(mat.as_str(), replacement.as_str())); } else { - output.push_str(&color_matches(mat.as_str(), ®ex, &opts)); + output.push_str(&color_matches(mat.as_str(), regex, opts)); } output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); true }); } @@ -7265,22 +7345,22 @@ impl Builtin for Rg { { output.push_str(&opts.context_separator); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } write_rg_context( - &mut output, + output, filename, - ®ex, + regex, &lines, &match_lines, - &opts, + opts, line_show_filename, output_limit, ); } else { for &line_idx in &match_lines { write_rg_prefix( - &mut output, + output, RgPrefix { filename, show_filename: line_show_filename, @@ -7308,55 +7388,17 @@ impl Builtin for Rg { output.push_str(&format_rg_output_line( lines[line_idx].text, lines[line_idx].match_text, - ®ex, - &opts, + regex, + opts, true, - rg_output_remaining(&output, output_limit), + rg_output_remaining(output, output_limit), )); output.push(record_terminator); - truncate_rg_output(&mut output, output_limit); + truncate_rg_output(output, output_limit); } } } - - if json_output { - write_rg_json_summary( - &mut output, - json_bytes_searched, - json_matched_lines, - json_matches, - json_searches, - json_searches_with_match, - ); - } else if opts.stats { - let bytes_printed = if opts.count_only - || opts.count_matches - || opts.files_with_matches - || opts.files_without_matches - || opts.quiet - { - 0 - } else { - output.len() - }; - append_rg_stats(&mut output, &stats, bytes_printed); - } - - truncate_rg_output(&mut output, output_limit); - - let exit_code = if collected_inputs.had_errors { - 2 - } else if any_match { - 0 - } else { - 1 - }; - Ok(ExecResult { - stdout: output.into(), - stderr: collected_inputs.stderr.into(), - exit_code, - ..Default::default() - }) + None } } diff --git a/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs b/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs index 442183941..d6f178088 100644 --- a/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs +++ b/crates/bashkit/tests/integration/remote_fs_round_trip_tests.rs @@ -651,3 +651,30 @@ async fn nested_mount_below_search_root_disables_the_index() { ); assert_eq!(c.search, 0, "{c}"); } + +/// rg searches each file as it reads it: `-q` stops the walk at the first +/// match instead of reading the whole tree first. +#[tokio::test] +async fn rg_quiet_stops_reading_at_the_first_match() { + let (fs, mut bash) = setup(CountingFs::new()).await; + let (c, _) = run(&fs, &mut bash, "rg -q needle tree").await; + // The first needle is file 0; ignore-file probes aside, a few reads. + assert!(c.read_file < 10, "{c}"); + let (_, out) = run(&fs, &mut bash, "rg -q needle tree; echo $?").await; + assert_eq!(out, "0\n"); +} + +/// Several roots stream one after another in path order, with the same +/// output as one globally sorted walk; nested roots keep that order too. +#[tokio::test] +async fn rg_several_roots_keep_path_order() { + let (fs, mut bash) = setup(CountingFs::new()).await; + let (_, all) = run(&fs, &mut bash, "rg -l needle tree | grep -E '^tree/d[01]/'").await; + let (_, split) = run(&fs, &mut bash, "rg -l needle tree/d1 tree/d0").await; + assert_eq!(split, all); + assert!(!split.is_empty()); + let (_, nested) = run(&fs, &mut bash, "rg -l needle tree/d0/s1 tree/d0").await; + let mut sorted: Vec<&str> = nested.lines().collect(); + sorted.sort(); + assert_eq!(nested.lines().collect::>(), sorted); +} diff --git a/crates/bashkit/tests/large_tree_stress_tests.rs b/crates/bashkit/tests/large_tree_stress_tests.rs index 55b508660..7dd046f0e 100644 --- a/crates/bashkit/tests/large_tree_stress_tests.rs +++ b/crates/bashkit/tests/large_tree_stress_tests.rs @@ -411,32 +411,30 @@ async fn rg_stops_at_the_input_budget_on_a_huge_tree() { assert!(r.is_err(), "expected the input budget to stop rg"); // ~25 B per file: the 1 MiB budget covers ~40k files of the tree. assert!((reads as usize) < fs.files() / 2, "read {reads} files"); - // rg keeps every file it read until the budget trips, so the bound - // scales with reads: ~290 B per read locally, ~360 B under tarpaulin's - // instrumented build. Before the walk streamed, the whole-tree candidate - // list pushed this past 1.5 KB per read (~70 MB at 200k files). - let per_read = peak.saturating_sub(BOUNDED_PEAK) / (reads as usize).max(1); - assert!( - peak < BOUNDED_PEAK + 512 * reads as usize, - "peak {peak} B for {reads} reads ({per_read} B/read over the fixed bound)" - ); + // Each file is searched and dropped as it is read, so nothing scales + // with reads: ~5 MiB here. Holding the read text took ~13.7 MB (17 MB + // under tarpaulin); the old whole-tree candidate list ~70 MB. + assert!(peak < 2 * BOUNDED_PEAK, "peak {peak} B for {reads} reads"); } -/// rg within budget over the whole tree: memory scales with the text it -/// searches (rg holds every searched file until output is built), at -/// ~180 B per file here. TODO(TM-DOS-140): search each file as it is read -/// so non-matching files are dropped; until then the aggregate-input budget -/// is the bound. +/// rg within budget over the whole tree: each file is searched as it is +/// read and dropped, so memory stays bounded however many files it searches +/// (it held ~160 B per file, ~300 MB at 2M files, before searching moved +/// into the walk). Several roots stream one after another the same way. #[tokio::test(flavor = "current_thread")] -async fn rg_within_budget_holds_only_file_text() { +async fn rg_within_budget_holds_bounded_memory() { let _serial = SERIAL.lock().await; let (fs, mut bash) = setup().await; + for cmd in [ + "rg -l nomatch /big", + "rg -c nomatch /big/d1 /big/d0", + "rg nomatch /big", + ] { + let r = measure(&fs, &mut bash, cmd).await; + assert_eq!(r.exit_code, 1, "{cmd}"); + assert!(r.peak < BOUNDED_PEAK, "{cmd}: peak {} B", r.peak); + } let r = measure(&fs, &mut bash, "rg -l nomatch /big").await; - assert_eq!(r.exit_code, 1); // Every file, plus any ignore file the listing shows. assert!(r.read_file as usize >= fs.files()); - // Per searched file: its ~25 B text plus its display path and bookkeeping. - let per_file = r.peak / fs.files(); - eprintln!("rg: {per_file} B per searched file"); - assert!(per_file < 250, "rg holds {per_file} B per file"); } diff --git a/knowledge/foundations/vfs.md b/knowledge/foundations/vfs.md index 77caf0b49..55fa7c007 100644 --- a/knowledge/foundations/vfs.md +++ b/knowledge/foundations/vfs.md @@ -460,15 +460,15 @@ and measured by `benches/remote_fs.rs` over the bashkit checkout: listing shows, and tracks "inside a git repo" down the walk instead of a `stat` per ancestor. `--max-depth` is applied to index matches. `-L`, `--type`, `--max-filesize`, `--sort` other than path still walk. -- `rg` keeps every searched file's text until output is built; it charges - each file to the aggregate-input budget as it reads (default 100 MB) and - stops at the first refusal, so a huge tree fails at the budget instead of - after loading every file (TM-DOS-140). With one root in path order, the - walk visits entries in sorted order and reads each file as it finds it, - so no candidate list is held and the walk stops at the budget. Several - roots, a non-path `--sort` and `--files` still collect every candidate - (paths + metadata) before reading. Follow-ups: stream each root in turn, - and search each file as it is read (dropping non-matching text). +- `rg` searches each file as it reads it and drops the text (`RgSearch`), so + memory holds the output, not the searched text. It still charges each + file to the aggregate-input budget (default 100 MB) and stops at the first + refusal (TM-DOS-140). In path order the walk visits entries sorted and + reads each file as it finds it, so no candidate list is held; several + roots stream one after another (sorted), which equals the global path + sort unless one root lies inside another, which keeps the collected list. + `-q` stops the walk at its answer. A non-path `--sort` and `--files` still + collect every candidate (paths + metadata) before reading. - `ls` (with `-R` or on one wide directory) stops appending lines once its output passes `max_stdout_bytes` (the rest would be cut), so its memory is bounded by the stdout limit. diff --git a/knowledge/log.md b/knowledge/log.md index 8c68c4284..e03c0795e 100644 --- a/knowledge/log.md +++ b/knowledge/log.md @@ -3,6 +3,7 @@ ## 2026-11-06 * **Monty fuzz target**: `python_fuzz` fuzzes the forked Monty `python3` with the metered allocator installed (file, stdin, `-c`, CLI args; 32 MiB / 500 ms limits, per-exec wall-clock assertion, leak checks). Nightly in `fuzz.yml`, build-checked in `fuzz-check`. First local run: 282k execs in 8 min, 0 crashes. See [Python Builtin](runtimes/python-builtin.md), TM-PY-032. +* **rg searches as it reads**: `rg` searched every file only after reading all of them, holding ~160 B of text per file (~300 MB at 2M files) within the input budget. Searching moved into the walk (`RgSearch`): each file is searched and dropped as it is read, several roots stream one after another in path order, and `-q` stops the walk at its answer. Peak over 200k files: 34 MB to 1.3 MiB. See [Virtual Filesystem](foundations/vfs.md#remote-backends-round-trips), TM-DOS-140. * **Dependabot jobs green again**: the weekly cargo "/" job failed since 2026-10-19 because `turso_core = "0.8.0-pre.1"` (lock at 0.8.3) made Dependabot try 0.9.0-pre.2 as an in-range lockfile update, which cargo rejects; the requirement is now the stable `0.8.3`. The example/fixture job failed since 2026-10-13 because Dependabot follows the `crates/bashkit` path dep into the root workspace and tries to bump bashkit's own (root-owned, partly optional) deps; that entry now `allow`s only each manifest's own deps and uses `versioning-strategy: increase` for the lockfile-less fixtures. Crates only the Monty forks declare are ignored in the "/" entry so they move with upstream (#2848 had bumped them and broke the build). All three are pinned by `scripts/tests/test_dependabot_coverage.py`. See [Dependencies](operations/dependencies.md). ## 2026-11-05 diff --git a/knowledge/operations/testing.md b/knowledge/operations/testing.md index 657eb5166..6c960e1bd 100644 --- a/knowledge/operations/testing.md +++ b/knowledge/operations/testing.md @@ -107,8 +107,9 @@ and contents computed from the path, so the tree costs no memory) with ~200k files plus a hidden `.git`, and asserts that `find`, `du`, `tree`, `grep -r` stay under an 8 MiB heap peak and list each directory once, that `ls -R` adds only its output, and that `rg` stops at the aggregate-input budget -(~14 MB peak at a 1 MiB budget; it held a ~70 MB candidate list before) and -holds under 250 B per searched file within budget. Scale it with +(~5 MiB peak at a 1 MiB budget; ~70 MB candidate list, then ~14 MB of held +text before) and stays under 8 MiB within budget, also over several roots +(it held ~160 B per searched file before searching moved into the walk). Scale it with `BASHKIT_STRESS_FILES=2000000 cargo test --release -p bashkit --test large_tree_stress_tests -- --nocapture` (or `just stress`). diff --git a/knowledge/security/threat-model.md b/knowledge/security/threat-model.md index 6504a7582..15eee34e5 100644 --- a/knowledge/security/threat-model.md +++ b/knowledge/security/threat-model.md @@ -313,7 +313,7 @@ on default 2 MiB test threads (TM-DOS-044). | TM-DOS-107 | Static-analysis command validation amplification | A large comment before thousands of commands makes a whole-script ordered-subsequence scan per command | Build one source-character position index, then validate each analyzed command-name character with a logarithmic position lookup instead of rescanning source | **MITIGATED** | | TM-DOS-138 | Join matching-row output growth | Equal-key row groups multiply generated output and synchronous work before dispatcher capture | Parsed rows, fields, keys, decoded input and generated output own shared-budget capacity before growth. VFS reads charge aggregate input and admit metadata size; output fields append directly without temporary row storage, and the byte-stream copy is admitted. Parsing, grouping (including suppressed matches), comparisons and emissions charge work and poll cancellation/deadlines. Errors abort the request. Ordinary two-row fixtures cover memory/work rejection, cancellation/deadlines, session recovery, and complete pipeline/redirect output | **MITIGATED** | | TM-DOS-139 | Embedded CLI limit escalation | `markkit extract x --max-input-size 99999999999 --timeout 1e9` buys a larger CPU/memory budget in a shared process | Host clamps every markkit limit to its default after flags (`CliHost::limits`); fetchkit bodies capped by `HttpLimits`; OCR (host binaries) refused | **MITIGATED** | -| TM-DOS-140 | Tree-walk memory on huge trees | A tenant mounts or creates a tree with millions of files and runs `find`, `du` or `rg` over it; a bulk prefetch of every listing, or rg collecting every file's text before charging the input budget, holds the whole tree in memory | `FileSystem::walk` answers are bounded batches (`WalkOptions::max_entries`, default 10k entries; a listing is never split); `find`/`du` refill through `builtins/walk_cache.rs` one batch at a time, consume listings as they descend, and fall back to `read_dir` if an answer does not hold the requested directory; rg charges each file's text to the aggregate-input budget as it is read and stops at the first refusal, and with one root its walk reads files as it finds them (no candidate list); `ls` (recursive or one wide directory) stops appending lines at `max_stdout_bytes`. Heap peaks over a 200k/2M-file procedural tree are pinned by `large_tree_stress_tests` (walkers under 8 MiB). Residuals: within budget rg holds every searched file's text (~160 B per file) until output is built; several roots, a non-path `--sort` or `--files` still build the full candidate list (paths + metadata per file, no budget charge) before reading; one wide directory is held whole by `read_dir`. Regressions: `walk_cache::tests::batches_stay_bounded_and_cover_every_directory`, `remote_fs_round_trip_tests::walk_batches_are_bounded_*`, `rg_stops_reading_at_input_budget` | **MITIGATED** | +| TM-DOS-140 | Tree-walk memory on huge trees | A tenant mounts or creates a tree with millions of files and runs `find`, `du` or `rg` over it; a bulk prefetch of every listing, or rg collecting every file's text before charging the input budget, holds the whole tree in memory | `FileSystem::walk` answers are bounded batches (`WalkOptions::max_entries`, default 10k entries; a listing is never split); `find`/`du` refill through `builtins/walk_cache.rs` one batch at a time, consume listings as they descend, and fall back to `read_dir` if an answer does not hold the requested directory; rg searches each file as it is read and drops its text, charges it to the aggregate-input budget and stops at the first refusal, and in path order its walk reads files as it finds them, one root after another (no candidate list); `ls` (recursive or one wide directory) stops appending lines at `max_stdout_bytes`. Heap peaks over a 200k/2M-file procedural tree are pinned by `large_tree_stress_tests` (walkers under 8 MiB). Residuals: a non-path `--sort`, `--files`, or nested roots still build the full candidate list (paths + metadata per file, no budget charge) before reading; one wide directory is held whole by `read_dir`. Regressions: `walk_cache::tests::batches_stay_bounded_and_cover_every_directory`, `remote_fs_round_trip_tests::walk_batches_are_bounded_*`, `rg_stops_reading_at_input_budget` | **MITIGATED** | **TM-DOS-051** is historical. The custom parser was deleted with the `yaml` helper; the replacement `yq` parser/evaluator boundary is tracked by TM-DOS-101.