From 3505d9dd722e09980f683b717fdfd871c0f5ce36 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:08:30 +0000 Subject: [PATCH 1/9] perf(check): cut repeated per-probe work on big Python, TypeScript and Rust diffs Python source facts looked up each fact's line by scanning the file from the start, so extraction was quadratic in file size. An IndexedSource keeps the newline offsets and answers by binary search. TypeScript related-test selection walked the filesystem for package.json twice per (owner, test) pair. OwnerPackageScope resolves the owner's package once and each test directory once per owner. Rust classification reparsed the whole owner file per probe for the derived tuple admission even when the file cannot contain the canonical parameters; the names are now checked first. Per-(test, owner) value facts are memoized on the run-scoped candidate index, and test-name token matching no longer allocates two strings per (test, token). Output is unchanged: check JSON is byte-identical on 12 real commits of tokio, vite, django and ripr-swarm. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- crates/ripr/src/analysis/classifier.rs | 3 +- .../ripr/src/analysis/classifier/evidence.rs | 9 +- .../evidence/tuple_match/derived_admission.rs | 19 +- .../ripr/src/analysis/classify/activation.rs | 196 +++++++++++++++++- crates/ripr/src/analysis/classify/context.rs | 14 ++ crates/ripr/src/analysis/classify/mod.rs | 3 +- .../src/analysis/classify/related_tests.rs | 82 +++++++- .../analysis/language/python/owners_tests.rs | 28 ++- .../analysis/language/python/python_tests.rs | 19 ++ .../analysis/language/python/source_facts.rs | 47 +++-- .../analysis/language/python/source_utils.rs | 53 ++++- .../language/typescript/related_tests.rs | 74 ++++++- .../language/typescript/static_limit.rs | 3 +- .../src/analysis/language/typescript/tests.rs | 62 ++++++ 14 files changed, 541 insertions(+), 71 deletions(-) diff --git a/crates/ripr/src/analysis/classifier.rs b/crates/ripr/src/analysis/classifier.rs index 5be9795999e..2fb601e8527 100644 --- a/crates/ripr/src/analysis/classifier.rs +++ b/crates/ripr/src/analysis/classifier.rs @@ -67,7 +67,8 @@ pub(in crate::analysis) fn classify_probe_with_candidate_index( workspace_complete, ) .with_helper_chain(helper_chain) - .with_file_use_statements(candidate_index.file_use_statements()); + .with_file_use_statements(candidate_index.file_use_statements()) + .with_test_value_facts(candidate_index.test_value_facts()); let reveal_expression = parser_expression_for_probe( index, &probe.location.file, diff --git a/crates/ripr/src/analysis/classifier/evidence.rs b/crates/ripr/src/analysis/classifier/evidence.rs index 9388176c738..ba2b23f6b4a 100644 --- a/crates/ripr/src/analysis/classifier/evidence.rs +++ b/crates/ripr/src/analysis/classifier/evidence.rs @@ -1,7 +1,7 @@ use crate::analysis::classify::{ - ProbeContext, PropagationWitnessV1, activation_evidence, classify, confidence_score, - current_path_witness, infection_evidence, local_flow_sinks, owner_may_be_reached_unseen, - package_prefix, propagation_evidence_with_witness, reach_evidence, + ProbeContext, PropagationWitnessV1, activation_evidence_with_value_facts, classify, + confidence_score, current_path_witness, infection_evidence, local_flow_sinks, + owner_may_be_reached_unseen, package_prefix, propagation_evidence_with_witness, reach_evidence, reveal_evidence_with_expression, }; use crate::domain::*; @@ -43,7 +43,7 @@ impl ClassifiedProbeEvidence { let flow_sinks = local_flow_sinks(context.probe, context.owner_fn); let propagation_witness = current_path_witness(context.probe, &flow_sinks) .map(PropagationWitnessDiagnostic::from_witness); - let activation = activation_evidence( + let activation = activation_evidence_with_value_facts( context.probe, context.owner_fn, &test_summaries, @@ -51,6 +51,7 @@ impl ClassifiedProbeEvidence { context.helper_chain.as_ref(), context.index, context.workspace_complete, + context.test_value_facts, ); let infect = infection_evidence(context.probe, &test_summaries, &activation); let valid_witness = propagation_witness diff --git a/crates/ripr/src/analysis/classifier/evidence/tuple_match/derived_admission.rs b/crates/ripr/src/analysis/classifier/evidence/tuple_match/derived_admission.rs index ca5bb1255d9..01b4e20c1e9 100644 --- a/crates/ripr/src/analysis/classifier/evidence/tuple_match/derived_admission.rs +++ b/crates/ripr/src/analysis/classifier/evidence/tuple_match/derived_admission.rs @@ -20,6 +20,16 @@ pub(super) fn admits(context: &ProbeContext<'_>) -> bool { fn admits_inner(context: &ProbeContext<'_>) -> Option { let owner = context.owner_fn?; let facts = find_file_facts(context.index, &owner.file)?; + // `canonical_owner_roles` requires these exact parameter names, so a + // file that never spells one cannot admit. Checking before the parse + // skips a whole-file reparse per probe (profiled: ~16% of a `ripr + // check` on this repository) without changing any verdict. + if !CANONICAL_PARAMETER_NAMES + .iter() + .all(|name| facts.source.contains(name)) + { + return Some(false); + } let root = parsed(&facts.source)?; let function = named_function(&root, &owner.name)?; if !canonical_owner_roles(&function)? { @@ -41,17 +51,20 @@ fn admits_inner(context: &ProbeContext<'_>) -> Option { top_level_projection_observes(&test_function, &owner.name, &result) } +/// The parameter names `canonical_owner_roles` pins with `has_exact_parameter`. +const CANONICAL_PARAMETER_NAMES: [&str; 3] = ["receipt_request_ids", "request_set", "task_id"]; + /// First-slice authority is the canonical helper boundary only. Merely finding /// any owner parameter or any `.contains` call cannot assign semantic roles. fn canonical_owner_roles(function: &ast::Fn) -> Option { if !canonical_receipt_iteration(function)? || !has_exact_parameter( function, - "receipt_request_ids", + CANONICAL_PARAMETER_NAMES[0], "&BTreeMap>", )? - || !has_exact_parameter(function, "request_set", "&BTreeSet")? - || !has_exact_parameter(function, "task_id", "&str")? + || !has_exact_parameter(function, CANONICAL_PARAMETER_NAMES[1], "&BTreeSet")? + || !has_exact_parameter(function, CANONICAL_PARAMETER_NAMES[2], "&str")? { return Some(false); } diff --git a/crates/ripr/src/analysis/classify/activation.rs b/crates/ripr/src/analysis/classify/activation.rs index 397c2553da5..7560976ad7d 100644 --- a/crates/ripr/src/analysis/classify/activation.rs +++ b/crates/ripr/src/analysis/classify/activation.rs @@ -2,6 +2,7 @@ use super::super::rust_index::{FunctionSummary, TestSummary}; use super::text::{delimited_contents_at, enum_variant_values, exact_error_variant}; use crate::domain::*; +#[cfg(test)] pub(in crate::analysis) fn activation_evidence( probe: &Probe, owner_fn: Option<&FunctionSummary>, @@ -10,10 +11,42 @@ pub(in crate::analysis) fn activation_evidence( helper_chain: Option<&super::helper_transfer::HelperChain>, index: &crate::analysis::rust_index::RustIndex, workspace_complete: bool, +) -> ActivationEvidence { + activation_evidence_with_value_facts( + probe, + owner_fn, + related_tests, + flow_sinks, + helper_chain, + index, + workspace_complete, + None, + ) +} + +/// `activation_evidence`, reading each related test's owner-independent +/// value facts through `value_facts` when the classifier supplies its +/// run-scoped memo. +#[allow( + clippy::too_many_arguments, + reason = "activation_evidence's inputs plus the optional run-scoped memo" +)] +pub(in crate::analysis) fn activation_evidence_with_value_facts( + probe: &Probe, + owner_fn: Option<&FunctionSummary>, + related_tests: &[&TestSummary], + flow_sinks: &[FlowSinkFact], + helper_chain: Option<&super::helper_transfer::HelperChain>, + index: &crate::analysis::rust_index::RustIndex, + workspace_complete: bool, + value_facts: Option<&TestValueFacts>, ) -> ActivationEvidence { let mut observed_values = related_tests .iter() - .flat_map(|test| value_facts_for_test(test, owner_fn)) + .flat_map(|test| match value_facts { + Some(memo) => memo.facts_for(index, test, owner_fn), + None => value_facts_for_test(test, owner_fn), + }) .collect::>(); observed_values.extend(observed_discriminator_values( probe, @@ -63,6 +96,84 @@ struct ParameterValue { text: String, } +/// `value_facts_for_test` per (related test, owner), computed at most once +/// for as long as the memo lives. +/// +/// The facts depend only on the test and the owner, never on the probe, and +/// every probe in an owner relates to largely the same tests, so a +/// classification run shares one memo across its probes (it rides the +/// run-scoped `RelatedTestCandidateIndex`). Entries are keyed by the test's +/// and owner's slots in the index the memo was first queried with; a test +/// or owner that is not an element of that index, or a query against +/// another index, is computed fresh and never cached, so a key can only +/// ever name the same fact values. +#[derive(Clone, Debug, Default)] +pub(in crate::analysis) struct TestValueFacts { + index_identity: std::cell::Cell>, + by_slot: std::cell::RefCell), Vec>>, +} + +impl TestValueFacts { + /// `value_facts_for_test(test, owner_fn)`. + pub(in crate::analysis) fn facts_for( + &self, + index: &crate::analysis::rust_index::RustIndex, + test: &TestSummary, + owner_fn: Option<&FunctionSummary>, + ) -> Vec { + let Some(key) = self.slot_key(index, test, owner_fn) else { + return value_facts_for_test(test, owner_fn); + }; + if let Some(facts) = self.by_slot.borrow().get(&key) { + return facts.clone(); + } + let facts = value_facts_for_test(test, owner_fn); + self.by_slot.borrow_mut().insert(key, facts.clone()); + facts + } + + fn slot_key( + &self, + index: &crate::analysis::rust_index::RustIndex, + test: &TestSummary, + owner_fn: Option<&FunctionSummary>, + ) -> Option<(usize, Option)> { + let identity = ( + index.tests.as_ptr() as usize, + index.functions.as_ptr() as usize, + ); + match self.index_identity.get() { + None => self.index_identity.set(Some(identity)), + Some(bound) if bound != identity => return None, + Some(_) => {} + } + let test_slot = slot_in(&index.tests, test)?; + let owner_slot = match owner_fn { + Some(owner) => Some(slot_in(&index.functions, owner)?), + None => None, + }; + Some((test_slot, owner_slot)) + } +} + +/// The position of `item` in `items` when `item` is one of its elements +/// (by address, not by value). +fn slot_in(items: &[T], item: &T) -> Option { + let size = std::mem::size_of::(); + if size == 0 { + return None; + } + let offset = (item as *const T as usize).checked_sub(items.as_ptr() as usize)?; + if offset % size != 0 { + return None; + } + let slot = offset / size; + items + .get(slot) + .is_some_and(|candidate| std::ptr::eq(candidate, item)) + .then_some(slot) +} + fn value_facts_for_test(test: &TestSummary, owner_fn: Option<&FunctionSummary>) -> Vec { let owner_name = owner_fn.map(|owner| owner.name.as_str()).unwrap_or(""); let parameters = owner_fn.map(function_parameters).unwrap_or_default(); @@ -2707,6 +2818,89 @@ assert_eq!(input.amount, 100);"# assert!(!facts.iter().any(|fact| fact.value == "AuthError::Ignored")); } + /// The run-scoped memo answers every (test, owner) query exactly as a + /// fresh `value_facts_for_test` does, on the first (computing) query and + /// every later (cached) one; owners that differ only in their parameter + /// names get different facts, and a test or index the memo is not bound + /// to is computed fresh without being cached. + #[test] + fn test_value_facts_memo_matches_fresh_facts_for_every_test_and_owner() { + let call = |line: usize, text: &str| CallFact { + line, + name: "score".to_string(), + text: text.to_string(), + }; + let test = |name: &str, body: &str, calls: Vec| TestSummary { + name: name.to_string(), + file: PathBuf::from("tests/value.rs"), + start_line: 10, + end_line: 14, + body: body.to_string(), + calls, + assertions: vec![oracle_fact( + "assert_eq!(total, 100);", + OracleKind::ExactValue, + )], + literals: Vec::new(), + attrs: Vec::new(), + nested_fn_names: Vec::new(), + let_bindings: Vec::new(), + }; + let index = crate::analysis::rust_index::RustIndex { + tests: vec![ + test( + "enum_call", + "score(AuthError::RevokedToken);", + vec![call(11, "score(AuthError::RevokedToken);")], + ), + test( + "literal_call", + "let rows = [(99, 100)];\nscore(7);", + vec![call(12, "score(7);")], + ), + ], + functions: vec![ + function("pub fn score(error: AuthError) -> u32 {\n 0\n}"), + function("pub fn score(code: AuthError) -> u32 {\n 0\n}"), + ], + ..crate::analysis::rust_index::RustIndex::default() + }; + let memo = TestValueFacts::default(); + let owners = [None, Some(&index.functions[0]), Some(&index.functions[1])]; + for round in 0..2 { + for test in &index.tests { + for owner in owners { + assert_eq!( + memo.facts_for(&index, test, owner), + value_facts_for_test(test, owner), + "round {round}: {} / {:?}", + test.name, + owner.map(|owner| owner.body.as_str()) + ); + } + } + } + assert_ne!( + memo.facts_for(&index, &index.tests[1], owners[1]), + memo.facts_for(&index, &index.tests[1], owners[2]), + "the owner's parameter names are part of the facts" + ); + let cached = memo.by_slot.borrow().len(); + assert_eq!(cached, index.tests.len() * owners.len()); + + let detached = index.tests[0].clone(); + assert_eq!( + memo.facts_for(&index, &detached, owners[1]), + value_facts_for_test(&detached, owners[1]) + ); + let other_index = index.clone(); + assert_eq!( + memo.facts_for(&other_index, &other_index.tests[0], None), + value_facts_for_test(&other_index.tests[0], None) + ); + assert_eq!(memo.by_slot.borrow().len(), cached); + } + // #4228: a reversed literal (`100 < amount`) and a local boundary // (`let limit = 100;`) close at the boundary input and stay open one // step off it; a local no row can evaluate names no repair at all. diff --git a/crates/ripr/src/analysis/classify/context.rs b/crates/ripr/src/analysis/classify/context.rs index 02fba6b1883..7d7213eb435 100644 --- a/crates/ripr/src/analysis/classify/context.rs +++ b/crates/ripr/src/analysis/classify/context.rs @@ -1,4 +1,5 @@ use super::super::rust_index::{FunctionSummary, RustIndex, TestSummary}; +use super::activation::TestValueFacts; use super::helper_transfer::HelperChain; use super::reveal::FileUseStatements; use crate::domain::{Probe, RelationReason}; @@ -27,6 +28,9 @@ pub(in crate::analysis) struct ProbeContext<'a> { /// Run-scoped per-file `use` scan, attached by the classifier; `None` /// (unit-test contexts) scans on every query. pub file_use_statements: Option<&'a FileUseStatements>, + /// Run-scoped per-(test, owner) value facts, attached by the + /// classifier; `None` (unit-test contexts) computes them per probe. + pub test_value_facts: Option<&'a TestValueFacts>, } impl<'a> ProbeContext<'a> { @@ -47,6 +51,7 @@ impl<'a> ProbeContext<'a> { index, workspace_complete, file_use_statements: None, + test_value_facts: None, } } @@ -59,6 +64,15 @@ impl<'a> ProbeContext<'a> { self } + /// Share one classification run's per-test value facts across probes. + pub(in crate::analysis) fn with_test_value_facts( + mut self, + test_value_facts: &'a TestValueFacts, + ) -> Self { + self.test_value_facts = Some(test_value_facts); + self + } + /// Attach the #3296 helper-transfer chain (computed once by the /// classifier, where the index is available). pub(in crate::analysis) fn with_helper_chain( diff --git a/crates/ripr/src/analysis/classify/mod.rs b/crates/ripr/src/analysis/classify/mod.rs index 724ed8b3a54..9642b616b71 100644 --- a/crates/ripr/src/analysis/classify/mod.rs +++ b/crates/ripr/src/analysis/classify/mod.rs @@ -16,7 +16,8 @@ mod transitive_reach; mod value_transfer; pub(in crate::analysis) use activation::{ - LocalBoundary, activation_evidence, literal_operand_value, local_boundary, + LocalBoundary, TestValueFacts, activation_evidence_with_value_facts, literal_operand_value, + local_boundary, }; pub(in crate::analysis) use context::ProbeContext; pub(in crate::analysis) use decision::{ diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 5fa7c375c1e..2517d1e3f53 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -57,6 +57,8 @@ pub(in crate::analysis) struct RelatedTestCandidateIndex { /// Run-scoped reveal memo filled lazily from the same index; valid for /// exactly as long as the candidate lists above are. file_use_statements: super::FileUseStatements, + /// Run-scoped activation memo, keyed by slots of the same index. + test_value_facts: super::TestValueFacts, } impl RelatedTestCandidateIndex { @@ -123,6 +125,12 @@ impl RelatedTestCandidateIndex { &self.file_use_statements } + /// The run-scoped per-(test, owner) value facts shared by every probe + /// classified against this index. + pub(in crate::analysis) fn test_value_facts(&self) -> &super::TestValueFacts { + &self.test_value_facts + } + fn candidate_indices( &self, probe: &Probe, @@ -660,6 +668,11 @@ fn find_related_tests_with_candidates<'a>( // `no_static_path`, while these proximity-only tests keep reach `Weak` // for an owner that may be reached unseen (trait method, named caller). let mut substring_only_fallback = Vec::new(); + let owner_name_lc = owner_name.to_ascii_lowercase(); + let test_name_words: Vec = probe_tokens + .iter() + .filter_map(|token| test_name_word_token(token, common_words)) + .collect(); for test_index in candidate_indices { let test = &index.tests[test_index]; // Compute calls_owner BEFORE the package-prefix guard so a cross-crate @@ -819,7 +832,6 @@ fn find_related_tests_with_candidates<'a>( }); let test_name = test.name.to_ascii_lowercase(); - let owner_name_lc = owner_name.to_ascii_lowercase(); let same_test_file = same_test_file(&probe.location.file, &test.file); // Keep the broad path-token association available to callers, but do // not publish it as file identity. A short source stem such as @@ -827,9 +839,9 @@ fn find_related_tests_with_candidates<'a>( // `reconfigure.rs`). let file_path_token_matches = test_path_names_probe_stem(&test.file, &file_name); let owner_name_in_test = !owner_name_lc.is_empty() && test_name.contains(&owner_name_lc); - let token_in_test_name = probe_tokens + let token_in_test_name = test_name_words .iter() - .any(|token| test_name_names_probe_token(&test_name, token, common_words)); + .any(|word| test_name_has_word(&test_name, word)); let same_file_or_named = same_test_file || file_path_token_matches || owner_name_in_test || token_in_test_name; @@ -1411,19 +1423,42 @@ fn normalize_path(path: &Path) -> String { /// changed code, and its strong assertion then read as the discriminator /// once another test supplied reach, so a mutation no test catches read /// `exposed`. +#[cfg(test)] fn test_name_names_probe_token( test_name: &str, token: &str, common_words: &BTreeSet, ) -> bool { + test_name_word_token(token, common_words) + .is_some_and(|word| test_name_has_word(test_name, &word)) +} + +/// The lowercased form of `token` that `test_name_names_probe_token` looks +/// for, or `None` when the token is too short, generic, or common. It +/// depends only on the probe, so the test loop computes it once per probe. +fn test_name_word_token(token: &str, common_words: &BTreeSet) -> Option { if token.len() < 3 || GENERIC_PROBE_TOKENS.contains(&token) { - return false; + return None; } let lowered = token.to_ascii_lowercase(); - if common_words.contains(&lowered) { - return false; + (!common_words.contains(&lowered)).then_some(lowered) +} + +/// `format!("_{test_name}_").contains(&format!("_{word}_"))` without the two +/// allocations per (test, token) pair: some occurrence of `word`, overlapping +/// ones included, is bounded by `_` or the name's ends on both sides. +fn test_name_has_word(test_name: &str, word: &str) -> bool { + let bytes = test_name.as_bytes(); + let mut from = 0; + while let Some(found) = test_name.get(from..).and_then(|rest| rest.find(word)) { + let start = from + found; + let end = start + word.len(); + if (start == 0 || bytes[start - 1] == b'_') && (end == bytes.len() || bytes[end] == b'_') { + return true; + } + from = start + test_name[start..].chars().next().map_or(1, char::len_utf8); } - format!("_{test_name}_").contains(&format!("_{lowered}_")) + false } /// Tokens so widespread across a package's tests that sharing one ties no @@ -3444,6 +3479,39 @@ fn crate_c_score_test() { )); } + /// The allocation-free word search agrees with the padded-substring + /// rule it replaces on every short name over `_`, ASCII, and multi-byte + /// characters, overlapping and repeated occurrences included. + #[test] + fn test_name_has_word_matches_the_padded_substring_rule() { + let alphabet = ["a", "b", "_", "é"]; + let mut strings = vec![String::new()]; + let mut level = vec![String::new()]; + for _ in 0..5 { + level = level + .iter() + .flat_map(|text| alphabet.iter().map(move |letter| format!("{text}{letter}"))) + .collect(); + strings.extend(level.iter().cloned()); + } + let words: Vec<&String> = strings + .iter() + .filter(|word| (1..=3).contains(&word.chars().count())) + .collect(); + let mut checked = 0usize; + for name in &strings { + for word in &words { + assert_eq!( + super::test_name_has_word(name, word), + format!("_{name}_").contains(&format!("_{word}_")), + "{name:?} / {word:?}" + ); + checked += 1; + } + } + assert!(checked > 100_000, "only {checked} pairs checked"); + } + #[test] fn test_name_token_match_needs_whole_words_and_a_specific_token() { let none = BTreeSet::new(); diff --git a/crates/ripr/src/analysis/language/python/owners_tests.rs b/crates/ripr/src/analysis/language/python/owners_tests.rs index 1818c014f75..78506ee012f 100644 --- a/crates/ripr/src/analysis/language/python/owners_tests.rs +++ b/crates/ripr/src/analysis/language/python/owners_tests.rs @@ -3,9 +3,7 @@ use super::module_constants::{ }; #[cfg(test)] use super::source_facts::extract_source_facts; -use super::source_utils::{ - line_for_range_end, line_for_range_start, normalized_path, text_for_range, -}; +use super::source_utils::{IndexedSource, normalized_path, text_for_range}; use super::static_limits::{collect_static_cli_receiver_names, is_static_route_decorator}; use super::{ PythonImport, PythonOwner, PythonParameter, PythonTest, collect_assertions_from_statements, @@ -25,7 +23,7 @@ pub(super) fn extract_owners(file: &Path, source: &str) -> Vec { pub(super) fn collect_owners_from_statements( file: &Path, - source: &str, + source: &IndexedSource<'_>, statements: &[Stmt], class_context: Option<&str>, imports: &[PythonImport], @@ -99,7 +97,7 @@ pub(super) fn collect_owners_from_statements( #[derive(Clone, Copy)] struct PythonOwnerContext<'a> { file: &'a Path, - source: &'a str, + source: &'a IndexedSource<'a>, class_context: Option<&'a str>, imports: &'a [PythonImport], module_constants: &'a [PythonModuleConstant], @@ -139,8 +137,8 @@ fn owner_from_function( name: name.to_string(), qualified_name, file: context.file.to_path_buf(), - start_line: line_for_range_start(context.source, range), - end_line: line_for_range_end(context.source, range), + start_line: context.source.line_for_range_start(range), + end_line: context.source.line_for_range_end(range), owner_kind: Some(owner_kind), decorators, imports: context.imports.to_vec(), @@ -191,8 +189,8 @@ fn owner_from_class( name: name.to_string(), qualified_name, file: context.file.to_path_buf(), - start_line: line_for_range_start(context.source, range), - end_line: line_for_range_end(context.source, range), + start_line: context.source.line_for_range_start(range), + end_line: context.source.line_for_range_end(range), owner_kind: None, decorators: decorator_names(decorators), imports: context.imports.to_vec(), @@ -207,7 +205,7 @@ fn owner_from_class( pub(super) fn module_owner( file: &Path, - source: &str, + source: &IndexedSource<'_>, range: TextRange, imports: &[PythonImport], ) -> PythonOwner { @@ -215,8 +213,8 @@ pub(super) fn module_owner( name: "".to_string(), qualified_name: "".to_string(), file: file.to_path_buf(), - start_line: line_for_range_start(source, range), - end_line: line_for_range_end(source, range), + start_line: source.line_for_range_start(range), + end_line: source.line_for_range_end(range), owner_kind: Some(OwnerKind::ModuleFunction), decorators: Vec::new(), imports: imports.to_vec(), @@ -239,7 +237,7 @@ pub(super) fn extract_tests(file: &Path, source: &str) -> Vec { /// Custom collection prefixes and hooks are not resolved here. pub(super) fn collect_tests_from_statements( file: &Path, - source: &str, + source: &IndexedSource<'_>, statements: &[Stmt], class_context: Option<&str>, in_unittest_class: bool, @@ -259,7 +257,7 @@ pub(super) fn collect_tests_from_statements( qualified_name: qualified_test_name(class_context, &name), name, file: file.to_path_buf(), - line: line_for_range_start(source, function.range), + line: source.line_for_range_start(function.range), body_text: text_for_range(source, function.range), imports: imports.to_vec(), decorators: decorator_names(&function.decorator_list), @@ -285,7 +283,7 @@ pub(super) fn collect_tests_from_statements( qualified_name: qualified_test_name(class_context, &name), name, file: file.to_path_buf(), - line: line_for_range_start(source, function.range), + line: source.line_for_range_start(function.range), body_text: text_for_range(source, function.range), imports: imports.to_vec(), decorators: decorator_names(&function.decorator_list), diff --git a/crates/ripr/src/analysis/language/python/python_tests.rs b/crates/ripr/src/analysis/language/python/python_tests.rs index 60d000f780a..27d452ce55b 100644 --- a/crates/ripr/src/analysis/language/python/python_tests.rs +++ b/crates/ripr/src/analysis/language/python/python_tests.rs @@ -1262,6 +1262,25 @@ fn line_for_offset_counts_newlines() { assert_eq!(line_for_offset(source, 999), 3); } +/// The newline index answers every offset, including offsets inside a +/// multi-byte character, on a `\r\n` line, and past the end, exactly as +/// the scanning `line_for_offset` does. +#[test] +fn indexed_source_lines_match_line_for_offset_at_every_offset() { + let source = "def f():\r\n return \"é→\"\n\n\nx = 1 # ü\n"; + let indexed = super::source_utils::IndexedSource::new(source); + for offset in 0..=source.len() + 2 { + assert_eq!( + indexed.line_for_offset(offset), + line_for_offset(source, offset), + "offset {offset}" + ); + } + assert_eq!(&*indexed, source); + let empty = super::source_utils::IndexedSource::new(""); + assert_eq!(empty.line_for_offset(0), line_for_offset("", 0)); +} + #[test] fn looks_like_call_expression_handles_trailing_semicolons_and_whitespace() { assert!(looks_like_call_expression("notify(event);")); diff --git a/crates/ripr/src/analysis/language/python/source_facts.rs b/crates/ripr/src/analysis/language/python/source_facts.rs index 9a1ec942996..36250466faf 100644 --- a/crates/ripr/src/analysis/language/python/source_facts.rs +++ b/crates/ripr/src/analysis/language/python/source_facts.rs @@ -3,7 +3,7 @@ use super::owners_tests::{ collect_imports_from_statements, collect_owners_from_statements, collect_tests_from_statements, module_owner, }; -use super::source_utils::{line_for_range_end, line_for_range_start, text_for_range}; +use super::source_utils::{IndexedSource, text_for_range}; use super::{PythonOwner, PythonTest, expr_full_name}; use crate::domain::{LanguageId as DomainLanguageId, StaticLimitKind}; use rustpython_parser::{ @@ -246,10 +246,11 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac TextSize::from(0), TextSize::from(u32::try_from(source.len()).unwrap_or(u32::MAX)), ); + let indexed = IndexedSource::new(source); push_source_fact( &mut snapshot.facts, file, - source, + &indexed, PythonSourceFactKind::Module, None, module_range, @@ -259,7 +260,7 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac let module_constants = module_literal_constants(source, &module.body); collect_owners_from_statements( file, - source, + &indexed, &module.body, None, &imports, @@ -268,10 +269,10 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac ); snapshot .owners - .push(module_owner(file, source, module_range, &imports)); + .push(module_owner(file, &indexed, module_range, &imports)); collect_tests_from_statements( file, - source, + &indexed, &module.body, None, false, @@ -281,13 +282,13 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac with_module_rebinding(source, &module.body, &mut snapshot.tests); collect_source_facts_from_statements( file, - source, + &indexed, &module.body, None, None, &mut snapshot.facts, ); - collect_docstring_line_ranges(source, &module.body, &mut snapshot.docstring_line_ranges); + collect_docstring_line_ranges(&indexed, &module.body, &mut snapshot.docstring_line_ranges); snapshot } @@ -298,7 +299,7 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac /// f-strings, and string expressions inside control-flow blocks are deliberately /// excluded: they are not docstrings, even when they use triple quotes. fn collect_docstring_line_ranges( - source: &str, + source: &IndexedSource<'_>, scope_body: &[Stmt], out: &mut Vec>, ) { @@ -317,14 +318,14 @@ fn collect_docstring_line_ranges( /// docstring token. A docstring may share a line with behavioral code through a /// semicolon; such boundary lines must remain analyzable. fn push_docstring_only_line_ranges( - source: &str, + source: &IndexedSource<'_>, range: TextRange, out: &mut Vec>, ) { let start_offset = usize::from(range.start()); let end_offset = usize::from(range.end()); - let start_line = line_for_range_start(source, range); - let end_line = line_for_range_end(source, range); + let start_line = source.line_for_range_start(range); + let end_line = source.line_for_range_end(range); let start_line_offset = source[..start_offset] .rfind('\n') .map_or(0, |offset| offset + 1); @@ -357,7 +358,7 @@ fn push_docstring_only_line_ranges( } fn collect_nested_docstring_scopes( - source: &str, + source: &IndexedSource<'_>, statements: &[Stmt], out: &mut Vec>, ) { @@ -448,7 +449,7 @@ pub(super) fn source_fact_snapshot_observation(facts: &PythonSourceFacts) -> usi fn push_source_fact( out: &mut Vec, file: &Path, - source: &str, + source: &IndexedSource<'_>, kind: PythonSourceFactKind, owner: Option<&str>, range: TextRange, @@ -457,8 +458,8 @@ fn push_source_fact( kind, file: file.to_path_buf(), owner: owner.map(str::to_string), - start_line: line_for_range_start(source, range), - end_line: line_for_range_end(source, range), + start_line: source.line_for_range_start(range), + end_line: source.line_for_range_end(range), start_byte: usize::from(range.start()), end_byte: usize::from(range.end()), text: text_for_range(source, range).trim().to_string(), @@ -467,7 +468,7 @@ fn push_source_fact( fn collect_source_facts_from_statements( file: &Path, - source: &str, + source: &IndexedSource<'_>, statements: &[Stmt], class_context: Option<&str>, current_owner: Option<&str>, @@ -861,7 +862,7 @@ fn collect_source_facts_from_statements( struct PythonFunctionSourceContext<'a> { file: &'a Path, - source: &'a str, + source: &'a IndexedSource<'a>, class_context: Option<&'a str>, name: &'a str, range: TextRange, @@ -919,7 +920,7 @@ fn collect_source_facts_from_function( fn collect_decorator_fact( file: &Path, - source: &str, + source: &IndexedSource<'_>, decorator: &Expr, owner: Option<&str>, out: &mut Vec, @@ -937,7 +938,7 @@ fn collect_decorator_fact( fn collect_parameter_facts( file: &Path, - source: &str, + source: &IndexedSource<'_>, args: &ast::Arguments, owner: Option<&str>, out: &mut Vec, @@ -987,7 +988,7 @@ fn collect_parameter_facts( fn collect_assignment_target_facts( file: &Path, - source: &str, + source: &IndexedSource<'_>, target: &Expr, owner: Option<&str>, out: &mut Vec, @@ -1007,7 +1008,7 @@ fn collect_assignment_target_facts( fn collect_source_facts_from_except_handlers( file: &Path, - source: &str, + source: &IndexedSource<'_>, handlers: &[ast::ExceptHandler], class_context: Option<&str>, current_owner: Option<&str>, @@ -1031,7 +1032,7 @@ fn collect_source_facts_from_except_handlers( fn collect_source_facts_from_expr( file: &Path, - source: &str, + source: &IndexedSource<'_>, expr: &Expr, owner: Option<&str>, out: &mut Vec, @@ -1287,7 +1288,7 @@ fn collect_source_facts_from_expr( fn collect_source_facts_from_comprehensions( file: &Path, - source: &str, + source: &IndexedSource<'_>, comprehensions: &[ast::Comprehension], owner: Option<&str>, out: &mut Vec, diff --git a/crates/ripr/src/analysis/language/python/source_utils.rs b/crates/ripr/src/analysis/language/python/source_utils.rs index b8d8d18778a..a15f95c7abb 100644 --- a/crates/ripr/src/analysis/language/python/source_utils.rs +++ b/crates/ripr/src/analysis/language/python/source_utils.rs @@ -15,12 +15,57 @@ pub(super) fn line_for_offset(source: &str, offset: usize) -> usize { line } -pub(super) fn line_for_range_start(source: &str, range: TextRange) -> usize { - line_for_offset(source, usize::from(range.start())) +/// A source plus its newline byte offsets, so a line lookup is a binary +/// search instead of a scan from the start of the file. Source-fact +/// extraction looks up two lines per fact, and the scan made it quadratic +/// in file size (~79% of a `ripr check` on a Django commit). Lines match +/// `line_for_offset` exactly: a `\n` byte is never part of a multi-byte +/// UTF-8 character, so counting newline bytes before `offset` counts the +/// same newlines as counting newline characters there. +pub(super) struct IndexedSource<'a> { + text: &'a str, + newline_offsets: Vec, +} + +impl<'a> IndexedSource<'a> { + pub(super) fn new(text: &'a str) -> Self { + let newline_offsets = text + .bytes() + .enumerate() + .filter_map(|(offset, byte)| (byte == b'\n').then_some(offset)) + .collect(); + Self { + text, + newline_offsets, + } + } + + /// `line_for_offset(self, offset)`. + pub(super) fn line_for_offset(&self, offset: usize) -> usize { + 1 + self + .newline_offsets + .partition_point(|newline| *newline < offset) + } + + pub(super) fn line_for_range_start(&self, range: TextRange) -> usize { + self.line_for_offset(usize::from(range.start())) + } + + pub(super) fn line_for_range_end(&self, range: TextRange) -> usize { + self.line_for_offset(usize::from(range.end())) + } } -pub(super) fn line_for_range_end(source: &str, range: TextRange) -> usize { - line_for_offset(source, usize::from(range.end())) +impl std::ops::Deref for IndexedSource<'_> { + type Target = str; + + fn deref(&self) -> &str { + self.text + } +} + +pub(super) fn line_for_range_start(source: &str, range: TextRange) -> usize { + line_for_offset(source, usize::from(range.start())) } pub(super) fn text_for_range(source: &str, range: TextRange) -> String { diff --git a/crates/ripr/src/analysis/language/typescript/related_tests.rs b/crates/ripr/src/analysis/language/typescript/related_tests.rs index 260325ef95f..dc9ef1937f6 100644 --- a/crates/ripr/src/analysis/language/typescript/related_tests.rs +++ b/crates/ripr/src/analysis/language/typescript/related_tests.rs @@ -269,12 +269,22 @@ impl ReExportIndex { /// does NOT perform full `PackageDiscovery`. It is used only for the /// package-local ownership filter. pub(crate) fn package_root_for_file_path(file: &Path, workspace_root: &Path) -> Option { + package_root_for_dir(&file_parent_dir(file, workspace_root)?, workspace_root) +} + +/// The directory `package_root_for_file_path` starts its walk from; `None` +/// when the file has no parent. +fn file_parent_dir(file: &Path, workspace_root: &Path) -> Option { let absolute_file = if file.is_absolute() { file.to_path_buf() } else { workspace_root.join(file) }; - let start = absolute_file.parent()?; + absolute_file.parent().map(Path::to_path_buf) +} + +/// The walk behind `package_root_for_file_path`, from the file's directory. +fn package_root_for_dir(start: &Path, workspace_root: &Path) -> Option { let mut current = start.to_path_buf(); loop { if current.join("package.json").is_file() { @@ -302,6 +312,49 @@ pub(crate) fn package_root_for_file_path(file: &Path, workspace_root: &Path) -> None } +/// `same_package_root` for one owner file against many test files. The +/// owner's root is resolved once and each test directory's root at most +/// once, instead of two filesystem walks per test: an owner is checked +/// against every test in the workspace, and those walks were ~64% of a +/// `ripr check` on a vite commit. Answers match `same_package_root` as long +/// as no `package.json` appears or disappears while the scope lives. +pub(crate) struct OwnerPackageScope<'r> { + workspace_root: &'r Path, + owner_package: Option, + package_by_dir: std::cell::RefCell>>, +} + +impl<'r> OwnerPackageScope<'r> { + pub(crate) fn new(owner_file: &Path, workspace_root: &'r Path) -> Self { + Self { + workspace_root, + owner_package: package_root_for_file_path(owner_file, workspace_root), + package_by_dir: std::cell::RefCell::default(), + } + } + + /// `same_package_root(owner_file, test_file, workspace_root)`. + pub(crate) fn contains(&self, test_file: &Path) -> bool { + let Some(owner_package) = &self.owner_package else { + return true; + }; + let Some(dir) = file_parent_dir(test_file, self.workspace_root) else { + return true; + }; + if let Some(test_package) = self.package_by_dir.borrow().get(&dir) { + return test_package + .as_ref() + .is_none_or(|test| test == owner_package); + } + let test_package = package_root_for_dir(&dir, self.workspace_root); + let same = test_package + .as_ref() + .is_none_or(|test| test == owner_package); + self.package_by_dir.borrow_mut().insert(dir, test_package); + same + } +} + /// Return `true` when `owner_file` and `test_file` both resolve to the same /// package root under `workspace_root`, or when either file's package root /// cannot be determined (fail-open: preserve existing behaviour when no @@ -310,6 +363,7 @@ pub(crate) fn package_root_for_file_path(file: &Path, workspace_root: &Path) -> /// A cross-package candidate is one where the owner lives in /// `packages/a/` and the test lives in `packages/b/`. Such a candidate /// MUST NOT be selected as an owned relation. +#[cfg(test)] pub(crate) fn same_package_root( owner_file: &Path, test_file: &Path, @@ -347,13 +401,15 @@ pub(crate) fn related_test_candidates<'a>( reexport_index: &ReExportIndex, alias_map: Option<&TsAliasMap>, ) -> Vec> { + let package_scope = workspace_root.map(|root| OwnerPackageScope::new(&owner.file, root)); + let in_owner_package = |test: &&TypeScriptTest| { + package_scope + .as_ref() + .is_none_or(|scope| scope.contains(&test.file)) + }; let mut candidates: Vec> = all_tests .iter() - .filter(|test| { - workspace_root - .map(|root| same_package_root(&owner.file, &test.file, root)) - .unwrap_or(true) - }) + .filter(in_owner_package) .filter_map(|test| { owner_call_relation(test, owner, reexport_index, alias_map, workspace_root) .map(|relation| TypeScriptRelatedCandidate { test, relation }) @@ -362,11 +418,7 @@ pub(crate) fn related_test_candidates<'a>( if candidates.is_empty() { candidates = all_tests .iter() - .filter(|test| { - workspace_root - .map(|root| same_package_root(&owner.file, &test.file, root)) - .unwrap_or(true) - }) + .filter(in_owner_package) .filter_map(|test| { heuristic_relation(test, owner, alias_map, workspace_root) .map(|relation| TypeScriptRelatedCandidate { test, relation }) diff --git a/crates/ripr/src/analysis/language/typescript/static_limit.rs b/crates/ripr/src/analysis/language/typescript/static_limit.rs index a11a2be9e2a..a4dd803b435 100644 --- a/crates/ripr/src/analysis/language/typescript/static_limit.rs +++ b/crates/ripr/src/analysis/language/typescript/static_limit.rs @@ -317,6 +317,7 @@ pub(crate) fn named_limitations_for_unresolved_ownership( let mut limitations: Vec = Vec::new(); let mut saw_target_unresolved = false; + let package_scope = OwnerPackageScope::new(&owner.file, workspace_root); for test in all_tests { if saw_target_unresolved { break; @@ -324,7 +325,7 @@ pub(crate) fn named_limitations_for_unresolved_ownership( // Only consider tests that are NOT in the same package — cross-package // ones are the real producer. Within-package tests are handled by the // normal candidate logic. - if same_package_root(&owner.file, &test.file, workspace_root) { + if package_scope.contains(&test.file) { continue; } // Check whether this cross-package test actually references the owner diff --git a/crates/ripr/src/analysis/language/typescript/tests.rs b/crates/ripr/src/analysis/language/typescript/tests.rs index ec76ca0461f..c91809f9e3c 100644 --- a/crates/ripr/src/analysis/language/typescript/tests.rs +++ b/crates/ripr/src/analysis/language/typescript/tests.rs @@ -7139,6 +7139,68 @@ fn oracle_confidence_low_for_weak_and_smoke() { // PR6: Ownership hardening — package-local, import forms, typescript_target_unresolved // ────────────────────────────────────────────────────────────────────────────── +/// The per-owner package scope answers every (owner, test) pair exactly as +/// `same_package_root` does, on first (walking) and repeated (cached) +/// queries: nested packages, a directory outside any package, absolute and +/// relative test paths, and an owner with no package root. +#[test] +fn owner_package_scope_matches_same_package_root_for_every_pair() -> Result<(), String> { + use std::fs; + use std::time::{SystemTime, UNIX_EPOCH}; + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let temp = std::env::temp_dir().join(format!("ripr-pkg-scope-{stamp}")); + let root = temp.join("repo"); + for dir in [ + "packages/a/src", + "packages/a/tests/deep", + "packages/a/nested/src", + "packages/b/test", + "scripts", + ] { + fs::create_dir_all(root.join(dir)).map_err(|error| error.to_string())?; + } + for manifest in [ + "packages/a/package.json", + "packages/a/nested/package.json", + "packages/b/package.json", + ] { + fs::write(root.join(manifest), "{}").map_err(|error| error.to_string())?; + } + let files: Vec = [ + "packages/a/src/cart.ts", + "packages/a/tests/cart.test.ts", + "packages/a/tests/deep/cart.test.ts", + "packages/a/nested/src/inner.test.ts", + "packages/b/test/cart.test.ts", + "scripts/cart.test.ts", + "top.test.ts", + ] + .into_iter() + .map(PathBuf::from) + .chain([root.join("packages/b/test/abs.test.ts")]) + .collect(); + let mut compared = 0; + for owner in &files { + let scope = OwnerPackageScope::new(owner, &root); + for round in 0..2 { + for test in &files { + assert_eq!( + scope.contains(test), + same_package_root(owner, test, &root), + "round {round}: owner {owner:?} / test {test:?}" + ); + compared += 1; + } + } + } + let _ = fs::remove_dir_all(&temp); + assert_eq!(compared, files.len() * files.len() * 2); + Ok(()) +} + /// Package-local filter: a test in the SAME package as the owner IS selected. #[test] fn package_local_filter_selects_same_package_test() { From 104af2515c2e29f6e4fd5fc7a58d75b5f5815dae Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:08:44 +0000 Subject: [PATCH 2/9] docs(changelog): record the big-repo check speedups Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 494bb48a279..f86d9cb0c81 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ are scoped or reviewed. ### Fixed +- `ripr check` is faster on large repositories, with byte-identical JSON on + 12 real commits of tokio, vite, Django and ripr. Python source-fact + extraction found each fact's line by scanning the file from the start; + a Django commit went from 6.7 s to 1.7 s. TypeScript test selection + walked the directory tree for `package.json` twice per owner and test; + a vite commit went from 7.4 s to 3.9 s. Rust classification stopped + reparsing the owner's file per probe and computing each related test's + value facts again for every probe in the same owner; a ripr commit went + from 10.8 s to 7.4 s. - `ripr check` spends less time rescanning test files. The same-name-import gate re-masked every related test file's source for every probe; one scan per file now serves the whole run. On a ripr commit, a warm check went from From 2fdd7dc1fc4405beb7f36d584d83e70b9a86f9df Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:30:56 +0000 Subject: [PATCH 3/9] docs(changelog): use timings measured against current main Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f86d9cb0c81..c3069742c03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,12 +14,12 @@ are scoped or reviewed. - `ripr check` is faster on large repositories, with byte-identical JSON on 12 real commits of tokio, vite, Django and ripr. Python source-fact extraction found each fact's line by scanning the file from the start; - a Django commit went from 6.7 s to 1.7 s. TypeScript test selection + a Django commit went from 6.9 s to 1.5 s. TypeScript test selection walked the directory tree for `package.json` twice per owner and test; - a vite commit went from 7.4 s to 3.9 s. Rust classification stopped + a vite commit went from 6.7 s to 3.2 s. Rust classification stopped reparsing the owner's file per probe and computing each related test's value facts again for every probe in the same owner; a ripr commit went - from 10.8 s to 7.4 s. + from 11.1 s to 8.1 s. - `ripr check` spends less time rescanning test files. The same-name-import gate re-masked every related test file's source for every probe; one scan per file now serves the whole run. On a ripr commit, a warm check went from From ccdb8a8318cb61244adf185e284951ca40383930 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:40:49 +0000 Subject: [PATCH 4/9] refactor(check): name the value-facts memo key type Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- crates/ripr/src/analysis/classify/activation.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/classify/activation.rs b/crates/ripr/src/analysis/classify/activation.rs index 7560976ad7d..8d15888fa74 100644 --- a/crates/ripr/src/analysis/classify/activation.rs +++ b/crates/ripr/src/analysis/classify/activation.rs @@ -107,10 +107,14 @@ struct ParameterValue { /// or owner that is not an element of that index, or a query against /// another index, is computed fresh and never cached, so a key can only /// ever name the same fact values. +/// A related test's slot in `RustIndex::tests` and its owner's slot in +/// `RustIndex::functions` (`None` for an ownerless probe). +type TestOwnerSlot = (usize, Option); + #[derive(Clone, Debug, Default)] pub(in crate::analysis) struct TestValueFacts { index_identity: std::cell::Cell>, - by_slot: std::cell::RefCell), Vec>>, + by_slot: std::cell::RefCell>>, } impl TestValueFacts { @@ -137,7 +141,7 @@ impl TestValueFacts { index: &crate::analysis::rust_index::RustIndex, test: &TestSummary, owner_fn: Option<&FunctionSummary>, - ) -> Option<(usize, Option)> { + ) -> Option { let identity = ( index.tests.as_ptr() as usize, index.functions.as_ptr() as usize, From 1f7f457cebcd640b2f103957928788d6548071d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:51:33 +0000 Subject: [PATCH 5/9] test(check): cover overlapping test-name word matches Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- crates/ripr/src/analysis/classify/related_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 2517d1e3f53..f17fde8e606 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -3487,7 +3487,9 @@ fn crate_c_score_test() { let alphabet = ["a", "b", "_", "é"]; let mut strings = vec![String::new()]; let mut level = vec![String::new()]; - for _ in 0..5 { + // Six characters reach `ba_a_a` / `a_a`: the only whole-word match + // overlaps a rejected one, which a non-overlapping search misses. + for _ in 0..6 { level = level .iter() .flat_map(|text| alphabet.iter().map(move |letter| format!("{text}{letter}"))) @@ -3509,7 +3511,7 @@ fn crate_c_score_test() { checked += 1; } } - assert!(checked > 100_000, "only {checked} pairs checked"); + assert!(checked > 300_000, "only {checked} pairs checked"); } #[test] From c6fef48a8d65b600a1c86f1a59340b5b8d8b38fb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 01:58:36 +0000 Subject: [PATCH 6/9] docs(changelog): say when the owner reparse is still needed Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3069742c03..4c436887382 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,9 +16,10 @@ are scoped or reviewed. extraction found each fact's line by scanning the file from the start; a Django commit went from 6.9 s to 1.5 s. TypeScript test selection walked the directory tree for `package.json` twice per owner and test; - a vite commit went from 6.7 s to 3.2 s. Rust classification stopped - reparsing the owner's file per probe and computing each related test's - value facts again for every probe in the same owner; a ripr commit went + a vite commit went from 6.7 s to 3.2 s. Rust classification no longer + reparses the owner's file per probe unless the file could admit the + derived tuple slice, and computes each related test's value facts once + per owner instead of once per probe; a ripr commit went from 11.1 s to 8.1 s. - `ripr check` spends less time rescanning test files. The same-name-import gate re-masked every related test file's source for every probe; one scan From eea44728bbd06b060f1bc1ac7941cf22b92d6c5a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 03:32:21 +0000 Subject: [PATCH 7/9] Drop Python line index in favour of #4580; route module-entry reach through OwnerPackageScope #4580 owns the Python line-start index (SourceText), so this PR no longer carries IndexedSource. Main's new same-module entry reach used the removed same_package_root call; it now shares the owner's package scope with the other candidate passes. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- CHANGELOG.md | 4 +- .../analysis/language/python/owners_tests.rs | 28 +++++----- .../analysis/language/python/python_tests.rs | 19 ------- .../analysis/language/python/source_facts.rs | 47 ++++++++-------- .../analysis/language/python/source_utils.rs | 53 ++----------------- .../language/typescript/related_tests.rs | 6 +-- 6 files changed, 44 insertions(+), 113 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a61af7b3af0..2cb3002ecd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,9 +12,7 @@ are scoped or reviewed. ### Fixed - `ripr check` is faster on large repositories, with byte-identical JSON on - 12 real commits of tokio, vite, Django and ripr. Python source-fact - extraction found each fact's line by scanning the file from the start; - a Django commit went from 6.9 s to 1.5 s. TypeScript test selection + 12 real commits of tokio, vite, Django and ripr. TypeScript test selection walked the directory tree for `package.json` twice per owner and test; a vite commit went from 6.7 s to 3.2 s. Rust classification no longer reparses the owner's file per probe unless the file could admit the diff --git a/crates/ripr/src/analysis/language/python/owners_tests.rs b/crates/ripr/src/analysis/language/python/owners_tests.rs index 78506ee012f..1818c014f75 100644 --- a/crates/ripr/src/analysis/language/python/owners_tests.rs +++ b/crates/ripr/src/analysis/language/python/owners_tests.rs @@ -3,7 +3,9 @@ use super::module_constants::{ }; #[cfg(test)] use super::source_facts::extract_source_facts; -use super::source_utils::{IndexedSource, normalized_path, text_for_range}; +use super::source_utils::{ + line_for_range_end, line_for_range_start, normalized_path, text_for_range, +}; use super::static_limits::{collect_static_cli_receiver_names, is_static_route_decorator}; use super::{ PythonImport, PythonOwner, PythonParameter, PythonTest, collect_assertions_from_statements, @@ -23,7 +25,7 @@ pub(super) fn extract_owners(file: &Path, source: &str) -> Vec { pub(super) fn collect_owners_from_statements( file: &Path, - source: &IndexedSource<'_>, + source: &str, statements: &[Stmt], class_context: Option<&str>, imports: &[PythonImport], @@ -97,7 +99,7 @@ pub(super) fn collect_owners_from_statements( #[derive(Clone, Copy)] struct PythonOwnerContext<'a> { file: &'a Path, - source: &'a IndexedSource<'a>, + source: &'a str, class_context: Option<&'a str>, imports: &'a [PythonImport], module_constants: &'a [PythonModuleConstant], @@ -137,8 +139,8 @@ fn owner_from_function( name: name.to_string(), qualified_name, file: context.file.to_path_buf(), - start_line: context.source.line_for_range_start(range), - end_line: context.source.line_for_range_end(range), + start_line: line_for_range_start(context.source, range), + end_line: line_for_range_end(context.source, range), owner_kind: Some(owner_kind), decorators, imports: context.imports.to_vec(), @@ -189,8 +191,8 @@ fn owner_from_class( name: name.to_string(), qualified_name, file: context.file.to_path_buf(), - start_line: context.source.line_for_range_start(range), - end_line: context.source.line_for_range_end(range), + start_line: line_for_range_start(context.source, range), + end_line: line_for_range_end(context.source, range), owner_kind: None, decorators: decorator_names(decorators), imports: context.imports.to_vec(), @@ -205,7 +207,7 @@ fn owner_from_class( pub(super) fn module_owner( file: &Path, - source: &IndexedSource<'_>, + source: &str, range: TextRange, imports: &[PythonImport], ) -> PythonOwner { @@ -213,8 +215,8 @@ pub(super) fn module_owner( name: "".to_string(), qualified_name: "".to_string(), file: file.to_path_buf(), - start_line: source.line_for_range_start(range), - end_line: source.line_for_range_end(range), + start_line: line_for_range_start(source, range), + end_line: line_for_range_end(source, range), owner_kind: Some(OwnerKind::ModuleFunction), decorators: Vec::new(), imports: imports.to_vec(), @@ -237,7 +239,7 @@ pub(super) fn extract_tests(file: &Path, source: &str) -> Vec { /// Custom collection prefixes and hooks are not resolved here. pub(super) fn collect_tests_from_statements( file: &Path, - source: &IndexedSource<'_>, + source: &str, statements: &[Stmt], class_context: Option<&str>, in_unittest_class: bool, @@ -257,7 +259,7 @@ pub(super) fn collect_tests_from_statements( qualified_name: qualified_test_name(class_context, &name), name, file: file.to_path_buf(), - line: source.line_for_range_start(function.range), + line: line_for_range_start(source, function.range), body_text: text_for_range(source, function.range), imports: imports.to_vec(), decorators: decorator_names(&function.decorator_list), @@ -283,7 +285,7 @@ pub(super) fn collect_tests_from_statements( qualified_name: qualified_test_name(class_context, &name), name, file: file.to_path_buf(), - line: source.line_for_range_start(function.range), + line: line_for_range_start(source, function.range), body_text: text_for_range(source, function.range), imports: imports.to_vec(), decorators: decorator_names(&function.decorator_list), diff --git a/crates/ripr/src/analysis/language/python/python_tests.rs b/crates/ripr/src/analysis/language/python/python_tests.rs index 27d452ce55b..60d000f780a 100644 --- a/crates/ripr/src/analysis/language/python/python_tests.rs +++ b/crates/ripr/src/analysis/language/python/python_tests.rs @@ -1262,25 +1262,6 @@ fn line_for_offset_counts_newlines() { assert_eq!(line_for_offset(source, 999), 3); } -/// The newline index answers every offset, including offsets inside a -/// multi-byte character, on a `\r\n` line, and past the end, exactly as -/// the scanning `line_for_offset` does. -#[test] -fn indexed_source_lines_match_line_for_offset_at_every_offset() { - let source = "def f():\r\n return \"é→\"\n\n\nx = 1 # ü\n"; - let indexed = super::source_utils::IndexedSource::new(source); - for offset in 0..=source.len() + 2 { - assert_eq!( - indexed.line_for_offset(offset), - line_for_offset(source, offset), - "offset {offset}" - ); - } - assert_eq!(&*indexed, source); - let empty = super::source_utils::IndexedSource::new(""); - assert_eq!(empty.line_for_offset(0), line_for_offset("", 0)); -} - #[test] fn looks_like_call_expression_handles_trailing_semicolons_and_whitespace() { assert!(looks_like_call_expression("notify(event);")); diff --git a/crates/ripr/src/analysis/language/python/source_facts.rs b/crates/ripr/src/analysis/language/python/source_facts.rs index 36250466faf..9a1ec942996 100644 --- a/crates/ripr/src/analysis/language/python/source_facts.rs +++ b/crates/ripr/src/analysis/language/python/source_facts.rs @@ -3,7 +3,7 @@ use super::owners_tests::{ collect_imports_from_statements, collect_owners_from_statements, collect_tests_from_statements, module_owner, }; -use super::source_utils::{IndexedSource, text_for_range}; +use super::source_utils::{line_for_range_end, line_for_range_start, text_for_range}; use super::{PythonOwner, PythonTest, expr_full_name}; use crate::domain::{LanguageId as DomainLanguageId, StaticLimitKind}; use rustpython_parser::{ @@ -246,11 +246,10 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac TextSize::from(0), TextSize::from(u32::try_from(source.len()).unwrap_or(u32::MAX)), ); - let indexed = IndexedSource::new(source); push_source_fact( &mut snapshot.facts, file, - &indexed, + source, PythonSourceFactKind::Module, None, module_range, @@ -260,7 +259,7 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac let module_constants = module_literal_constants(source, &module.body); collect_owners_from_statements( file, - &indexed, + source, &module.body, None, &imports, @@ -269,10 +268,10 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac ); snapshot .owners - .push(module_owner(file, &indexed, module_range, &imports)); + .push(module_owner(file, source, module_range, &imports)); collect_tests_from_statements( file, - &indexed, + source, &module.body, None, false, @@ -282,13 +281,13 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac with_module_rebinding(source, &module.body, &mut snapshot.tests); collect_source_facts_from_statements( file, - &indexed, + source, &module.body, None, None, &mut snapshot.facts, ); - collect_docstring_line_ranges(&indexed, &module.body, &mut snapshot.docstring_line_ranges); + collect_docstring_line_ranges(source, &module.body, &mut snapshot.docstring_line_ranges); snapshot } @@ -299,7 +298,7 @@ pub(super) fn extract_source_facts(file: &Path, source: &str) -> PythonSourceFac /// f-strings, and string expressions inside control-flow blocks are deliberately /// excluded: they are not docstrings, even when they use triple quotes. fn collect_docstring_line_ranges( - source: &IndexedSource<'_>, + source: &str, scope_body: &[Stmt], out: &mut Vec>, ) { @@ -318,14 +317,14 @@ fn collect_docstring_line_ranges( /// docstring token. A docstring may share a line with behavioral code through a /// semicolon; such boundary lines must remain analyzable. fn push_docstring_only_line_ranges( - source: &IndexedSource<'_>, + source: &str, range: TextRange, out: &mut Vec>, ) { let start_offset = usize::from(range.start()); let end_offset = usize::from(range.end()); - let start_line = source.line_for_range_start(range); - let end_line = source.line_for_range_end(range); + let start_line = line_for_range_start(source, range); + let end_line = line_for_range_end(source, range); let start_line_offset = source[..start_offset] .rfind('\n') .map_or(0, |offset| offset + 1); @@ -358,7 +357,7 @@ fn push_docstring_only_line_ranges( } fn collect_nested_docstring_scopes( - source: &IndexedSource<'_>, + source: &str, statements: &[Stmt], out: &mut Vec>, ) { @@ -449,7 +448,7 @@ pub(super) fn source_fact_snapshot_observation(facts: &PythonSourceFacts) -> usi fn push_source_fact( out: &mut Vec, file: &Path, - source: &IndexedSource<'_>, + source: &str, kind: PythonSourceFactKind, owner: Option<&str>, range: TextRange, @@ -458,8 +457,8 @@ fn push_source_fact( kind, file: file.to_path_buf(), owner: owner.map(str::to_string), - start_line: source.line_for_range_start(range), - end_line: source.line_for_range_end(range), + start_line: line_for_range_start(source, range), + end_line: line_for_range_end(source, range), start_byte: usize::from(range.start()), end_byte: usize::from(range.end()), text: text_for_range(source, range).trim().to_string(), @@ -468,7 +467,7 @@ fn push_source_fact( fn collect_source_facts_from_statements( file: &Path, - source: &IndexedSource<'_>, + source: &str, statements: &[Stmt], class_context: Option<&str>, current_owner: Option<&str>, @@ -862,7 +861,7 @@ fn collect_source_facts_from_statements( struct PythonFunctionSourceContext<'a> { file: &'a Path, - source: &'a IndexedSource<'a>, + source: &'a str, class_context: Option<&'a str>, name: &'a str, range: TextRange, @@ -920,7 +919,7 @@ fn collect_source_facts_from_function( fn collect_decorator_fact( file: &Path, - source: &IndexedSource<'_>, + source: &str, decorator: &Expr, owner: Option<&str>, out: &mut Vec, @@ -938,7 +937,7 @@ fn collect_decorator_fact( fn collect_parameter_facts( file: &Path, - source: &IndexedSource<'_>, + source: &str, args: &ast::Arguments, owner: Option<&str>, out: &mut Vec, @@ -988,7 +987,7 @@ fn collect_parameter_facts( fn collect_assignment_target_facts( file: &Path, - source: &IndexedSource<'_>, + source: &str, target: &Expr, owner: Option<&str>, out: &mut Vec, @@ -1008,7 +1007,7 @@ fn collect_assignment_target_facts( fn collect_source_facts_from_except_handlers( file: &Path, - source: &IndexedSource<'_>, + source: &str, handlers: &[ast::ExceptHandler], class_context: Option<&str>, current_owner: Option<&str>, @@ -1032,7 +1031,7 @@ fn collect_source_facts_from_except_handlers( fn collect_source_facts_from_expr( file: &Path, - source: &IndexedSource<'_>, + source: &str, expr: &Expr, owner: Option<&str>, out: &mut Vec, @@ -1288,7 +1287,7 @@ fn collect_source_facts_from_expr( fn collect_source_facts_from_comprehensions( file: &Path, - source: &IndexedSource<'_>, + source: &str, comprehensions: &[ast::Comprehension], owner: Option<&str>, out: &mut Vec, diff --git a/crates/ripr/src/analysis/language/python/source_utils.rs b/crates/ripr/src/analysis/language/python/source_utils.rs index a15f95c7abb..b8d8d18778a 100644 --- a/crates/ripr/src/analysis/language/python/source_utils.rs +++ b/crates/ripr/src/analysis/language/python/source_utils.rs @@ -15,59 +15,14 @@ pub(super) fn line_for_offset(source: &str, offset: usize) -> usize { line } -/// A source plus its newline byte offsets, so a line lookup is a binary -/// search instead of a scan from the start of the file. Source-fact -/// extraction looks up two lines per fact, and the scan made it quadratic -/// in file size (~79% of a `ripr check` on a Django commit). Lines match -/// `line_for_offset` exactly: a `\n` byte is never part of a multi-byte -/// UTF-8 character, so counting newline bytes before `offset` counts the -/// same newlines as counting newline characters there. -pub(super) struct IndexedSource<'a> { - text: &'a str, - newline_offsets: Vec, -} - -impl<'a> IndexedSource<'a> { - pub(super) fn new(text: &'a str) -> Self { - let newline_offsets = text - .bytes() - .enumerate() - .filter_map(|(offset, byte)| (byte == b'\n').then_some(offset)) - .collect(); - Self { - text, - newline_offsets, - } - } - - /// `line_for_offset(self, offset)`. - pub(super) fn line_for_offset(&self, offset: usize) -> usize { - 1 + self - .newline_offsets - .partition_point(|newline| *newline < offset) - } - - pub(super) fn line_for_range_start(&self, range: TextRange) -> usize { - self.line_for_offset(usize::from(range.start())) - } - - pub(super) fn line_for_range_end(&self, range: TextRange) -> usize { - self.line_for_offset(usize::from(range.end())) - } -} - -impl std::ops::Deref for IndexedSource<'_> { - type Target = str; - - fn deref(&self) -> &str { - self.text - } -} - pub(super) fn line_for_range_start(source: &str, range: TextRange) -> usize { line_for_offset(source, usize::from(range.start())) } +pub(super) fn line_for_range_end(source: &str, range: TextRange) -> usize { + line_for_offset(source, usize::from(range.end())) +} + pub(super) fn text_for_range(source: &str, range: TextRange) -> String { let start = usize::from(range.start()).min(source.len()); let end = usize::from(range.end()).min(source.len()); diff --git a/crates/ripr/src/analysis/language/typescript/related_tests.rs b/crates/ripr/src/analysis/language/typescript/related_tests.rs index c999ddfe945..5e18bd6ca5b 100644 --- a/crates/ripr/src/analysis/language/typescript/related_tests.rs +++ b/crates/ripr/src/analysis/language/typescript/related_tests.rs @@ -665,11 +665,7 @@ pub(crate) fn related_test_candidates<'a>( if candidates.is_empty() && !owner.module_entries.is_empty() { candidates = all_tests .iter() - .filter(|test| { - workspace_root - .map(|root| same_package_root(&owner.file, &test.file, root)) - .unwrap_or(true) - }) + .filter(in_owner_package) .filter(|test| { module_entry_relation(test, owner, reexport_index, alias_map, workspace_root) }) From 225a1d540b917a8b586abda747feb6f9c90f8746 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 03:44:15 +0000 Subject: [PATCH 8/9] Format typescript/mod.rs module order (red on main after #4635) Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- crates/ripr/src/analysis/language/typescript/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ripr/src/analysis/language/typescript/mod.rs b/crates/ripr/src/analysis/language/typescript/mod.rs index 906b2f097ef..f2da11bddfd 100644 --- a/crates/ripr/src/analysis/language/typescript/mod.rs +++ b/crates/ripr/src/analysis/language/typescript/mod.rs @@ -52,9 +52,9 @@ mod bounded_read; mod bun_bridge; mod classifier; mod discovery; -mod module_entries; #[cfg(test)] mod line_index_tests; +mod module_entries; #[cfg(test)] mod new_declaration_tests; mod oracle; From 1411148e48bd71b72e8252902ccc2a3f2a0a4155 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 03:51:06 +0000 Subject: [PATCH 9/9] Pass SourceText to computed test titles (main fails to build after #4593 and #4635) #4593 added a computed-title path calling the free line_for_offset, which #4635 made test-only in favour of SourceText::line_for_offset. Each merged green alone; together main does not compile. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_015fB1dGecsPvXwSxSuqCNQQ --- .../ripr/src/analysis/language/typescript/tests_extract.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ripr/src/analysis/language/typescript/tests_extract.rs b/crates/ripr/src/analysis/language/typescript/tests_extract.rs index e398c9bbb99..191055ed81f 100644 --- a/crates/ripr/src/analysis/language/typescript/tests_extract.rs +++ b/crates/ripr/src/analysis/language/typescript/tests_extract.rs @@ -1339,7 +1339,7 @@ fn argument_parameter_names(argument: &oxc_ast::ast::Argument<'_>) -> Vec( stmt: &'a Statement<'a>, - source: &str, + source: &SourceText<'_>, ) -> Option<(String, &'a oxc_allocator::Vec<'a, Statement<'a>>)> { let Statement::ExpressionStatement(expr_stmt) = stmt else { return None; @@ -1472,7 +1472,7 @@ fn is_active_declaration_modifier(name: &str) -> bool { /// runtime value. A spread argument is not a title. fn title_argument( arg: &oxc_ast::ast::Argument<'_>, - source: &str, + source: &SourceText<'_>, registration_start: usize, ) -> Option { match arg { @@ -1481,7 +1481,7 @@ fn title_argument( oxc_ast::ast::Argument::TemplateLiteral(template) if template.single_quasi().is_some() => { template.single_quasi().map(|quasi| quasi.to_string()) } - _ => Some(computed_title(line_for_offset(source, registration_start))), + _ => Some(computed_title(source.line_for_offset(registration_start))), } }