diff --git a/CHANGELOG.md b/CHANGELOG.md index d4b2c53c66d..7bb575d3ba0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,14 @@ 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. 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 + 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. - Security: Rust source discovery skips symlinked `.rs` entries, as the Python and TypeScript readers already did. A cloned repository or pull request that committed `src/zero.rs -> /dev/zero` made `ripr check` read 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..8d15888fa74 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,88 @@ 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. +/// 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>>, +} + +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 { + 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 +2822,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..f17fde8e606 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,41 @@ 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()]; + // 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}"))) + .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 > 300_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/typescript/related_tests.rs b/crates/ripr/src/analysis/language/typescript/related_tests.rs index 5d0d25538bd..bb259a2fcc6 100644 --- a/crates/ripr/src/analysis/language/typescript/related_tests.rs +++ b/crates/ripr/src/analysis/language/typescript/related_tests.rs @@ -514,12 +514,22 @@ fn push_declaration_export_names(declaration: &Declaration<'_>, names: &mut Vec< /// 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() { @@ -547,6 +557,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 @@ -555,6 +608,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, @@ -592,13 +646,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 }) @@ -609,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) }) @@ -626,11 +678,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 329614e133c..c01191c342c 100644 --- a/crates/ripr/src/analysis/language/typescript/static_limit.rs +++ b/crates/ripr/src/analysis/language/typescript/static_limit.rs @@ -324,6 +324,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; @@ -331,7 +332,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 964f34a45ee..a0150840277 100644 --- a/crates/ripr/src/analysis/language/typescript/tests.rs +++ b/crates/ripr/src/analysis/language/typescript/tests.rs @@ -7243,6 +7243,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() {