From 0ea255ce29b2f8fb72d689c2f637b1d52f4660d8 Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:42:24 -0500 Subject: [PATCH 01/14] fix(analysis): credit aliased owner imports and fail closed on #[path] redirects (#14508) --- .ripr/traceability.d/RIPR-SPEC-0442.toml | 45 + changelog.d/14508-aliased-owner-import.md | 10 + .../ripr/src/analysis/classifier/evidence.rs | 1 + .../ripr/src/analysis/classify/const_flow.rs | 40 + crates/ripr/src/analysis/classify/mod.rs | 18 +- .../src/analysis/classify/related_tests.rs | 17 + crates/ripr/src/analysis/extract/shadow.rs | 217 +++- crates/ripr/src/analysis/facts/model.rs | 9 +- crates/ripr/src/analysis/syntax/ra.rs | 207 +++- .../ripr/src/analysis/test_grip_evidence.rs | 54 +- .../test_grip_evidence/related_tests.rs | 397 +++++- .../related_tests/context.rs | 486 ++++++++ .../src/analysis/test_grip_evidence/tests.rs | 1078 +++++++++++++++++ docs/spec-index.d/RIPR-SPEC-0442.md | 1 + ...R-SPEC-0442-aliased-owner-import-credit.md | 159 +++ ...t_test_local_rival_import_alias_crate.json | 26 + ...est_local_rival_import_alias_external.json | 26 + .../corpus.json | 4 +- .../Cargo.toml | 10 + .../src/lib.rs | 17 + .../Cargo.toml | 10 + .../src/lib.rs | 7 + .../tests/control.rs | 6 + .../rust-repo-exposure-alias-crate.json | 52 + .../rust-repo-exposure-alias-external.json | 52 + policy/doc-artifacts.d/RIPR-SPEC-0442.toml | 7 + xtask/src/evidence_promotion.rs | 132 ++ xtask/src/main.rs | 7 +- 28 files changed, 3001 insertions(+), 94 deletions(-) create mode 100644 .ripr/traceability.d/RIPR-SPEC-0442.toml create mode 100644 changelog.d/14508-aliased-owner-import.md create mode 100644 docs/spec-index.d/RIPR-SPEC-0442.md create mode 100644 docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md create mode 100644 fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json create mode 100644 fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json create mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml create mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs create mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml create mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs create mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs create mode 100644 fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json create mode 100644 fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json create mode 100644 policy/doc-artifacts.d/RIPR-SPEC-0442.toml diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..b34c3660ecd --- /dev/null +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -0,0 +1,45 @@ +# Aliased direct import of the owner credits the owner only when the import +# names its module in the same compilation unit (#14508). +[[behavior]] +id = "RIPR-SPEC-0442" +name = "Aliased owner import credit" +spec = "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md" +tests = [ + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_owner_takes_no_value_from_it", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_table_covers_each_scanned_form", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_ignores_a_genuine_call_in_the_last_match_arm", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_keeps_a_real_match_arm_binding", +] +fixtures = [ + "fixtures/evidence-promotion-honesty-corpus/corpus.json", + "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json", + "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json", +] +code = [ + "crates/ripr/src/analysis/test_grip_evidence/related_tests.rs", + "crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs", + "crates/ripr/src/analysis/classify/const_flow.rs", + "crates/ripr/src/analysis/extract/shadow.rs", +] +outputs = [ + "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md", +] +metrics = [ + "unit_test_pass_rate", + "corpus_case_pass_rate", +] diff --git a/changelog.d/14508-aliased-owner-import.md b/changelog.d/14508-aliased-owner-import.md new file mode 100644 index 00000000000..c1db2263adf --- /dev/null +++ b/changelog.d/14508-aliased-owner-import.md @@ -0,0 +1,10 @@ + +- `ripr pilot` and the repo-exposure grip path credit a test that imports the + changed owner under an alias as a direct owner call when the import names the + owner's module (crate root, nested file module, `mod.rs`, or an integration + test's package-qualified import). A `crate::` import in an integration test + names that test crate's own module, so it does not credit the library owner + (#14508). The alias credits only when the resolved `crate::` chain file is + the owner file; a missing declaration or a non-literal `#[path]` on any + segment is withheld. Inline-module owners stay uncredited, tracked in + #14558. diff --git a/crates/ripr/src/analysis/classifier/evidence.rs b/crates/ripr/src/analysis/classifier/evidence.rs index 0bcfa478ce0..70172a5f6cc 100644 --- a/crates/ripr/src/analysis/classifier/evidence.rs +++ b/crates/ripr/src/analysis/classifier/evidence.rs @@ -3862,6 +3862,7 @@ mod tests { fn owner_local_bindings_exclude_names_the_signature_binds() { let binding = |name: &str| LetBindingFact { line: 1, + scope_end: None, name: name.to_string(), }; let owner = FunctionSummary { diff --git a/crates/ripr/src/analysis/classify/const_flow.rs b/crates/ripr/src/analysis/classify/const_flow.rs index 9e7c6b1249a..3fab2b9c6a3 100644 --- a/crates/ripr/src/analysis/classify/const_flow.rs +++ b/crates/ripr/src/analysis/classify/const_flow.rs @@ -211,6 +211,46 @@ impl ModuleScopes { .iter() .all(|line| self.0.get(line) == Some(declared)) } + + /// The chain of inline `mod` names in force at `line`, outermost first, + /// ignoring non-module blocks. `None` when the line is outside the + /// scanned source (#14508 review). + pub(in crate::analysis) fn module_chain_at(&self, line: usize) -> Option> { + let chain = self.0.get(&line)?; + Some(chain.iter().filter_map(|name| name.as_deref()).collect()) + } + + /// Whether the chain of `mod` items in force at `declaration_line` is at + /// least as deep as `use_module_depth` and is a prefix of the chain at + /// `call_line`. That is a declaration in the import's module or a nested + /// module, and in the call's module or an enclosing one. A declaration in + /// an enclosing module than the import is shadowed by the import, so it + /// does not withhold the call (#14508 review). + pub(in crate::analysis) fn declaration_shadows_import( + &self, + declaration_line: usize, + use_module_depth: usize, + call_line: usize, + ) -> bool { + let (Some(declared), Some(used)) = (self.0.get(&declaration_line), self.0.get(&call_line)) + else { + return false; + }; + let declared = declared + .iter() + .filter_map(|name| name.as_deref()) + .collect::>(); + let used = used + .iter() + .filter_map(|name| name.as_deref()) + .collect::>(); + declared.len() >= use_module_depth + && declared.len() <= used.len() + && declared + .iter() + .zip(used.iter()) + .all(|(declared, used)| declared == used) + } } /// What evaluating the related tests under the old and new value showed. diff --git a/crates/ripr/src/analysis/classify/mod.rs b/crates/ripr/src/analysis/classify/mod.rs index 4ac79745b01..3a89853db70 100644 --- a/crates/ripr/src/analysis/classify/mod.rs +++ b/crates/ripr/src/analysis/classify/mod.rs @@ -100,7 +100,7 @@ pub(in crate::analysis) use caller_loop_selector::withhold_caller_loop_selector_ pub(in crate::analysis) use compile_time_guard::constrained_by_compile_time_assertion; pub(in crate::analysis) use const_flow::{ ChangedConsts, ConstFlow, associated_const_binding, const_value_changes, evaluate_const_flow, - shares_module_scope, + module_scopes, shares_module_scope, }; pub(in crate::analysis) use const_readers::{const_reader_returns, same_file_const_readers}; pub(in crate::analysis) use context::ProbeContext; @@ -208,14 +208,14 @@ pub(in crate::analysis) use refusal_miss::{ }; pub(in crate::analysis) use related_tests::{ DependencyEdgeContext, RelatedTestCandidateIndex, assertion_pins_display_string, - body_contains_owner_call, call_text_may_call_free_function, changes_only_string_literals, - companion_scope_admits, declared_dependent_package_calls_owner, - find_related_tests_with_candidate_index, free_helper_call_resolves, impl_self_type_name, - inherent_owner_call_resolves, is_display_fmt_owner, is_drop_destructor, is_partial_eq_method, - manifests_with_unindexed_files, method_call_resolves_to_impl, module_stem, - owner_call_is_direct, owner_call_text, owner_dispatch_trait, owner_impl_identity_shadowed, - owner_trait_name, package_prefix, requires_inherent_receiver_identity, - resolves_method_in_prefix, test_calls_free_function, + body_contains_owner_call, call_text_may_call_free_function, call_text_spells_bare_free_call, + changes_only_string_literals, companion_scope_admits, declared_dependent_package_calls_owner, + find_related_tests_with_candidate_index, free_function_call_text, free_helper_call_resolves, + impl_self_type_name, inherent_owner_call_resolves, is_display_fmt_owner, is_drop_destructor, + is_partial_eq_method, manifests_with_unindexed_files, method_call_resolves_to_impl, + module_stem, owner_call_is_direct, owner_call_text, owner_dispatch_trait, + owner_impl_identity_shadowed, owner_trait_name, package_prefix, + requires_inherent_receiver_identity, resolves_method_in_prefix, test_calls_free_function, }; #[cfg(feature = "lang-rust")] pub(in crate::analysis) use reveal::RELATED_TESTS_RENDER_CAP; diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index aad7e0dccee..56960f34374 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -8108,6 +8108,23 @@ pub(in crate::analysis) fn free_function_call_text<'text>( text.get(at..) } +/// Whether one captured call's raw source text spells the bare free-function +/// call `name(` — the only spelling an imported alias can bind to. A +/// module-qualified path (`rival::name(`) names that module's function, not +/// the alias, even when the module name is lowercase (#14508 review). +pub(in crate::analysis) fn call_text_spells_bare_free_call(text: &str, name: &str) -> bool { + if name.is_empty() { + return false; + } + let masked = mask_comments_and_strings(text); + let mut calls = masked + .match_indices(name) + .map(|(at, _)| at) + .filter(|&at| is_free_function_call_at(&masked, at, name)) + .peekable(); + calls.peek().is_some() && calls.all(|at| !masked[..at].trim_end().ends_with("::")) +} + /// The text a captured call named like `owner` contributes as an owner /// call: the whole line for an owner that may be reached through a path or /// receiver, the free-call suffix for a module-level `fn`, `None` when the diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index 71b90eb8f5b..dba182ba14e 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -10,15 +10,17 @@ //! the original text, and shadow-shaped text inside comments, strings, or //! char literals never defeats a real call (#3728 rounds 3-5). //! -//! #3727 Slice A adds a parser-backed decision path with the SAME rules at -//! line granularity: on files whose `FileFacts.used_lexical_fallback` is -//! false, [`ShadowAuthority::ParserBodyFacts`] derives the decision from -//! the parser-produced `nested_fn_names` / `let_bindings` fact fields; on -//! fallback files (or files absent from the index) -//! [`ShadowAuthority::LexicalMaskedBody`] runs the byte-level scanners -//! byte-identically. THE FLAG — not set emptiness — is the discriminator: -//! a parser-backed file can legitimately contain zero bindings, and empty -//! fact sets on parser-backed files are real "no shadow" results. +//! The two authorities share the same binding vocabulary and the same +//! whole-body `let`/nested-`fn` rules, but they diverge deliberately for the +//! scoped binding forms added in #14508: the parser path carries each +//! binding's `scope_end` and defeats only uses inside that body/arm, while +//! the lexical fallback detects the same forms and withholds the whole body. +//! The fallback is deliberately conservative (it may drop credit for a +//! genuine call after the scope on a file the parser could not read; it +//! never grants credit to a scoped binding). THE FLAG — not set emptiness — +//! is the discriminator: a parser-backed file can legitimately contain zero +//! bindings, and empty fact sets on parser-backed files are real "no shadow" +//! results. use crate::analysis::facts::LetBindingFact; @@ -90,12 +92,18 @@ pub(crate) fn fact_body_let_shadow_line( } let_bindings .iter() + .filter(|binding| binding.scope_end.is_none()) .filter(|binding| binding.name == callee) .map(|binding| binding.line) .min() } /// Parser-fact twin of [`body_shadows_callee_at_line`] (#3727 Slice A). +/// +/// A `let` binding keeps the shipped end-of-function over-approximation +/// (`scope_end == None`); a closure, `for`, match-arm, `if let`/`while let` +/// or nested-fn parameter carries its body/arm end and defeats only uses +/// inside that scope (#14508 review). pub(crate) fn fact_body_shadows_callee_at_line( nested_fn_names: &[String], let_bindings: &[LetBindingFact], @@ -103,7 +111,25 @@ pub(crate) fn fact_body_shadows_callee_at_line( body_line: usize, ) -> bool { fact_body_defines_callee_fn(nested_fn_names, callee) - || fact_body_let_shadow_line(let_bindings, callee).is_some_and(|shadow| shadow <= body_line) + || fact_body_binding_shadows_at_line(let_bindings, callee, body_line) +} + +/// Whether a binding of `callee` is in scope at `body_line`: the binding +/// starts at its own line and ends at `scope_end` (inclusive), or at the end +/// of the function when `scope_end` is `None` (a `let`). +pub(crate) fn fact_body_binding_shadows_at_line( + let_bindings: &[LetBindingFact], + callee: &str, + body_line: usize, +) -> bool { + if callee.is_empty() { + return false; + } + let_bindings.iter().any(|binding| { + binding.name == callee + && binding.line <= body_line + && binding.scope_end.is_none_or(|end| body_line <= end) + }) } /// Whole-word identifier extraction over one binding pattern's text @@ -278,6 +304,94 @@ pub(crate) fn test_body_defines_callee_fn(body: &str, callee: &str) -> bool { pub(crate) fn body_shadows_callee_at_line(body: &str, callee: &str, body_line: usize) -> bool { test_body_defines_callee_fn(body, callee) || test_body_let_shadow_line(body, callee).is_some_and(|shadow| shadow <= body_line) + || test_body_scoped_shadow_at_line(body, callee) +} + +/// Lexical fallback for the scoped binding forms the parser facts cover +/// (#14508 review): a closure, `for`, match-arm, `if let`/`while let` or +/// nested-fn parameter that names `callee`. The lexical path is a +/// whole-body approximation like [`test_body_let_shadow_line`]: it withholds +/// credit for the whole body rather than computing the binding's exact +/// extent. That is the fail-closed direction (a genuine call after the scope +/// may lose credit on a file the parser could not read), and it keeps the +/// fallback from crediting a scoped binding as the owner. +pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool { + if callee.is_empty() { + return false; + } + // `for in ..` + if let Some(pattern) = between_keywords(body, "for ", " in ") + && pattern_contains_word(pattern, callee) + { + return true; + } + // `if let = ..` and `while let = ..` + for keyword in ["if let ", "while let "] { + if let Some(pattern) = between_keywords(body, keyword, " = ") + && pattern_contains_word(pattern, callee) + { + return true; + } + } + // `match .. { => .. }` + if let Some(open) = body.find("match ") { + if let Some(brace) = body[open..].find('{') { + let arms = &body[open + brace + 1..]; + // Only text before a `=>` is a pattern; the final segment is the + // last arm's body and must not be scanned as a pattern (#14508 + // review). + let mut rest = arms; + while let Some((pattern, after)) = rest.split_once("=>") { + let pattern = pattern.rsplit(['{', ',', ';']).next().unwrap_or(pattern); + if pattern_contains_word(pattern, callee) { + return true; + } + rest = after; + } + } + } + // `|| ..` + let mut search = 0usize; + while let Some(offset) = body[search..].find('|') { + let start = search + offset; + search = start + 1; + if body.as_bytes().get(start + 1) == Some(&b'|') { + search = start + 2; + continue; + } + let Some(end) = body[start + 1..].find('|') else { + break; + }; + let params = &body[start + 1..start + 1 + end]; + if pattern_contains_word(params, callee) { + return true; + } + search = start + 1 + end + 1; + } + // `fn (: T) ..` + let mut search = 0usize; + while let Some(offset) = body[search..].find("fn ") { + let start = search + offset; + search = start + 3; + let Some(open) = body[start..].find('(') else { + continue; + }; + let Some(close) = body[start + open..].find(')') else { + continue; + }; + let params = &body[start + open + 1..start + open + close]; + if pattern_contains_word(params, callee) { + return true; + } + } + false +} + +/// The text between the first `start` keyword and the next `end` keyword. +fn between_keywords<'a>(body: &'a str, start: &str, end: &str) -> Option<&'a str> { + let start = body.find(start)? + start.len(); + let end = body[start..].find(end)?; + Some(&body[start..start + end]) } /// Whole-word containment: `word` delimited by non-identifier characters on @@ -308,6 +422,7 @@ mod fact_authority_tests { fn binding(line: usize, name: &str) -> LetBindingFact { LetBindingFact { line, + scope_end: None, name: name.to_string(), } } @@ -442,4 +557,86 @@ mod fact_authority_tests { ); } } + + #[test] + fn scoped_shadow_ignores_a_genuine_call_in_the_last_match_arm() { + let body = "match v {\n Some(x) => helper(x),\n _ => owner(1)\n}\n"; + assert!( + !test_body_scoped_shadow_at_line(body, "owner"), + "the last arm's body is not a pattern; a genuine owner(..) call must not shadow" + ); + } + + #[test] + fn scoped_shadow_keeps_a_real_match_arm_binding() { + let body = "match v {\n Some(owner) => helper(x),\n _ => other(1)\n}\n"; + assert!( + test_body_scoped_shadow_at_line(body, "owner"), + "a real arm binding of owner must still shadow" + ); + } + + #[test] + fn scoped_shadow_table_covers_each_scanned_form() { + let cases = [ + ("for pattern", "for owner in items { use_it(); }", true), + ("for other", "for item in items { use_it(); }", false), + ( + "if let pattern", + "if let Some(owner) = value { use_it(); }", + true, + ), + ( + "if let other", + "if let Some(item) = value { use_it(); }", + false, + ), + ( + "while let pattern", + "while let Some(owner) = value { use_it(); }", + true, + ), + ( + "while let other", + "while let Some(item) = value { use_it(); }", + false, + ), + ("closure parameter", "let f = |owner| owner;", true), + ("closure other", "let f = |item| item;", false), + ("nested fn parameter", "fn helper(owner: i32) { }", true), + ("nested fn other", "fn helper(item: i32) { }", false), + ( + "match arm binding", + "match v { Some(owner) => helper(x), _ => other(1) }", + true, + ), + ( + "match arm other", + "match v { Some(item) => helper(x), _ => other(1) }", + false, + ), + ( + "last arm bare call", + "match v { Some(x) => helper(x), _ => owner(1) }", + false, + ), + ( + "last arm block call", + "match v { Some(x) => helper(x), _ => { owner(1) } }", + false, + ), + ( + "last arm binding", + "match v { Some(x) => helper(x), owner => owner(1) }", + true, + ), + ]; + for (label, body, expected) in cases { + assert_eq!( + test_body_scoped_shadow_at_line(body, "owner"), + expected, + "{label}: {body}" + ); + } + } } diff --git a/crates/ripr/src/analysis/facts/model.rs b/crates/ripr/src/analysis/facts/model.rs index f5918bf0359..a78a0172c2c 100644 --- a/crates/ripr/src/analysis/facts/model.rs +++ b/crates/ripr/src/analysis/facts/model.rs @@ -1080,10 +1080,17 @@ impl FunctionSourceRole { /// columns: a binding defeats uses at and after its own body-relative line. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct LetBindingFact { - /// 0-based line of the `let` token relative to the enclosing function's + /// 0-based line of the binding token relative to the enclosing function's /// body start (the same body-relative line math the lexical shadow /// scanners use). pub line: usize, + /// Last body-relative line where the binding is in scope (inclusive). + /// `None` for a `let` binding, which keeps the shipped end-of-function + /// over-approximation; `Some(end)` for a closure, `for`, match-arm, + /// `if let`/`while let` or nested-fn parameter, whose scope ends at its + /// body or arm (#14508 review). + #[serde(default)] + pub scope_end: Option, /// One whole-word identifier from the binding's pattern (`x` for /// `let mut x = ..`, `a` and `b` for `let (a, b) = ..`). Extracted with /// the lexical authority's whole-word semantics so the fact-derived and diff --git a/crates/ripr/src/analysis/syntax/ra.rs b/crates/ripr/src/analysis/syntax/ra.rs index 02c61c9b9b4..bfa4b3d4346 100644 --- a/crates/ripr/src/analysis/syntax/ra.rs +++ b/crates/ripr/src/analysis/syntax/ra.rs @@ -3,7 +3,7 @@ use crate::domain::{OracleKind, OracleStrength, SymbolId}; use ra_ap_syntax::Edition; use ra_ap_syntax::{ AstNode, SourceFile, SyntaxKind, SyntaxNode, TextSize, - ast::{self, HasAttrs, HasGenericArgs, HasGenericParams, HasModuleItem, HasName}, + ast::{self, HasAttrs, HasGenericArgs, HasGenericParams, HasLoopBody, HasModuleItem, HasName}, }; mod closure_callbacks; #[cfg(test)] @@ -1140,18 +1140,26 @@ fn simple_cfg_guard(attributes: &[String]) -> Option<(String, bool)> { /// Collects the parser-backed test-body shadow facts for one function /// (#3727 Slice A): the names of `fn` items nested inside the function's -/// body, and one [`LetBindingFact`] per whole-word name in every -/// initialized `let` binding's pattern, line-relative to the function's -/// `fn` keyword line. +/// body, and one [`LetBindingFact`] per whole-word name in a `let` pattern, +/// a nested `fn` name, and each closure, `for`, match-arm, +/// `if let`/`while let` or nested-`fn` parameter, line-relative to the +/// function's `fn` keyword line. /// -/// The semantics are deliberately scanner-equivalent at line granularity -/// (see `analysis::extract::shadow`): a nested `fn ` item is -/// hoisted and defeats the whole body, and a binding defeats uses at and -/// after its own body-relative line. No scope extents, no columns. The -/// pattern names are extracted with the shared lexical authority's -/// whole-word vocabulary (`extract_pattern_words`), so the fact-derived -/// decisions equal the lexical scanners' decisions on the same masked body -/// for realistic Rust — the equivalence battery in this module pins it. +/// A nested `fn ` item is hoisted and defeats the whole body. A +/// `let` binding carries `scope_end: None` and keeps the shipped +/// end-of-function over-approximation. A closure, `for`, match-arm, +/// `if let`/`while let` or nested-`fn` parameter carries `scope_end` with +/// the inclusive end line of its body or arm, so it defeats only uses inside +/// that scope. The pattern names are extracted with the shared lexical +/// authority's whole-word vocabulary (`extract_pattern_words`). +/// +/// The lexical fallback in `analysis::extract::shadow` deliberately diverges +/// for the scoped forms: it withholds the whole body rather than computing +/// the exact extent, which is fail-closed (it may drop credit for a genuine +/// call after the scope on a file the parser could not read, and never +/// grants credit to a scoped binding). The equivalence battery in this +/// module pins only the shared families (`let` bindings and nested `fn` +/// names), not the scoped forms. /// /// `line_of` maps a tree offset to a 1-based line, and `fn_line` is the /// 1-based line of the function's `fn` keyword — the two inputs that make @@ -1202,6 +1210,7 @@ fn collect_body_shadow_facts( for name in extract_pattern_words(&pattern.syntax().text().to_string()) { let_bindings.push(LetBindingFact { line: body_relative_line, + scope_end: None, name, }); } @@ -1264,16 +1273,175 @@ fn collect_body_shadow_facts( for name in extract_pattern_words(&pattern) { let_bindings.push(LetBindingFact { line: body_relative_line, + scope_end: None, name, }); } } } + // #14508 review: a closure, `for`, match-arm, `if let`/`while let` or + // nested-fn parameter binds the alias only inside its own body/arm. The + // fact carries that scope end so a genuine call after the scope keeps its + // credit. + for closure in function + .syntax() + .descendants() + .filter_map(ast::ClosureExpr::cast) + { + let Some(body) = closure.body() else { + continue; + }; + let scope_end = body.syntax().text_range().end(); + if let Some(params) = closure.param_list() { + for param in params.params() { + push_scoped_binding_facts( + &mut let_bindings, + param.pat(), + scope_end, + line_of, + fn_line, + ); + } + } + } + for for_expr in function + .syntax() + .descendants() + .filter_map(ast::ForExpr::cast) + { + let Some(body) = for_expr.loop_body() else { + continue; + }; + push_scoped_binding_facts( + &mut let_bindings, + for_expr.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + for arm in function + .syntax() + .descendants() + .filter_map(ast::MatchArm::cast) + { + let Some(expr) = arm.expr() else { + continue; + }; + push_scoped_binding_facts( + &mut let_bindings, + arm.pat(), + expr.syntax().text_range().end(), + line_of, + fn_line, + ); + } + for if_expr in function + .syntax() + .descendants() + .filter_map(ast::IfExpr::cast) + { + let Some(condition) = if_expr.condition() else { + continue; + }; + let Some(then_branch) = if_expr.then_branch() else { + continue; + }; + // A let-chain condition (`if let Some(dt) = .. && cond`) is a + // BinExpr, so walk every LetExpr under it, not only a direct + // condition (#14508 review). + for let_expr in condition + .syntax() + .descendants() + .filter_map(ast::LetExpr::cast) + { + push_scoped_binding_facts( + &mut let_bindings, + let_expr.pat(), + then_branch.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + for while_expr in function + .syntax() + .descendants() + .filter_map(ast::WhileExpr::cast) + { + let Some(condition) = while_expr.condition() else { + continue; + }; + let Some(body) = while_expr.loop_body() else { + continue; + }; + for let_expr in condition + .syntax() + .descendants() + .filter_map(ast::LetExpr::cast) + { + push_scoped_binding_facts( + &mut let_bindings, + let_expr.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + for nested_fn in function.syntax().descendants().filter_map(ast::Fn::cast) { + if nested_fn.syntax().text_range() == function.syntax().text_range() { + continue; + } + let Some(body) = nested_fn.body() else { + continue; + }; + if let Some(params) = nested_fn.param_list() { + for param in params.params() { + push_scoped_binding_facts( + &mut let_bindings, + param.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + } let_bindings.sort_by(|left, right| left.line.cmp(&right.line).then(left.name.cmp(&right.name))); let_bindings.dedup(); (nested_fn_names, let_bindings) } +/// Record one scoped binding fact per whole-word name in `pattern`, with the +/// binding's body-relative start line and the inclusive end line of the +/// body/arm that scopes it (#14508 review). +fn push_scoped_binding_facts( + let_bindings: &mut Vec, + pattern: Option, + scope_end: TextSize, + line_of: &impl Fn(TextSize) -> usize, + fn_line: usize, +) { + let Some(pattern) = pattern else { + return; + }; + let Some(start) = line_of(pattern.syntax().text_range().start()).checked_sub(fn_line) else { + return; + }; + let last = TextSize::from(u32::from(scope_end).saturating_sub(1)); + let Some(end) = line_of(last).checked_sub(fn_line) else { + return; + }; + for name in extract_pattern_words(&pattern.syntax().text().to_string()) { + let_bindings.push(LetBindingFact { + line: start, + scope_end: Some(end), + name, + }); + } +} + /// Parser-backed shadow facts (#3727 Slice A) for a bare body text that is /// not necessarily a `fn` item — harness-subject invocation spans and /// merged evidence bodies. The text is wrapped in a synthetic `fn` item @@ -5165,11 +5333,16 @@ mod nested { include!("nested.rs"); } #[cfg(test)] mod shadow_fact_equivalence_tests { - //! #3727 Slice A: the parser-produced body facts must decide the shared - //! shadow authority EXACTLY like the lexical scanners decide the same - //! masked body, so switching consumers between the two authorities - //! cannot move a verdict. The battery pins scanner equivalence over the - //! #3722/#3728 pin families plus the positional and same-line rules. + //! #3727 Slice A: the parser-produced body facts and the lexical + //! scanners must agree on the shared families — `let` bindings and + //! nested `fn` names — so switching consumers between the two + //! authorities cannot move a verdict for those forms. The battery pins + //! that shared-family equivalence over the #3722/#3728 pin families plus + //! the positional and same-line rules. It does not cover the scoped + //! forms (closure, `for`, match-arm, `if let`/`while let` and nested-`fn` + //! parameters): the parser carries their `scope_end` and credits a + //! genuine call after the scope, while the lexical fallback withholds the + //! whole body by design (see `analysis::extract::shadow`). use super::*; use crate::analysis::extract::{ diff --git a/crates/ripr/src/analysis/test_grip_evidence.rs b/crates/ripr/src/analysis/test_grip_evidence.rs index 6784234d2f9..c96cd16c93a 100644 --- a/crates/ripr/src/analysis/test_grip_evidence.rs +++ b/crates/ripr/src/analysis/test_grip_evidence.rs @@ -47,7 +47,7 @@ use related_tests::{ use super::classify::{ assertion_observes_collection_argument, assertion_observes_direct_collection_for_probe, assertion_pins_pushed_collection_count, call_text_may_call_free_function, - direct_collection_mutation_receiver, is_ignored, owner_call_text, + direct_collection_mutation_receiver, free_function_call_text, is_ignored, owner_call_text, predicate_line_arms_all_agree, reach_evidence as classify_reach_evidence, related_tests_reach_owner_indirectly, relation_establishes_reach, test_calls_free_function, test_count_pins_pushed_collection, test_counts_pushed_collection_argument, @@ -3223,12 +3223,30 @@ fn observed_value_facts_for_test( let value_facts = indexed.value_facts(index); let env = super::value_resolution::ValueEnv::new(seam, value_facts); for call in indexed.test.body_calls() { - if call.name != owner_name { + let is_alias = call.name != owner_name; + // The alias names a free function. An associated owner resolves its + // own calls through its type; a free alias of the same name must not + // lend it arguments (#14508 review). + if is_alias && owner_fn.impl_context != FunctionImplContext::Free { continue; } - let Some(args) = - owner_call_text(&call.text, owner_fn).and_then(|text| call_arguments(text, owner_name)) - else { + if is_alias && !context.is_direct_owner_alias(indexed, owner_name, &owner_fn.file, call) { + continue; + } + let call_name = if is_alias { + call.name.as_str() + } else { + owner_name + }; + let Some(args) = (if is_alias { + // The alias names a free function, so only a free-call spelling + // reaches it; `Rival::dt(..)` calls an associated function on + // another type and must not lend its arguments (#14508 review). + free_function_call_text(&call.text, call_name) + .and_then(|text| call_arguments(text, call_name)) + } else { + owner_call_text(&call.text, owner_fn).and_then(|text| call_arguments(text, call_name)) + }) else { continue; }; for (arg_index, arg) in args.into_iter().enumerate() { @@ -3782,12 +3800,30 @@ fn boundary_equality_overlap_score( let mut score = 0; for call in indexed.test.body_calls() { - if call.name != owner_fn.name { + let is_alias = call.name != owner_fn.name; + // The alias names a free function; an associated owner's boundary + // can only be closed by its own calls (#14508 review). + if is_alias && owner_fn.impl_context != FunctionImplContext::Free { continue; } - let Some(args) = owner_call_text(&call.text, owner_fn) - .and_then(|text| call_arguments(text, &owner_fn.name)) - else { + if is_alias && !context.is_direct_owner_alias(indexed, &owner_fn.name, &owner_fn.file, call) + { + continue; + } + let call_name = if is_alias { + call.name.as_str() + } else { + owner_fn.name.as_str() + }; + let Some(args) = (if is_alias { + // Same free-call authority as the observed-value loop: a + // qualified `Rival::dt(..)` is not the aliased free function + // (#14508 review). + free_function_call_text(&call.text, call_name) + .and_then(|text| call_arguments(text, call_name)) + } else { + owner_call_text(&call.text, owner_fn).and_then(|text| call_arguments(text, call_name)) + }) else { continue; }; let Some(left_arg) = args.get(left_operand.index) else { diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index a508253ef28..b536d487d79 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -4,7 +4,7 @@ use crate::analysis::classify::{ inherent_owner_call_resolves, method_call_resolves_to_impl, module_stem, owner_dispatch_trait, owner_impl_identity_shadowed, requires_inherent_receiver_identity, test_calls_free_function, }; -use crate::analysis::facts::FunctionImplContext; +use crate::analysis::facts::{FunctionImplContext, ModulePathTarget}; use std::sync::Arc; pub(super) mod context; @@ -150,6 +150,9 @@ pub(super) struct OwnerContext<'index> { inherent_owner: Option<&'index FunctionSummary>, /// The seam's owning function, for the shadowed-impl-identity refusal. function: Option<&'index FunctionSummary>, + /// The owner's file, for the compilation-unit identity check (#14508 + /// review). + file: Option<&'index Path>, impl_trait: Option, same_name_count: usize, identity: Option>, @@ -199,6 +202,7 @@ impl<'index> OwnerContext<'index> { inherent_receiver, inherent_owner: owner_fn.filter(|owner| requires_inherent_receiver_identity(owner)), function: owner_fn, + file: owner_file, impl_trait, same_name_count, identity, @@ -324,58 +328,359 @@ pub(super) fn match_direct_owner_call( if owner.name.is_empty() { return; } - let Some(indices) = context.tests_by_call_name.get(&owner.name) else { - return; - }; - for test_index in indices { - let Some(indexed) = context.tests.get(*test_index) else { - continue; - }; - if owner.inherent_receiver { - // Every inherent entry borrows the complete shared owner refusal, - // independently of the legacy impl-name ambiguity shortcut. - if !owner.inherent_owner.is_some_and(|function| { - inherent_owner_call_resolves(indexed.test, function, context.index) + if let Some(indices) = context.tests_by_call_name.get(&owner.name) { + for test_index in indices { + let Some(indexed) = context.tests.get(*test_index) else { + continue; + }; + if owner.inherent_receiver { + // Every inherent entry borrows the complete shared owner refusal, + // independently of the legacy impl-name ambiguity shortcut. + if !owner.inherent_owner.is_some_and(|function| { + inherent_owner_call_resolves(indexed.test, function, context.index) + }) { + continue; + } + } else if owner.same_name_count > 1 + && let Some(impl_type) = owner.impl_type.as_deref() + && !method_call_resolves_to_impl( + indexed.test, + &owner.name, + impl_type, + owner.impl_trait.as_deref(), + ) + { + continue; + } + // `ByteSize::kb(1)` or `size.kb()` never calls a free `kb` (#6713). + if owner.free_function + && !context + .tests + .get(*test_index) + .is_some_and(|indexed| test_calls_free_function(indexed.test, &owner.name)) + { + continue; + } + // A call spelled like a direct-owner import alias of another + // function binds to that import, not to a same-named local + // function in a sibling module (#14508 review). + if context.alias_spelling_binds_other_owner(indexed.test, &owner.name, &owner.name) { + continue; + } + // #11382: a test whose own scope rebinds the owner's impl type or + // trait calls the test-local item, not the production owner; the + // finding-level relation refuses the same call. Refusal only removes + // the direct-call credit, so this can only lower a relation. + if owner.function.is_some_and(|function| { + owner_impl_identity_shadowed(indexed.test, function, context.index) }) { continue; } - } else if owner.same_name_count > 1 - && let Some(impl_type) = owner.impl_type.as_deref() - && !method_call_resolves_to_impl( - indexed.test, - &owner.name, - impl_type, - owner.impl_trait.as_deref(), - ) - { - continue; + insert_related_candidate( + candidates, + context, + prefix, + *test_index, + RelationReason::DirectOwnerCall, + ); } - // `ByteSize::kb(1)` or `size.kb()` never calls a free `kb` (#6713). - if owner.free_function - && !context - .tests - .get(*test_index) - .is_some_and(|indexed| test_calls_free_function(indexed.test, &owner.name)) - { - continue; + } + // #14508: a test that imports the owner under an alias and calls the + // alias reaches the owner directly. The import's module path must name + // the owner's module: crate-relative for `crate::` imports, or the + // package-qualified path for an integration test's external import. + if owner.impl_type.is_none() + && !owner.inherent_receiver + && let Some(aliased) = context.tests_by_direct_owner_alias.get(&owner.name) + { + let owner_module = owner.module_path.as_deref().unwrap_or(""); + let owner_is_crate_root = owner.crate_root_file.is_some(); + for entry in aliased { + let Some(indexed) = context.tests.get(entry.test_index) else { + continue; + }; + let matches = direct_owner_alias_module_matches( + &entry.module_path, + entry.crate_relative, + owner_module, + owner_is_crate_root, + owner.crate_root_file.as_deref(), + indexed.test.file.as_path(), + owner.file, + owner.prefix.as_deref(), + context.index, + ); + if !matches { + continue; + } + // A local inline module of the alias's path shadows the import, so + // the call binds to that module, not to the owner (#14508 review). + if context.local_module_shadows_alias(indexed, &entry.module_path, &owner.name) { + continue; + } + // A local function of the alias's name shadows the import, so the + // call binds to it, not to the owner (#14508 review). + if context.local_function_shadows_call(indexed, &entry.alias, entry.module_depth) { + continue; + } + // A `let`/closure/parameter binding of the alias at the call line + // binds the call to that local value, not to the owner. + if context.alias_binding_shadows_call(indexed, &entry.alias, entry.call_line) { + continue; + } + if owner.function.is_some_and(|function| { + owner_impl_identity_shadowed(indexed.test, function, context.index) + }) { + continue; + } + insert_related_candidate( + candidates, + context, + prefix, + entry.test_index, + RelationReason::DirectOwnerCall, + ); } - // #11382: a test whose own scope rebinds the owner's impl type or - // trait calls the test-local item, not the production owner; the - // finding-level relation refuses the same call. Refusal only removes - // the direct-call credit, so this can only lower a relation. - if owner.function.is_some_and(|function| { - owner_impl_identity_shadowed(indexed.test, function, context.index) - }) { - continue; + } +} + +fn direct_owner_alias_module_matches( + alias_module: &str, + alias_crate_relative: bool, + owner_module: &str, + owner_is_crate_root: bool, + owner_crate_root: Option<&str>, + test_file: &Path, + owner_file: Option<&Path>, + owner_prefix: Option<&str>, + index: &RustIndex, +) -> bool { + // `src/pricing/mod.rs` names the `pricing` module, but + // `module_path_for_index` keeps the file stem (`pricing/mod`). Fold the + // `mod` leaf so a `mod.rs` owner matches its `crate::pricing` import + // (#14508 review). + let owner_module = owner_module.strip_suffix("/mod").unwrap_or(owner_module); + if alias_crate_relative { + // `crate::` resolves against the crate that compiles the test file. + // An integration test (`tests/...`) is its own crate, so its + // `crate::pricing` names `tests/pricing.rs`, never the library's + // `src/pricing.rs`; a unit test inside `src/` shares the library + // crate with the owner. Requiring compilation-unit identity before + // the equality check is what stops a test crate's own module from + // crediting the library owner (#14508 review). + if rust_index::is_test_file(test_file) { + return false; + } + let owner_package = owner_prefix.unwrap_or(""); + let Some(test_package) = package_scope(test_file) else { + return false; + }; + if test_package != owner_package { + return false; + } + // Package identity alone does not establish library-versus-binary + // compilation-unit identity: a package can hold both a library and a + // binary, and `crate::` in the binary names the binary's own modules + // (#14508 review). + if !crate_relative_alias_shares_compilation_unit( + test_file, + alias_module, + owner_file, + owner_is_crate_root, + owner_crate_root, + index, + ) { + return false; + } + if alias_module.is_empty() { + return owner_is_crate_root; + } + // The chain resolution above already compared the resolved file with + // the owner file; the index's module path for a binary target + // (`bin/pricing`) is not the crate-relative spelling (`pricing`). + return true; + } + // An external import names a package first: `subject::pricing`. Only the + // identifiers the test's crate uses for the owner's own library count; a + // sibling package's name must not credit this owner (#14508 review). + let owner_root = match owner_crate_root { + Some(root) => root.to_string(), + None => match owner_prefix { + Some(prefix) => format!("{prefix}src/lib.rs"), + None => "src/lib.rs".to_string(), + }, + }; + let import_names = index + .member_crates + .import_names(test_file, Path::new(&owner_root)); + let (package, rest) = match alias_module.split_once('/') { + Some((package, rest)) => (package, Some(rest)), + None => (alias_module, None), + }; + if !import_names.iter().any(|name| name == package) { + return false; + } + match rest { + None => owner_is_crate_root, + Some(rest) => rest.strip_suffix("/mod").unwrap_or(rest) == owner_module, + } +} + +/// Whether a `crate::`-relative alias in `test_file` can name `owner_file` +/// (#14508 review). `crate::` resolves against the crate that compiles the +/// test file, so package identity alone is not enough: a binary target is a +/// separate compilation unit from the library beside it. +/// +/// Two shapes are definite negatives: +/// - the test file is an established binary target root, so `crate::` names +/// that binary and never another crate root (the library root or a sibling +/// binary's root); +/// - the test file belongs to a `src/bin/` target, whose module tree is +/// confined to its own directory, so `crate::` never names a +/// library module. +/// +/// A binary root that reaches a *different* file for the same module name +/// through `#[path]` stays unresolved here; the inline-module shadow guard +/// covers the inline spelling. +fn crate_relative_alias_shares_compilation_unit( + test_file: &Path, + alias_module: &str, + owner_file: Option<&Path>, + owner_is_crate_root: bool, + owner_crate_root: Option<&str>, + index: &RustIndex, +) -> bool { + if index.member_crates.is_binary_target_root(test_file) { + let test_root = context::crate_root_file_key(test_file); + if owner_is_crate_root && owner_crate_root != test_root.as_deref() { + return false; + } + } + if alias_module.is_empty() { + return true; + } + let Some(owner_file) = owner_file else { + return false; + }; + let Some(root_file) = crate_root_file_for_test(index, test_file) else { + return false; + }; + resolve_module_chain(index, &root_file, alias_module) + .is_some_and(|resolved| normalize_path(&resolved) == normalize_path(owner_file)) +} + +/// The crate root file that compiles `test_file` (#14508 review). A binary +/// target root is the file itself; a module inside a `src/bin/` target +/// resolves from that target's `main.rs` or flat `.rs`; a library or +/// binary module under `src/` resolves from `src/lib.rs` or `src/main.rs`. +fn crate_root_file_for_test(index: &RustIndex, test_file: &Path) -> Option { + if index.member_crates.is_binary_target_root(test_file) { + return Some(test_file.to_path_buf()); + } + if let Some(bin_dir) = binary_target_module_dir(test_file) { + let normalized = normalize_path(test_file); + if normalized == format!("{bin_dir}.rs") || normalized == format!("{bin_dir}/main.rs") { + return Some(test_file.to_path_buf()); + } + let main = PathBuf::from(format!("{bin_dir}/main.rs")); + if index_has_file(index, &main) { + return Some(main); + } + let flat = PathBuf::from(format!("{bin_dir}.rs")); + if index_has_file(index, &flat) { + return Some(flat); + } + return None; + } + let prefix = package_prefix(test_file).unwrap_or_default(); + let lib = PathBuf::from(format!("{prefix}src/lib.rs")); + if index_has_file(index, &lib) { + return Some(lib); + } + let main = PathBuf::from(format!("{prefix}src/main.rs")); + if index_has_file(index, &main) { + return Some(main); + } + None +} + +/// Resolve a slash-separated `crate::` chain from `root_file` the way rustc +/// does, following each declaration's `#[path]` target. A missing declaration +/// or a non-literal `#[path]` fails closed (#14508 review). +fn resolve_module_chain(index: &RustIndex, root_file: &Path, module_path: &str) -> Option { + let mut current = root_file.to_path_buf(); + for segment in module_path.split('/') { + let facts = index.files().get(¤t)?; + let declaration = facts + .module_declarations + .iter() + .find(|declaration| declaration.name == segment)?; + let dir = current.parent()?; + current = match &declaration.path_target { + ModulePathTarget::Default => { + let file = dir.join(format!("{segment}.rs")); + let mod_file = dir.join(segment).join("mod.rs"); + let file_exists = index_has_file(index, &file); + let mod_exists = index_has_file(index, &mod_file); + match (file_exists, mod_exists) { + (true, false) => file, + (false, true) => mod_file, + _ => return None, + } + } + ModulePathTarget::Literal(path) => { + let resolved = dir.join(path); + if index_has_file(index, &resolved) { + resolved + } else { + return None; + } + } + ModulePathTarget::Unknown => return None, + }; + } + Some(current) +} + +fn index_has_file(index: &RustIndex, path: &Path) -> bool { + let normalized = normalize_path(path); + index + .files() + .iter() + .any(|(key, _)| normalize_path(key) == normalized) +} + +/// The `src/bin/` directory a test file belongs to, when it sits in a +/// binary target's module tree (#14508 review). `src/bin/.rs`, +/// `src/bin//main.rs` and `src/bin//.rs` all name +/// `src/bin/`. +fn binary_target_module_dir(test_file: &Path) -> Option { + let normalized = normalize_path(test_file); + let at = normalized.find("src/bin/")?; + if at > 0 && !normalized[..at].ends_with('/') { + return None; + } + let after = &normalized[at + "src/bin/".len()..]; + let first = after.split('/').next()?; + let name = first.strip_suffix(".rs").unwrap_or(first); + (!name.is_empty()).then(|| format!("{}src/bin/{name}", &normalized[..at])) +} + +/// The module path a test file's own items sit under, for comparing an inline +/// module chain with an absolute `crate::` path (#14508 review). A crate root +/// names no module: `lib.rs`, `main.rs`, and a `src/bin` target root. +fn test_file_module_path(index: &RustIndex, file: &Path) -> String { + if module_stem(file).is_none() { + return String::new(); + } + if let Some(bin_dir) = binary_target_module_dir(file) { + let normalized = normalize_path(file); + if normalized == format!("{bin_dir}.rs") || normalized == format!("{bin_dir}/main.rs") { + return String::new(); } - insert_related_candidate( - candidates, - context, - prefix, - *test_index, - RelationReason::DirectOwnerCall, - ); } + let path = module_path_for_index(index, file).unwrap_or_default(); + path.strip_suffix("/mod").unwrap_or(&path).to_string() } pub(super) fn match_helper_owner_call( diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs index 11bf43c899b..14b3cd4bb82 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs @@ -12,6 +12,18 @@ pub(crate) struct CompactGripContext<'a> { pub(in crate::analysis::test_grip_evidence) index: &'a RustIndex, pub(in crate::analysis::test_grip_evidence) tests: Vec>, pub(in crate::analysis::test_grip_evidence) tests_by_call_name: BTreeMap>, + /// Tests whose call is spelled through a direct import alias of a + /// production function: imported name -> the test, the import's module + /// path (slash-separated), whether that path is `crate::`-relative, the + /// alias spelling and the call line. A relative path resolves against + /// the test's own crate; a package-qualified one names the owner's + /// package (#14508). + pub(in crate::analysis::test_grip_evidence) tests_by_direct_owner_alias: + BTreeMap>, + /// Per test file: start lines of every indexed non-test function, keyed by + /// name, so the alias shadow guard can tell a same-module declaration + /// from a sibling module's (#14508 review). + local_function_starts_by_file: BTreeMap>>, pub(in crate::analysis::test_grip_evidence) tests_by_helper_owner_call_name: BTreeMap>, /// Tests whose helper chain reaches the owner name through a @@ -110,6 +122,22 @@ pub(crate) struct CompactGripContext<'a> { pin_syntax: crate::analysis::classify::OwnerPinSyntax, } +/// One alias-spelled call of a directly imported owner (#14508). +#[derive(Clone, Debug, Eq, PartialEq)] +pub(in crate::analysis::test_grip_evidence) struct DirectOwnerAliasEntry { + pub(in crate::analysis::test_grip_evidence) test_index: usize, + /// Slash-separated module segments of the import. + pub(in crate::analysis::test_grip_evidence) module_path: String, + /// The import was written `crate::`-relative. + pub(in crate::analysis::test_grip_evidence) crate_relative: bool, + pub(in crate::analysis::test_grip_evidence) alias: String, + pub(in crate::analysis::test_grip_evidence) call_line: usize, + /// Number of enclosing `mod` scopes at the import, so the local-function + /// shadow guard can tell an enclosing declaration from a nearer one + /// (#14508 review). + pub(in crate::analysis::test_grip_evidence) module_depth: usize, +} + /// Candidate generation only: the existing `contains` and `same_module` /// predicates remain the authority for admitting relations. #[derive(Default)] @@ -283,6 +311,228 @@ impl<'a> CompactGripContext<'a> { &self.pin_syntax } + /// Whether `test` reaches `owner_name` through the alias spelling + /// `call.name` at `call.line` (#14508). The table lookup is + /// allocation-free; on a lexical-fallback file the binding check masks + /// the body per alias call, so this is not a constant-time query there. + /// + /// The table stores one row per resolved call line, so the row's own + /// identity is the authority: the row must name this exact call line and + /// its import module must name the owner's module. A nested + /// `use rival::different_function as dt` binds a later `dt(..)` to another + /// function, and a same-named import of another module must not borrow an + /// outer owner row's credit (#14508 review). + pub(in crate::analysis::test_grip_evidence) fn is_direct_owner_alias( + &self, + test: &CompactTest<'_>, + owner_name: &str, + owner_file: &Path, + call: &CallFact, + ) -> bool { + let Some(entries) = self.tests_by_direct_owner_alias.get(owner_name) else { + return false; + }; + // An imported alias is a local name, so only a bare `alias(..)` + // spelling binds to it. A same-line `rival::alias(..)` names that + // module's function and must not borrow the row (#14508 review). + if !crate::analysis::classify::call_text_spells_bare_free_call(&call.text, &call.name) { + return false; + } + // The shadow guards are expensive and only decide a call that is + // already spelled like one of this owner's aliases at this line, so + // find the matching entry first and run them once for that call + // (#14508 review). + let Some(matched) = entries.iter().find(|entry| { + entry.alias == call.name + && entry.call_line == call.line + && self + .tests + .get(entry.test_index) + .is_some_and(|indexed| std::ptr::eq(indexed.test, test.test)) + }) else { + return false; + }; + if self.alias_binding_shadows_call(test, &call.name, call.line) + || self.local_function_shadows_call(test, &call.name, matched.module_depth) + { + return false; + } + let owner_module = super::module_path_for_index(self.index, owner_file); + let owner_module = owner_module.as_deref().unwrap_or(""); + let file_stem = module_stem(owner_file).unwrap_or_default(); + let owner_crate_root = if file_stem.is_empty() { + crate_root_file_key(owner_file) + } else { + None + }; + let owner_is_crate_root = owner_crate_root.is_some(); + let owner_prefix = super::package_prefix(owner_file); + entries.iter().any(|entry| { + entry.alias == call.name + && entry.call_line == call.line + && self + .tests + .get(entry.test_index) + .is_some_and(|indexed| std::ptr::eq(indexed.test, test.test)) + && !self.local_module_shadows_alias(test, &entry.module_path, owner_name) + && super::direct_owner_alias_module_matches( + &entry.module_path, + entry.crate_relative, + owner_module, + owner_is_crate_root, + owner_crate_root.as_deref(), + test.test.file.as_path(), + Some(owner_file), + owner_prefix.as_deref(), + self.index, + ) + }) + } + + /// Whether a `let`, nested `fn` name, closure parameter, `for`/match-arm/ + /// `if let`/`while let` pattern, or nested-fn parameter named `call_name` + /// encloses the call at `call_line`, so the alias-spelled call binds to + /// that local value rather than to the imported owner (#14508 review). A + /// `let` keeps the end-of-function over-approximation; the other forms are + /// bounded by their body or arm. + pub(in crate::analysis::test_grip_evidence) fn alias_binding_shadows_call( + &self, + test: &CompactTest<'_>, + call_name: &str, + call_line: usize, + ) -> bool { + let body_line = call_line.saturating_sub(test.test.start_line); + let lexical = self + .index + .files() + .get(&test.test.file) + .is_some_and(|facts| facts.used_lexical_fallback); + if lexical { + let masked = crate::analysis::extract::mask_comments_and_strings(&test.test.body); + crate::analysis::extract::ShadowAuthority::LexicalMaskedBody + .body_shadows_callee_at_line(&masked, call_name, body_line) + } else { + crate::analysis::extract::ShadowAuthority::ParserBodyFacts { + nested_fn_names: &test.test.nested_fn_names, + let_bindings: &test.test.let_bindings, + } + .body_shadows_callee_at_line("", call_name, body_line) + } + } + + /// Whether `test`'s own module or a nearer module than the import + /// declares a non-test function named `call_name`, so an alias-spelled + /// call in that scope binds to the local function rather than to the + /// directly imported owner (#14508 review). A declaration in an enclosing + /// module than the import is shadowed by the import, and a sibling inline + /// module's same-named function is a different name scope. + pub(in crate::analysis::test_grip_evidence) fn local_function_shadows_call( + &self, + test: &CompactTest<'_>, + call_name: &str, + use_module_depth: usize, + ) -> bool { + let Some(starts) = self.local_function_starts_by_file.get(&test.test.file) else { + return false; + }; + let Some(lines) = starts.get(call_name) else { + return false; + }; + let Some(facts) = self.index.files().get(&test.test.file) else { + // Without the source the module scopes cannot be read; fall back + // to the file-wide answer (fail closed toward withholding). + return true; + }; + let scopes = crate::analysis::classify::module_scopes(&facts.source); + lines.iter().any(|line| { + scopes.declaration_shadows_import(*line, use_module_depth, test.test.start_line) + }) + } + + /// Whether the test file declares an inline module chain that matches the + /// alias's module path and defines the imported name, so the `crate::` + /// path names that local module rather than the owner file (#14508 + /// review). A binary target's inline `mod pricing { fn owner }` is a + /// different compilation unit from the library's `src/pricing.rs`, and + /// the import binds to the local module. + pub(in crate::analysis::test_grip_evidence) fn local_module_shadows_alias( + &self, + test: &CompactTest<'_>, + alias_module: &str, + imported_name: &str, + ) -> bool { + let Some(starts) = self.local_function_starts_by_file.get(&test.test.file) else { + return false; + }; + let Some(lines) = starts.get(imported_name) else { + return false; + }; + let Some(facts) = self.index.files().get(&test.test.file) else { + return false; + }; + // The alias path is absolute from the crate root, so the local + // module's absolute path is the test file's own module path plus the + // inline chain. + let file_module = super::test_file_module_path(self.index, &test.test.file); + let mut wanted: Vec<&str> = file_module + .split('/') + .filter(|segment| !segment.is_empty()) + .collect(); + wanted.extend( + alias_module + .split('/') + .filter(|segment| !segment.is_empty()), + ); + if wanted.is_empty() { + return false; + } + let scopes = crate::analysis::classify::module_scopes(&facts.source); + lines.iter().any(|line| { + scopes + .module_chain_at(*line) + .is_some_and(|chain| chain == wanted) + }) + } + + /// Whether every call of `call_name` in `test` is bound to a direct-owner + /// import alias of a *different* function, so a same-named local function + /// is not the callee (#14508 review). A test that also spells a genuine + /// local call of the name keeps the generic direct-call credit. + pub(in crate::analysis::test_grip_evidence) fn alias_spelling_binds_other_owner( + &self, + test: &TestSummary, + call_name: &str, + owner_name: &str, + ) -> bool { + let mut alias_lines = BTreeSet::new(); + for (imported_name, entries) in &self.tests_by_direct_owner_alias { + if imported_name == owner_name { + continue; + } + for entry in entries { + if entry.alias == call_name + && self + .tests + .get(entry.test_index) + .is_some_and(|indexed| std::ptr::eq(indexed.test, test)) + { + alias_lines.insert(entry.call_line); + } + } + } + if alias_lines.is_empty() { + return false; + } + let mut saw_call = false; + for call in test.calls.iter().filter(|call| call.name == call_name) { + saw_call = true; + if !alias_lines.contains(&call.line) { + return false; + } + } + saw_call + } + /// Pay the whole-index macro-site scan once, before the seam workers /// start, so it fans out over the pool instead of running in line on /// the first worker that needs it while the others wait (#9211). @@ -325,6 +575,8 @@ impl<'a> CompactGripContext<'a> { ) -> Result { checkpoint()?; let mut tests_by_call_name: BTreeMap> = BTreeMap::new(); + let mut tests_by_direct_owner_alias: BTreeMap> = + BTreeMap::new(); let mut tests_by_helper_owner_call_name: BTreeMap> = BTreeMap::new(); let mut tests_by_free_helper_owner_call_name: BTreeMap> = BTreeMap::new(); @@ -378,6 +630,10 @@ impl<'a> CompactGripContext<'a> { context_build_phase("direct_helper_import_aliases_by_file", || { direct_helper_import_aliases_by_file(index, &helper_owner_calls_by_module_path) }); + let direct_owner_import_aliases_by_file = + context_build_phase("direct_owner_import_aliases_by_file", || { + direct_owner_import_aliases_by_file(index) + }); checkpoint()?; let production_helper_owner_calls_by_package = context_build_phase("production_helper_owner_calls_by_package", || { @@ -403,6 +659,7 @@ impl<'a> CompactGripContext<'a> { checkpoint()?; let SharedIndexTables { function_names_by_file, + local_function_starts_by_file, module_import_aliases_by_file, unambiguous_production_owner_names_by_package, .. @@ -463,6 +720,35 @@ impl<'a> CompactGripContext<'a> { .iter() .map(|call| call.name.clone()) .collect::>(); + if let Some(owner_aliases) = direct_owner_import_aliases_by_file.get(&test.file) { + for call in &test.calls { + // The alias names a free function and only the bare + // `alias(..)` spelling binds to the import. A qualified + // `rival::dt(..)` names that module's function even + // when the module name is lowercase (#14508 review). + if !crate::analysis::classify::call_text_spells_bare_free_call( + &call.text, &call.name, + ) { + continue; + } + if let Some(binding) = owner_aliases + .get(&call.name) + .and_then(|alias| alias.binding_at(call.line)) + { + tests_by_direct_owner_alias + .entry(binding.name.clone()) + .or_default() + .push(DirectOwnerAliasEntry { + test_index, + module_path: binding.module_path.clone(), + crate_relative: binding.crate_relative, + alias: call.name.clone(), + call_line: call.line, + module_depth: binding.module_depth, + }); + } + } + } let mut assertion_tokens = BTreeSet::new(); for assertion in &test.assertions { for token in extract_identifier_tokens(&assertion.text) { @@ -639,6 +925,8 @@ impl<'a> CompactGripContext<'a> { index, tests, tests_by_call_name, + tests_by_direct_owner_alias, + local_function_starts_by_file, tests_by_helper_owner_call_name, tests_by_free_helper_owner_call_name, tests_by_target_affinity_owner_call_name, @@ -1404,10 +1692,17 @@ impl ScopedModuleImportAlias { #[derive(Clone, Debug, Eq, PartialEq)] pub(in crate::analysis::test_grip_evidence) struct ScopedImportedFunctionBinding { + /// Slash-separated module segments (`pricing/inner`), never `::`. pub(in crate::analysis::test_grip_evidence) module_path: String, + /// The import was written `crate::`-relative, so it resolves against the + /// crate that compiles the test file, not the owner's package (#14508 + /// review). + pub(in crate::analysis::test_grip_evidence) crate_relative: bool, pub(in crate::analysis::test_grip_evidence) name: String, start_line: usize, end_line: usize, + /// Number of enclosing `mod` scopes at the import (#14508 review). + module_depth: usize, /// Lines inside nested module bodies are not covered by this import. nested_module_lines: Vec<(usize, usize)>, /// The owning scope closes part-way through `end_line`, with code after @@ -1595,6 +1890,7 @@ pub(in crate::analysis::test_grip_evidence) fn free_spelling_target_affinity_own /// four rescans of every source's `use` statements per context. pub(in crate::analysis::test_grip_evidence) struct SharedIndexTables { function_names_by_file: BTreeMap>, + local_function_starts_by_file: BTreeMap>>, module_import_aliases_by_file: ModuleImportAliasesByFile, direct_function_import_aliases_by_file: ScopedDirectFunctionImportAliasesByFile, unambiguous_production_owner_names_by_package: ProductionOwnerNamesByPackage, @@ -1616,6 +1912,7 @@ impl SharedIndexTables { || { ( local_function_names_by_file(index), + local_function_starts_by_file(index), unambiguous_production_owner_names_by_package(index), production_owner_names_by_module_path(index), production_owner_names_by_package_and_module_path(index), @@ -1625,6 +1922,7 @@ impl SharedIndexTables { ); let ( function_names_by_file, + local_function_starts_by_file, unambiguous_production_owner_names_by_package, owner_names_by_module_path, owner_names_by_package_and_module_path, @@ -1632,6 +1930,7 @@ impl SharedIndexTables { ) = rest; Self { function_names_by_file, + local_function_starts_by_file, module_import_aliases_by_file, direct_function_import_aliases_by_file, unambiguous_production_owner_names_by_package, @@ -2738,9 +3037,11 @@ pub(in crate::analysis::test_grip_evidence) fn direct_function_import_aliases( .bindings .push(ScopedImportedFunctionBinding { module_path: imported.module_path, + crate_relative: true, name: imported.name, start_line: statement.start_line, end_line, + module_depth: statement.module_depth, nested_module_lines: nested_module_lines.clone(), end_is_partial: scan.end_is_partial(end_line), }); @@ -2935,6 +3236,165 @@ pub(in crate::analysis::test_grip_evidence) fn normalize_module_import_path( Some(path.to_string()) } +/// Normalize the module path of a direct function import for the owner-alias +/// table (#14508). Unlike [`normalize_module_import_path`], this accepts an +/// external package path (`subject::pricing`) as well as a crate-relative one +/// (`crate::pricing`), because an integration test imports the library by its +/// package name. `crate` alone is the crate root (empty path). +/// +/// Segments are normalized to `/` on both sides of the comparison: the +/// owner's module path comes from `module_path_for_index`, which joins with +/// `/`, while the import is written with `::`. Without one representation a +/// nested owner (`pricing/inner`) never matched its `crate::pricing::inner` +/// import (#14508 review). +fn normalize_direct_owner_module_path(path: &str) -> Option { + let path = path.trim(); + if path == "crate" { + return Some(OwnerModulePath { + module_path: String::new(), + crate_relative: true, + }); + } + if let Some(rest) = path.strip_prefix("crate::") { + let rest = rest.trim(); + return (!rest.is_empty()).then(|| OwnerModulePath { + module_path: rest.replace("::", "/"), + crate_relative: true, + }); + } + if path.is_empty() + || path.starts_with("self::") + || path.starts_with("super::") + || path.starts_with("::") + { + return None; + } + Some(OwnerModulePath { + module_path: path.replace("::", "/"), + crate_relative: false, + }) +} + +/// A direct-owner import's module path, normalized to `/` segments, plus +/// whether it was written `crate::`-relative (#14508 review). +#[derive(Clone, Debug, Eq, PartialEq)] +struct OwnerModulePath { + module_path: String, + crate_relative: bool, +} + +/// An imported owner function alias before it is scoped to a call line. +#[derive(Clone, Debug, Eq, PartialEq)] +struct OwnerImportedFunctionAlias { + module_path: String, + crate_relative: bool, + name: String, +} + +fn collect_direct_owner_import_aliases_from_use( + import: &str, +) -> Option> { + let import = import.trim_end_matches(';').trim(); + let mut aliases = BTreeMap::new(); + if let Some((base, rest)) = import.split_once("::{") { + let module = normalize_direct_owner_module_path(base)?; + let body = rest.strip_suffix('}')?; + for item in body.split(',').map(str::trim) { + if item.contains("::") || item.contains('{') || item.contains('}') { + continue; + } + collect_owner_function_alias(item, &module, &mut aliases); + } + return Some(aliases); + } + let (module_path, item) = import.rsplit_once("::")?; + let module = normalize_direct_owner_module_path(module_path)?; + collect_owner_function_alias(item.trim(), &module, &mut aliases); + Some(aliases) +} + +fn collect_owner_function_alias( + item: &str, + module: &OwnerModulePath, + aliases: &mut BTreeMap, +) { + let mut parsed = BTreeMap::new(); + collect_direct_function_import_alias(item, &module.module_path, &mut parsed); + for (alias, imported) in parsed { + aliases.insert( + alias, + OwnerImportedFunctionAlias { + module_path: imported.module_path, + crate_relative: module.crate_relative, + name: imported.name, + }, + ); + } +} + +/// Scoped direct-import aliases for the owner-call relation (#14508). This is +/// the same shape as [`direct_function_import_aliases`] but accepts external +/// package paths, so `use subject::owner as alias;` resolves as well as +/// `use crate::owner as alias;`. +pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases( + source: &str, +) -> BTreeMap { + let scan = scan_lexical_use_statements(source); + let mut aliases: BTreeMap = BTreeMap::new(); + for statement in &scan.statements { + let Some(parsed) = collect_direct_owner_import_aliases_from_use(&statement.text) else { + continue; + }; + if parsed.is_empty() { + continue; + } + let end_line = scan.end_line(statement); + let mut nested_module_lines = nested_module_line_ranges( + &scan.line_module_depths, + statement.start_line, + end_line, + statement.module_depth, + ); + for line in &scan.module_open_lines { + if statement.start_line <= *line && *line <= end_line { + nested_module_lines.push((*line, *line)); + } + } + for (alias, imported) in parsed { + aliases + .entry(alias) + .or_insert_with(|| ScopedImportedFunctionAlias { + bindings: Vec::new(), + }) + .bindings + .push(ScopedImportedFunctionBinding { + module_path: imported.module_path, + crate_relative: imported.crate_relative, + name: imported.name, + start_line: statement.start_line, + end_line, + module_depth: statement.module_depth, + nested_module_lines: nested_module_lines.clone(), + end_is_partial: scan.end_is_partial(end_line), + }); + } + } + aliases +} + +pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases_by_file( + index: &RustIndex, +) -> ScopedDirectFunctionImportAliasesByFile { + index + .files() + .iter() + .filter_map(|(file, facts)| { + let aliases = direct_owner_import_aliases(&facts.source); + (!aliases.is_empty()).then_some((file.clone(), aliases)) + }) + .collect() +} + pub(in crate::analysis::test_grip_evidence) fn unambiguous_production_owner_names_by_package( index: &RustIndex, ) -> ProductionOwnerNamesByPackage { @@ -2986,6 +3446,32 @@ pub(in crate::analysis::test_grip_evidence) fn local_function_names_by_file( names_by_file } +/// Per test file: the start lines of every indexed non-test function, keyed +/// by name. The alias shadow guard needs the declaration's line to tell a +/// same-module (or enclosing-module) function from a sibling module's +/// same-named one (#14508 review). +pub(in crate::analysis::test_grip_evidence) fn local_function_starts_by_file( + index: &RustIndex, +) -> BTreeMap>> { + let mut starts_by_file: BTreeMap>> = BTreeMap::new(); + let actual_tests = actual_test_keys(index); + for function in index.functions().iter().filter(|function| { + !actual_tests.contains(&ActualTestKey { + file: &function.file, + name: &function.name, + start_line: function.start_line, + }) + }) { + starts_by_file + .entry(function.file.clone()) + .or_default() + .entry(function.name.clone()) + .or_default() + .push(function.start_line); + } + starts_by_file +} + /// Borrowed (file, name, start_line) identity of a function that is an /// actual executable test (`TestFact` member), so graph-admission lookups /// need no per-function key clones. #3273 widened the function diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 85b33d50ac8..983d6035a46 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -22955,6 +22955,1084 @@ fn given_integration_test_when_bare_import_names_other_module_then_owner_keeps_r Ok(()) } +#[test] +fn given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508: both the crate-relative and the external package spelling of a + // direct import alias must resolve to the owner. The external case needs a + // real manifest so the owner's own package is the only import name that + // counts (#14508 review). + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let crate_src = format!( + "{prod_src}\n#[cfg(test)]\nmod tests {{\n use crate::discounted_total as dt;\n\n #[test]\n fn aliased() {{\n assert_eq!(dt(100, 100), 90);\n }}\n}}\n" + ); + let crate_root = alias_workspace_root("lib_proptest")?; + fs::write(crate_root.join("src/lib.rs"), crate_src).map_err(|error| error.to_string())?; + let crate_files = [PathBuf::from("src/lib.rs")]; + let crate_index = build_index(&crate_root, &crate_files)?; + let crate_seams = inventory_seams_from_index(&crate_files, &crate_index); + let crate_seam = crate_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let crate_related: Vec = evidence_for_seam(crate_seam, &crate_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert_eq!( + crate_related, + vec!["aliased".to_string()], + "use crate::discounted_total as dt;" + ); + + let external_root = alias_workspace_root("lib_proptest")?; + fs::write(external_root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write( + external_root.join("tests/boundary.rs"), + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn aliased() {\n assert_eq!(dt(100, 100), 90);\n}\n", + ) + .map_err(|error| error.to_string())?; + let external_files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let external_index = build_index(&external_root, &external_files)?; + let external_seams = + inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &external_index); + let external_seam = external_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let external_related: Vec = evidence_for_seam(external_seam, &external_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert_eq!( + external_related, + vec!["aliased".to_string()], + "use lib_proptest::discounted_total as dt;" + ); + Ok(()) +} + +fn alias_workspace_root(package: &str) -> Result { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_nanos(); + let root = claim_index_fixture_root(stamp)?; + fs::create_dir_all(root.join("src")).map_err(|error| error.to_string())?; + fs::create_dir_all(root.join("tests")).map_err(|error| error.to_string())?; + fs::write( + root.join("Cargo.toml"), + format!("[package]\nname = \"{package}\"\nversion = \"0.1.0\"\n"), + ) + .map_err(|error| error.to_string())?; + Ok(root) +} + +#[test] +fn given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: the test file declares its own `dt`, so the alias-spelled + // call binds to this local function; the owner must not be credited. + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn shadowed() {\n fn dt(_amount: i32, _threshold: i32) -> i32 { 777 }\n assert_eq!(dt(100, 100), 777);\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + let related: Vec = evidence + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert!( + related.is_empty(), + "a local function shadowing the import alias must not credit the owner: {related:?}" + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value() +-> Result<(), String> { + // #14508 review: the alias names the free owner. A free `dt(7, 7)` must + // not lend its arguments to a same-named associated owner. + let lib_src = "pub struct Rival;\n\nimpl Rival {\n pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { 777 } else { 7 } }\n}\n\npub fn discounted_total(amount: i32, _threshold: i32) -> i32 { amount + 1 }\n\n#[cfg(test)]\nmod tests {\n use crate::discounted_total as dt;\n use crate::Rival;\n\n #[test]\n fn mixed() {\n assert_eq!(Rival::discounted_total(100, 100), 777);\n assert_eq!(dt(7, 7), 8);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib_src)])?; + let evidence = evidence_for_alias_seam(&root, &[PathBuf::from("src/lib.rs")], "src/lib.rs")?; + let values: Vec<&str> = evidence + .observed_values + .iter() + .map(|fact| fact.value.as_str()) + .collect(); + assert!( + !values.contains(&"7"), + "the free alias call must not lend its argument to the associated owner: {values:?}" + ); + assert!( + values.contains(&"100"), + "the associated call's argument is the associated owner's activation value: {values:?}" + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // #14508 review: a test may call the owner through the alias and also + // spell `rival::dt(..)` on a lowercase module, which the free-call reader + // otherwise accepts. The relation still credits the owner through the bare + // alias, but the qualified call's arguments must not become its values. + let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let rival_src = "pub fn discounted_total(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\nuse lib_proptest::rival;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n assert_eq!(rival::dt(7, 7), 777);\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("src/rival.rs"), rival_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/rival.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "the free alias call still credits the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a qualified `Rival::dt(..)` must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the free alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a test in package A that imports package B's function + // under an alias must not credit package A's own same-named owner, even + // when both packages are indexed. + let negative = two_package_workspace("pkg_b")?; + let negative_files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("pkg_a/src/lib.rs"), + PathBuf::from("pkg_a/tests/control.rs"), + ]; + let negative_index = build_index(&negative, &negative_files)?; + let negative_seams = + inventory_seams_from_index(&[PathBuf::from("pkg_a/src/lib.rs")], &negative_index); + let negative_seam = negative_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let negative_related: Vec = evidence_for_seam(negative_seam, &negative_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert!( + negative_related.is_empty(), + "a sibling package's alias must not credit pkg_a's owner: {negative_related:?}" + ); + + let positive = two_package_workspace("pkg_a")?; + let positive_files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("pkg_a/src/lib.rs"), + PathBuf::from("pkg_a/tests/control.rs"), + ]; + let positive_index = build_index(&positive, &positive_files)?; + let positive_seams = + inventory_seams_from_index(&[PathBuf::from("pkg_a/src/lib.rs")], &positive_index); + let positive_seam = positive_seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let positive_related: Vec = evidence_for_seam(positive_seam, &positive_index) + .related_tests + .iter() + .map(|test| test.test_name.clone()) + .collect(); + assert_eq!( + positive_related, + vec!["aliased".to_string()], + "the owner's own package alias must still credit it" + ); + Ok(()) +} + +fn two_package_workspace(alias_package: &str) -> Result { + let stamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|error| error.to_string())? + .as_nanos(); + let root = claim_index_fixture_root(stamp)?; + for dir in ["src", "pkg_a/src", "pkg_a/tests"] { + fs::create_dir_all(root.join(dir)).map_err(|error| error.to_string())?; + } + // The root package is `pkg_b`, so `index.package_names` names the sibling + // package; the old all-packages check credited `pkg_a`'s owner for it. + fs::write( + root.join("Cargo.toml"), + "[package]\nname = \"pkg_b\"\nversion = \"0.1.0\"\n\n[workspace]\nmembers = [\"pkg_a\"]\nresolver = \"2\"\n", + ) + .map_err(|error| error.to_string())?; + fs::write( + root.join("pkg_a/Cargo.toml"), + "[package]\nname = \"pkg_a\"\nversion = \"0.1.0\"\n\n[dependencies]\npkg_b = { path = \"..\" }\n", + ) + .map_err(|error| error.to_string())?; + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("pkg_a/src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write( + root.join("pkg_a/tests/control.rs"), + format!( + "use {alias_package}::discounted_total as dt;\n\n#[test]\nfn aliased() {{\n assert_eq!(dt(100, 100), 90);\n}}\n" + ), + ) + .map_err(|error| error.to_string())?; + Ok(root) +} + +#[test] +fn given_direct_owner_alias_when_a_block_binding_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // #14508 review: a block-scoped `let dt = |..| 999;` beside a genuine + // `dt(100, 100)` must not lend the owner the closure's argument. + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n {\n let dt = |a: i32, b: i32| { let _ = (a, b); 999 };\n assert_eq!(dt(7, 7), 999);\n }\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "the genuine alias call still credits the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a block-scoped closure binding must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let f = |dt: fn(i32, i32) -> i32| dt(7, 7);\n assert_eq!(f(|a, b| a + b), 14);\n}\n", + "closure parameter", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_for_pattern_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n for dt in [|a: i32, b: i32| a + b] {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + "for pattern", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_match_arm_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let x = |a: i32, b: i32| a + b;\n match x {\n dt => assert_eq!(dt(7, 7), 14),\n };\n}\n", + "match arm", + ) +} + +#[test] +fn given_direct_owner_alias_when_an_if_let_pattern_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n if let Some(dt) = Some(|a: i32, b: i32| a + b) {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + "if let pattern", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_fn_parameter_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n fn helper(dt: fn(i32, i32) -> i32) -> i32 {\n dt(7, 7)\n }\n assert_eq!(helper(|a, b| a + b), 14);\n}\n", + "nested fn parameter", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n let f = |dt: fn(i32, i32) -> i32| dt(7, 7);\n assert_eq!(f(|a, b| a + b), 14);\n assert_eq!(dt(100, 100), 90);\n}\n", + "closure parameter after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_for_pattern_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n for dt in [|a: i32, b: i32| a + b] {\n assert_eq!(dt(7, 7), 14);\n }\n assert_eq!(dt(100, 100), 90);\n}\n", + "for pattern after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_match_arm_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n let x = |a: i32, b: i32| a + b;\n match x {\n dt => assert_eq!(dt(7, 7), 14),\n };\n assert_eq!(dt(100, 100), 90);\n}\n", + "match arm after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_an_if_let_pattern_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n if let Some(dt) = Some(|a: i32, b: i32| a + b) {\n assert_eq!(dt(7, 7), 14);\n }\n assert_eq!(dt(100, 100), 90);\n}\n", + "if let pattern after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_fn_parameter_shadows_it_then_a_later_genuine_call_keeps_credit() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n fn helper(dt: fn(i32, i32) -> i32) -> i32 {\n dt(7, 7)\n }\n assert_eq!(helper(|a, b| a + b), 14);\n assert_eq!(dt(100, 100), 90);\n}\n", + "nested fn parameter after scope", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_let_chain_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n if let Some(dt) = Some(|a: i32, b: i32| a + b) && 1 > 0 {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + "let-chain", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_while_let_chain_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + assert_scoped_alias_shadow( + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n while let Some(dt) = Some(|a: i32, b: i32| a + b) && 1 > 0 {\n assert_eq!(dt(7, 7), 14);\n break;\n }\n}\n", + "while-let-chain", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_let_chain_is_the_only_call_then_owner_gets_no_related_test() +-> Result<(), String> { + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write( + root.join("tests/boundary.rs"), + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn only_shadowed() {\n if let Some(dt) = Some(|a: i32, b: i32| a + b) && 1 > 0 {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + ) + .map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence.related_tests.is_empty(), + "a let-chain-only shadowed call must not credit the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a let-chain-only shadowed call must not lend the owner its argument: {:?}", + evidence.observed_values + ); + Ok(()) +} + +fn assert_scoped_alias_shadow(tests_src: &str, label: &str) -> Result<(), String> { + let prod_src = "pub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "{label}: the genuine alias call must still credit the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "{label}: a scoped binding must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "{label}: the genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_nested_import_shadows_it_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // #14508 review: one test can hold an outer owner-bound `dt(100, 101)` + // and an inner `use rival::different_function as dt` whose `dt(7, 7)` + // binds to the rival. The inner call must not borrow the outer alias + // row's authority: neither its arguments as observed values nor its + // equal operands as boundary overlap. + let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let rival_src = "pub fn different_function(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 101), 100);\n {\n use lib_proptest::rival::different_function as dt;\n assert_eq!(dt(7, 7), 777);\n }\n}\n"; + let root = alias_workspace_root("lib_proptest")?; + fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; + fs::write(root.join("src/rival.rs"), rival_src).map_err(|error| error.to_string())?; + fs::write(root.join("tests/boundary.rs"), tests_src).map_err(|error| error.to_string())?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/rival.rs"), + PathBuf::from("tests/boundary.rs"), + ]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&[PathBuf::from("src/lib.rs")], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(seam, &index); + assert!( + evidence + .related_tests + .iter() + .any(|test| test.test_name == "mixed"), + "the outer genuine alias call still credits the owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a nested import-bound `dt(..)` must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the outer genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + assert!( + evidence + .missing_discriminators + .iter() + .any(|fact| fact.value.contains("threshold")), + "the nested equal-operand call must not close the boundary-equality gap: {:?}", + evidence.missing_discriminators + ); + Ok(()) +} + +/// Build an `alias_workspace_root` and write every `(path, source)` into it. +fn alias_workspace_with_files( + package: &str, + files: &[(&str, &str)], +) -> Result { + let root = alias_workspace_root(package)?; + for (path, source) in files { + let full = root.join(path); + if let Some(parent) = full.parent() { + fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + fs::write(full, source).map_err(|error| error.to_string())?; + } + Ok(root) +} + +fn evidence_for_alias_seam( + root: &Path, + files: &[PathBuf], + seam_file: &str, +) -> Result { + let index = build_index(root, files)?; + let seams = inventory_seams_from_index(&[PathBuf::from(seam_file)], &index); + let seam = seams + .iter() + .find(|seam| seam.kind() == SeamKind::PredicateBoundary) + .ok_or_else(|| "expected predicate boundary seam".to_string())?; + Ok(evidence_for_seam(seam, &index)) +} + +/// The related tests the direct-owner-alias relation credited. Proximity +/// strategies (`AssertionTargetAffinity`) may also relate a test; those are +/// not the authority this repair reads. +fn direct_owner_call_tests(evidence: &TestGripEvidence) -> Vec<&str> { + evidence + .related_tests + .iter() + .filter(|test| test.relation_reason == RelationReason::DirectOwnerCall) + .map(|test| test.test_name.as_str()) + .collect() +} + +#[test] +fn given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `crate::pricing` in an integration test names the test + // crate's own `tests/pricing.rs`, not the library's `src/pricing.rs`. + // The rival call must not credit the library owner; the genuine + // package-qualified alias beside it still must. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let rival = "pub fn owner(amount: i32) -> i32 { amount }\n"; + let control = "mod pricing;\n\nuse crate::pricing::owner as rival_dt;\nuse lib_proptest::pricing::owner as genuine_dt;\n\n#[test]\nfn rival() {\n assert_eq!(rival_dt(100), 100);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(genuine_dt(100), 90);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", library), + ("tests/pricing.rs", rival), + ("tests/control.rs", control), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing.rs"), + PathBuf::from("tests/pricing.rs"), + PathBuf::from("tests/control.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["genuine"], + "a test crate's own `crate::pricing` module must not credit the library owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the genuine alias call's argument is the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a package with both a library and a binary. The binary's + // inline `mod pricing` is a different compilation unit from the library's + // `src/pricing.rs`, so `crate::pricing::owner` in `src/main.rs` binds to + // the binary's own function. The library unit test beside it still must + // credit the owner, and the rival's argument must not become an observed + // value. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::owner as dt;\n\n #[test]\n fn library_unit_test() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let binary = "mod pricing {\n pub fn owner(amount: i32) -> i32 {\n amount\n }\n}\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_local_rival() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", library), + ("src/main.rs", binary), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing.rs"), + PathBuf::from("src/main.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["library_unit_test"], + "a binary's inline `mod pricing` must not credit the library owner: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the binary rival's argument must not become an observed value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `crate::` in `src/main.rs` names the binary crate, so it + // can never name the library root `src/lib.rs`. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "use crate::owner as dt;\n\n#[test]\nfn binary_root_rival() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[("src/lib.rs", library), ("src/main.rs", binary)], + )?; + let files = [PathBuf::from("src/lib.rs"), PathBuf::from("src/main.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a binary root's `crate::owner` must not credit the library root: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the binary rival's argument must not become an observed value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a `src/bin/` target's module tree is confined to + // its own directory, so `crate::pricing` there never names the library's + // `src/pricing.rs`. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "use crate::pricing::owner as dt;\n\n#[test]\nfn bin_target_rival() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", library), + ("src/bin/cli.rs", binary), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing.rs"), + PathBuf::from("src/bin/cli.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a `src/bin` target's `crate::pricing` must not credit the library module: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review control: with no library target, `mod pricing;` in + // `src/main.rs` resolves to `src/pricing.rs`, so the crate-relative alias + // is a genuine direct owner call and must keep its credit. + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn bin_genuine() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "bin_only", + &[("src/main.rs", binary), ("src/pricing.rs", pricing)], + )?; + let files = [ + PathBuf::from("src/main.rs"), + PathBuf::from("src/pricing.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["bin_genuine"], + "a bin-only package's own module is the owner: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `#[path = "binary_pricing.rs"]` makes the binary's + // `crate::pricing` name `src/binary_pricing.rs`, not the library's + // `src/pricing.rs`, so the alias must fail closed. + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "#[path = \"binary_pricing.rs\"]\nmod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_redirected() {\n assert_eq!(dt(7), 7);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", owner), + ("src/main.rs", binary), + ("src/binary_pricing.rs", owner), + ], + )?; + let files = [ + "src/lib.rs", + "src/pricing.rs", + "src/main.rs", + "src/binary_pricing.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty() + && evidence + .observed_values + .iter() + .all(|fact| fact.value != "7") + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_an_intermediate_segment_redirects_with_path_then_owner_gets_no_related_test() +-> Result<(), String> { + // `mod pricing` is redirected to `other_pricing.rs`, so + // `crate::pricing::inner` does not name `src/pricing/inner.rs`. + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let lib = "#[path = \"other_pricing.rs\"]\npub mod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn redirected() {\n assert_eq!(dt(7), 7);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + ("src/pricing/inner.rs", owner), + ("src/other_pricing.rs", "pub mod inner;\n"), + ( + "src/other_pricing/inner.rs", + "pub fn owner(amount: i32) -> i32 { amount }\n", + ), + ], + )?; + let files = [ + "src/lib.rs", + "src/pricing/inner.rs", + "src/other_pricing.rs", + "src/other_pricing/inner.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/inner.rs")?; + assert!(direct_owner_call_tests(&evidence).is_empty()); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_flat_bin_root_imports_its_sibling_module_then_owner_keeps_related_test() +-> Result<(), String> { + let cargo = "[package]\nname = \"lib_proptest\"\nversion = \"0.1.0\"\nedition = \"2021\"\nautobins = false\n\n[[bin]]\nname = \"cli\"\npath = \"src/bin/cli.rs\"\n"; + let cli = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_genuine_flat() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("Cargo.toml", cargo), + ("src/bin/cli.rs", cli), + ("src/bin/pricing.rs", pricing), + ], + )?; + let files = ["src/bin/cli.rs", "src/bin/pricing.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/bin/pricing.rs")?; + assert_eq!( + direct_owner_call_tests(&evidence), + vec!["binary_genuine_flat"] + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_directory_bin_root_imports_its_own_module_then_owner_keeps_related_test() +-> Result<(), String> { + let cargo = "[package]\nname = \"lib_proptest\"\nversion = \"0.1.0\"\nedition = \"2021\"\nautobins = false\n\n[[bin]]\nname = \"cli\"\npath = \"src/bin/cli/main.rs\"\n"; + let main = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn binary_genuine_dir() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("Cargo.toml", cargo), + ("src/bin/cli/main.rs", main), + ("src/bin/cli/pricing.rs", pricing), + ], + )?; + let files = ["src/bin/cli/main.rs", "src/bin/cli/pricing.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/bin/cli/pricing.rs")?; + assert_eq!( + direct_owner_call_tests(&evidence), + vec!["binary_genuine_dir"] + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_lib_and_bin_share_the_module_then_owner_keeps_related_test() +-> Result<(), String> { + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "mod pricing;\n\nuse crate::pricing::owner as dt;\n\n#[test]\nfn bin_genuine() {\n assert_eq!(dt(100), 90);\n}\n\nfn main() {}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing.rs", owner), + ("src/main.rs", binary), + ], + )?; + let files = ["src/lib.rs", "src/pricing.rs", "src/main.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["bin_genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: the alias table stores the import with `::` while the + // owner's module path comes from the index with `/`; the nested owner + // (`pricing/inner`) must still resolve its `crate::pricing::inner` import. + let inner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let lib = "pub mod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn aliased_from_root() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + ("src/pricing/mod.rs", "pub mod inner;\n"), + ("src/pricing/inner.rs", inner), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing/mod.rs"), + PathBuf::from("src/pricing/inner.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/inner.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!(related, vec!["aliased", "aliased_from_root"]); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: `src/pricing/mod.rs` is the `pricing` module, whose + // import is `crate::pricing`; the index's file-stem path (`pricing/mod`) + // must fold the `mod` leaf. + let pricing = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", "pub mod pricing;\n"), + ("src/pricing/mod.rs", pricing), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing/mod.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/mod.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!(related, vec!["aliased"]); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: inline modules have separate name scopes. `dt` in + // `mod unrelated` cannot bind the `dt(..)` call in `mod tests`, so the + // import alias still reaches the owner. + let lib = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\nmod unrelated {\n pub fn dt(_amount: i32) -> i32 { 0 }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib)])?; + let files = [PathBuf::from("src/lib.rs")]; + let index = build_index(&root, &files)?; + let seams = inventory_seams_from_index(&files, &index); + let owner_seam = seams + .iter() + .find(|seam| { + seam.owner() == "src/lib.rs::owner" && seam.kind() == SeamKind::PredicateBoundary + }) + .ok_or_else(|| "expected the owner's predicate boundary seam".to_string())?; + let evidence = evidence_for_seam(owner_seam, &index); + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["aliased"], + "a sibling module's `dt` is a different name scope: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + // The sibling function is not the callee: the test's `dt(..)` binds to + // the imported owner, so the sibling must not be credited (#14508 + // review). + let sibling_seam = seams + .iter() + .find(|seam| seam.owner() == "src/lib.rs::unrelated::dt") + .ok_or_else(|| "expected the sibling module's seam".to_string())?; + let sibling_evidence = evidence_for_seam(sibling_seam, &index); + assert!( + direct_owner_call_tests(&sibling_evidence).is_empty(), + "the sibling module's `dt` must not be credited: {:?}", + sibling_evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review, mirror-image control for the enclosing-module case: the + // `use` is at the crate root and `fn dt` is inside `mod tests`, so the + // innermost binding is the local function and the import must not credit + // the owner. The shape compiles (the two `dt` items are in different + // modules). + let lib = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\nuse crate::owner as dt;\n\n#[cfg(test)]\nmod tests {\n fn dt(_amount: i32) -> i32 { 0 }\n\n #[test]\n fn shadowed() {\n assert_eq!(dt(100), 0);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib)])?; + let files = [PathBuf::from("src/lib.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a same-module `dt` must shadow the import alias: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_an_enclosing_module_declares_the_alias_name_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: the `use` inside `mod tests` shadows the crate-root + // `fn dt`, so the call binds to the import and the owner is credited. + let lib = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\nfn dt(_amount: i32) -> i32 { 0 }\n\n#[cfg(test)]\nmod tests {\n use crate::owner as dt;\n\n #[test]\n fn aliased_owner_is_reached() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files("lib_proptest", &[("src/lib.rs", lib)])?; + let files = [PathBuf::from("src/lib.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + let related = direct_owner_call_tests(&evidence); + assert_eq!( + related, + vec!["aliased_owner_is_reached"], + "an inner use shadows the enclosing fn: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100") + ); + Ok(()) +} + #[test] fn given_integration_test_when_rival_nested_in_another_module_then_owner_gets_no_related_test() -> Result<(), String> { diff --git a/docs/spec-index.d/RIPR-SPEC-0442.md b/docs/spec-index.d/RIPR-SPEC-0442.md new file mode 100644 index 00000000000..89a9d3c336c --- /dev/null +++ b/docs/spec-index.d/RIPR-SPEC-0442.md @@ -0,0 +1 @@ +| [RIPR-SPEC-0442](../specs/RIPR-SPEC-0442-aliased-owner-import-credit.md) | accepted | An aliased owner import credits the owner as a direct call only when the import names the owner's module in the same compilation unit; same-module, sibling-module, other-crate, binary and lexical bindings are refused (#14508) | diff --git a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md new file mode 100644 index 00000000000..9b21ff4757a --- /dev/null +++ b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md @@ -0,0 +1,159 @@ +# RIPR-SPEC-0442: An aliased owner import credits the owner only when the import names its module in the same compilation unit + +Status: accepted + +Owner: product / analysis + +Created: 2026-11-13 + +Linked issues: #14508 (an aliased direct import of the owner is not credited, +and naive name matching over-credits a test crate's own module); #14016 (the +selective control for test-local rival imports). + +Linked PRs: #14513 + +Support-tier impact: + +- No tier change. The change decides which existing `direct_owner_call` + relation a test already-spelled call earns; it adds no grip class, + `static_limit_kind` value or exposure class. Claim boundaries remain + governed by [support tiers](../status/SUPPORT_TIERS.md). + +Policy impact: + +- Register this spec in `policy/doc-artifacts.d/RIPR-SPEC-0442.toml` and + `.ripr/traceability.d/RIPR-SPEC-0442.toml`. +- No schema or JSON field change. The judged repo-exposure fields stay + `grip_class`, `evidence.reach`, `related_tests[].relation_reason` and + `observed_values`. + +## Problem + +A test that writes `use crate::pricing::discounted_total as dt;` and calls +`dt(100, 100)` reaches the owner, but no spec stated that the alias credits +it. The owner module path joined segments with `/` while the import used +`::`, so a nested owner stayed `activation_unknown`; and a test crate's own +`crate::pricing` resolved to `tests/pricing.rs` yet a bare module-name +comparison credited the library's `src/pricing.rs::owner`. A same-named local +binding, a sibling inline module and an enclosing-module declaration were the +other edges; the guard compares the import's module depth with the +declaration's module chain. + +## Behavior + +### Credit + +A direct import of the owner's function under an alias credits the owner as +`direct_owner_call` when both hold: + +1. The import names the owner's module in the same compilation unit. A unit + test may use `use crate::::owner as dt;` (or `use crate::owner as + dt;` for the crate root); an integration test uses the owner's package + qualification, `use ::::owner as dt;`, and the package + must be the one the test's crate imports the owner's library by. +2. The call's spelling binds to that import at the call line: no nearer + lexical `use`, local function, `let`, closure parameter, + `for`/match-arm/`if let`/`while let` pattern or nested-`fn` parameter of + the same spelling is in scope. + +Both sides of the module comparison use one `/`-segment representation. +`src/pricing/mod.rs` names the `pricing` module; a crate root has the empty +path. + +### Refusal + +The alias does not credit the owner when: + +- A `crate::` import appears in an integration test (`tests/...`), which + names the test crate's own modules, or in a binary target, which names the + binary. +- The import names another package, a sibling package, or another + compilation unit than the owner's. +- In a binary target root, the alias chain's first segment is declared with a + non-default `#[path]` or is not declared at all. +- A local function of the alias's name is declared in the import's own + module or a nested module (at least as deep as the import) and in the + call's module chain, or a lexical binding of the name is in scope at the + call. A declaration in an enclosing module is shadowed by the import, and a + sibling inline module is a different name scope: neither withholds the + alias, and the sibling does not itself receive the alias credit. + +A test that also spells a genuine local call of the alias name keeps the +generic direct-call credit for that call; only the alias-shaped calls are +routed to the import. + +### Scope + +The rule decides `related_tests[].relation_reason` in the seam-grip and +repo-exposure paths. It does not add a reach edge by itself: the stages still +read the test's assertions and the owner's body. + +## Required Evidence + +- An aliased unit-test call credits the owner with `direct_owner_call` and + the observed argument. +- An integration test's genuine package-qualified alias credits the owner; + the same test crate's own `crate::` module does not. +- A nested owner (`src/pricing/inner.rs`) and a `mod.rs` owner + (`src/pricing/mod.rs`) credit their `crate::` imports. +- A same-named local function in the import's module or a nested module, or + a lexical binding, withholds the owner; an enclosing-module declaration is + shadowed by the import and keeps credit; a later genuine alias call keeps + credit. +- A sibling inline module's same-named function neither shadows the alias + nor receives the alias credit. +- Only a bare `alias(..)` spelling binds to the import: a same-line + `rival::alias(..)` on a lowercase module names that module's function and + lends the owner no argument. +- A free alias of the owner's name lends no argument to a same-named + associated owner; the associated owner keeps only its own calls' values. + +## Non-Goals + +- Grouped (`use a::{b as c}`), chained (`use a::b as c; use c::d;`) and + renamed module aliases (`use a as b;`). +- The diff-mode `ripr check` relation path, which is a separate gap. +- Trait or impl alias credit; the alias must name a free function. +- In a lib+bin package whose binary root declares the module with the default + path, the binary's `crate::` compiles the same source file as the + library owner, and the alias still credits the library owner. Tracked in + #14558. + +## Acceptance Examples + +1. `src/pricing.rs::owner`, `tests/control.rs` with its own `mod pricing;` + and `use crate::pricing::owner as dt; assert_eq!(dt(100), 100);`: the + library owner stays `activation_unknown`; the call does not credit it. +2. `src/pricing/inner.rs::owner`, a unit test with + `use crate::pricing::inner::owner as dt; assert_eq!(dt(100), 90);`: + `direct_owner_call`, observed `["100"]`. +3. `src/lib.rs::owner` with a genuine `use crate::owner as dt;` beside + `mod unrelated { pub fn dt(..) { .. } }`: the real owner is credited; + `src/lib.rs::unrelated::dt` is not credited as a direct owner call. + +## Test Mapping + +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test` +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test` +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test` +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_owner_takes_no_value_from_it`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it` +- `fixtures/evidence-promotion-honesty-corpus/corpus.json` `report_digest_required` + report fixtures `rust-repo-exposure-alias-crate` and + `rust-repo-exposure-alias-external` + +## Implementation Mapping + +- `crates/ripr/src/analysis/test_grip_evidence/related_tests.rs`: + `match_direct_owner_call`, `direct_owner_alias_module_matches`, + `crate_relative_alias_shares_compilation_unit`. +- `crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs`: + `direct_owner_import_aliases`, `normalize_direct_owner_module_path`, + `local_function_shadows_call`, `alias_binding_shadows_call`, + `alias_spelling_binds_other_owner`, `local_module_shadows_alias`. +- `crates/ripr/src/analysis/classify/const_flow.rs`: + `ModuleScopes::declaration_shadows_import`. + +## Metrics + +- `unit_test_pass_rate` +- `corpus_case_pass_rate` diff --git a/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json b/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json new file mode 100644 index 00000000000..50b7b1b9c62 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json @@ -0,0 +1,26 @@ +{ + "id": "rust_test_local_rival_import_alias_crate", + "language": "rust", + "tier": "pure", + "source_report": "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json", + "report_subject": "fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate", + "vector": "crate_alias_of_the_owner_resolves_to_direct_owner_call", + "assertions": [ + { + "type": "expected_repo_seam_grip", + "owner": "src/lib.rs::discounted_total", + "expression": "amount >= threshold", + "grip_class": "strongly_gripped", + "reach": "yes" + }, + { + "type": "expected_repo_seam_related_test", + "owner": "src/lib.rs::discounted_total", + "expression": "amount >= threshold", + "test": "aliased_owner_boundary", + "file": "src/lib.rs", + "oracle_strength": "strong", + "relation_reason": "direct_owner_call" + } + ] +} diff --git a/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json b/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json new file mode 100644 index 00000000000..30aec1df41c --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json @@ -0,0 +1,26 @@ +{ + "id": "rust_test_local_rival_import_alias_external", + "language": "rust", + "tier": "pure", + "source_report": "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json", + "report_subject": "fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external", + "vector": "external_alias_of_the_owner_resolves_to_direct_owner_call", + "assertions": [ + { + "type": "expected_repo_seam_grip", + "owner": "src/lib.rs::discounted_total", + "expression": "amount >= threshold", + "grip_class": "strongly_gripped", + "reach": "yes" + }, + { + "type": "expected_repo_seam_related_test", + "owner": "src/lib.rs::discounted_total", + "expression": "amount >= threshold", + "test": "aliased_owner_boundary", + "file": "tests/control.rs", + "oracle_strength": "strong", + "relation_reason": "direct_owner_call" + } + ] +} diff --git a/fixtures/evidence-promotion-honesty-corpus/corpus.json b/fixtures/evidence-promotion-honesty-corpus/corpus.json index 90fcd7c9b7a..648c688e63e 100644 --- a/fixtures/evidence-promotion-honesty-corpus/corpus.json +++ b/fixtures/evidence-promotion-honesty-corpus/corpus.json @@ -262,7 +262,9 @@ "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-panic-marker-neutral.json", "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-test-local-rival-bare-use.json", "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-test-local-rival-glob-use.json", - "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-wrapper-fed-error.json" + "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-wrapper-fed-error.json", + "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json", + "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json" ], "cases": [ { diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml new file mode 100644 index 00000000000..a5bd9510bf8 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "test_local_rival_import_alias_crate_subject" +version = "0.0.0" +edition = "2024" + +[lib] +name = "test_local_rival_import_alias_crate_subject" +path = "src/lib.rs" + +[workspace] diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs new file mode 100644 index 00000000000..7d694fba3c9 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs @@ -0,0 +1,17 @@ +pub fn discounted_total(amount: i32, threshold: i32) -> i32 { + if amount >= threshold { + amount - 10 + } else { + amount + } +} + +#[cfg(test)] +mod tests { + use crate::discounted_total as dt; + + #[test] + fn aliased_owner_boundary() { + assert_eq!(dt(100, 100), 90); + } +} diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml new file mode 100644 index 00000000000..7ccb9c715c5 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "test_local_rival_import_alias_external_subject" +version = "0.0.0" +edition = "2024" + +[lib] +name = "test_local_rival_import_alias_external_subject" +path = "src/lib.rs" + +[workspace] diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs new file mode 100644 index 00000000000..1ca671a5aa6 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs @@ -0,0 +1,7 @@ +pub fn discounted_total(amount: i32, threshold: i32) -> i32 { + if amount >= threshold { + amount - 10 + } else { + amount + } +} diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs new file mode 100644 index 00000000000..47547a48527 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs @@ -0,0 +1,6 @@ +use test_local_rival_import_alias_external_subject::discounted_total as dt; + +#[test] +fn aliased_owner_boundary() { + assert_eq!(dt(100, 100), 90); +} diff --git a/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json b/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json new file mode 100644 index 00000000000..9ba9f80351a --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json @@ -0,0 +1,52 @@ +{ + "schema_version": "0.5", + "artifact": {"analysis":{"base_revision":null,"command":"ripr check --format repo-exposure-json","format":"repo-exposure-json","input_identity":"input:v4:fnv1a64:9e844298a0b1f5fd","mode":"draft","profile":"draft","worktree":"unavailable"},"canonicalization":"raw_json_placeholder_v1","content_sha256":"sha256:77769302427300f8b486534a246eaeaa32969fa90baef390ab4dc5690aba17a9","generated_at":"unix_ms:1794584393247","kind":"repo_exposure","producer":{"tool":"ripr","version":"0.11.0"},"repository":{"head":"unavailable","root":"/tmp/test-local-rival-import-alias-crate"},"schema_version":"1","snapshot_identity":"snapshot:input:v4:fnv1a64:9e844298a0b1f5fd;revision:unavailable"}, + "source_subject": {"corpus":{"analyzed_production_files":["src/lib.rs"],"cache_schema_version":"1.181","files_content_hash":"b2e0a0abcf9113f5","scope":"rust_workspace"},"digest_algorithm":"sha256","files":[{"digest":"sha256:b1d83c56f9241e5abb3ab4cc8ad96dee54c9c4a16e5ae8f78ea0bd68735c747c","path":"src/lib.rs"}]}, + "analysis_inputs": {"analyzer_version":"0.11.0+83da5a7577113f588ce17ffddc9fe2bcaa852ea6-dirty+src:a34ee991b0f684e9+languages:rust=1,typescript=1,python=1,perl=0","cfg_features_hash":"cbf29ce484222325","config_hash":"881255e2f498d9f2","lockfile_hash":"0b74165b4cea4f09","suppressions_hash":"cbf29ce484222325","test_intent_hash":"cbf29ce484222325","toolchain_hash":"833996a486514c49","workspace_manifests_hash":"9b4f3c6dd797bb62"}, + "scope": "repo", + "run_status": "complete", + "metrics": { + "seams_total": 1, + "headline_eligible": 0, + "strongly_gripped": 1, + "weakly_gripped": 0, + "ungripped": 0, + "reachable_unrevealed": 0, + "activation_unknown": 0, + "propagation_unknown": 0, + "observation_unknown": 0, + "discrimination_unknown": 0, + "opaque": 0, + "intentional": 0, + "suppressed": 0 + }, + "seams": [ + { + "seam_id": "67f9714ba37b3967", + "kind": "predicate_boundary", + "file": "src/lib.rs", + "line": 2, + "column": 8, + "end_line": 2, + "end_column": 27, + "owner": "src/lib.rs::discounted_total", + "expression": "amount >= threshold", + "grip_class": "strongly_gripped", + "headline_eligible": false, + "evidence": { + "reach": "yes", + "activate": "yes", + "propagate": "yes", + "observe": "yes", + "discriminate": "yes" + }, + "related_tests_total": 1, + "related_tests": [ + {"name": "aliased_owner_boundary", "file": "src/lib.rs", "line": 14, "oracle_kind": "exact_value", "oracle_strength": "strong", "evidence_summary": "exact value assertion", "relation_reason": "direct_owner_call", "relation_confidence": "high"} + ], + "observed_values": ["100"], + "missing_discriminators": [], + "evidence_record": {"actionability":{"class":"not_policy_relevant","has_concrete_guidance":false,"reason":"seam is already gripped or intentionally non-actionable under current policy","signals":{"assertion_shape":false,"candidate_value":true,"missing_discriminator":false,"recommended_test_target":true,"related_test":true,"verification_command":false}},"calibration":{"agreement":"no_runtime_data","availability":"not_imported","confidence":"unknown"},"canonical_gap_group_size":null,"canonical_gap_id":null,"canonical_gap_reason":null,"canonical_item":{"actionability":"already_observed","canonical_gap_id":null,"canonical_item_kind":"observed","command_specs":{"receipt":null,"verify":null},"confidence":{"basis":"static_only","notes":["no imported runtime calibration data"]},"evidence_class":"predicate_boundary","gap_state":"already_observed","group_reason":null,"primary_anchor":{"file":"src/lib.rs","kind":"strongly_gripped","line":2,"reason":"record_location","source_id":"67f9714ba37b3967"},"raw_group_size":1,"raw_spans":[{"end_line":2,"file":"src/lib.rs","kind":"strongly_gripped","source_id":"67f9714ba37b3967","start_line":2}],"receipt_command":null,"recommended_repair":"No new RIPR action; current static evidence already observes this seam.","related_test":{"file":"src/lib.rs","line":14,"name":"aliased_owner_boundary","reason":"direct_owner_call"},"repair_command":null,"repair_route":null,"static_limitations":[],"verify_command":null,"why":"seam is already gripped or intentionally non-actionable under current policy"},"evidence_path":{"activate":{"confidence":"medium","state":"yes","summary":"Observed 1 concrete activation value(s) for seam `amount >= threshold`"},"discriminate":{"confidence":"medium","state":"yes","summary":"Strongest oracle for seam kind `predicate_boundary` is `strong` (kind-match true)"},"observe":{"confidence":"medium","state":"yes","summary":"Observation evidence is `yes`"},"propagate":{"confidence":"low","state":"yes","summary":"Static propagation to `return_value` sink is yes"},"reach":{"confidence":"medium","state":"yes","summary":"Related tests appear to reach `src/lib.rs::discounted_total`: aliased_owner_boundary"}},"grip_class":"strongly_gripped","headline_eligible":false,"location":{"file":"src/lib.rs","line":2},"missing_discriminators":[],"observed_values":[{"context":"function_argument","line":15,"text":"assert_eq!(dt(100, 100), 90);","value":"100"}],"owner":"src/lib.rs::discounted_total","presentation_text":null,"raw_findings":[{"evidence_record_ref":"67f9714ba37b3967","expression":"amount >= threshold","file":"src/lib.rs","kind":"strongly_gripped","language":"rust","language_status":"stable","line":2,"probe_kind":"predicate_boundary","source_id":"67f9714ba37b3967"}],"recommendation":{"action":"no_action","assertion_shape":null,"candidate_values":[{"reason":"observed function_argument value from existing tests","value":"100"}],"nearest_test_to_imitate":{"evidence_summary":"exact value assertion","file":"src/lib.rs","line":14,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"},"reason":"seam is already gripped or intentionally non-actionable under current policy","recommended_test":null,"verify_command":null},"related_tests":[{"evidence_summary":"exact value assertion","file":"src/lib.rs","line":14,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"}],"related_tests_total":1,"schema_version":"0.1","seam_id":"67f9714ba37b3967","seam_kind":"predicate_boundary","static_limitations":[]} + } + ] +} diff --git a/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json b/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json new file mode 100644 index 00000000000..145508a5d86 --- /dev/null +++ b/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json @@ -0,0 +1,52 @@ +{ + "schema_version": "0.5", + "artifact": {"analysis":{"base_revision":null,"command":"ripr check --format repo-exposure-json","format":"repo-exposure-json","input_identity":"input:v4:fnv1a64:aa5beb28925f14ea","mode":"draft","profile":"draft","worktree":"unavailable"},"canonicalization":"raw_json_placeholder_v1","content_sha256":"sha256:5b38036a6ae0e3e8841329532392324544e5f5f5f6bb9919ca2c5ace3cf5c050","generated_at":"unix_ms:1794584396804","kind":"repo_exposure","producer":{"tool":"ripr","version":"0.11.0"},"repository":{"head":"unavailable","root":"/tmp/test-local-rival-import-alias-external"},"schema_version":"1","snapshot_identity":"snapshot:input:v4:fnv1a64:aa5beb28925f14ea;revision:unavailable"}, + "source_subject": {"corpus":{"analyzed_production_files":["src/lib.rs"],"cache_schema_version":"1.181","files_content_hash":"48dd1c951dd54872","scope":"rust_workspace"},"digest_algorithm":"sha256","files":[{"digest":"sha256:858593f0ceccb8663eff702f2aba4cfe384a6692e7f4befc072a4fd301ba4c15","path":"src/lib.rs"},{"digest":"sha256:51d5eae3c14db89fd5c3decc07479b22a0ec122bbd9e701f2f83bcb746cbc7eb","path":"tests/control.rs"}]}, + "analysis_inputs": {"analyzer_version":"0.11.0+83da5a7577113f588ce17ffddc9fe2bcaa852ea6-dirty+src:a34ee991b0f684e9+languages:rust=1,typescript=1,python=1,perl=0","cfg_features_hash":"cbf29ce484222325","config_hash":"881255e2f498d9f2","lockfile_hash":"0b74165b4cea4f09","suppressions_hash":"cbf29ce484222325","test_intent_hash":"cbf29ce484222325","toolchain_hash":"833996a486514c49","workspace_manifests_hash":"59fe076704c11c7d"}, + "scope": "repo", + "run_status": "complete", + "metrics": { + "seams_total": 1, + "headline_eligible": 0, + "strongly_gripped": 1, + "weakly_gripped": 0, + "ungripped": 0, + "reachable_unrevealed": 0, + "activation_unknown": 0, + "propagation_unknown": 0, + "observation_unknown": 0, + "discrimination_unknown": 0, + "opaque": 0, + "intentional": 0, + "suppressed": 0 + }, + "seams": [ + { + "seam_id": "67f9714ba37b3967", + "kind": "predicate_boundary", + "file": "src/lib.rs", + "line": 2, + "column": 8, + "end_line": 2, + "end_column": 27, + "owner": "src/lib.rs::discounted_total", + "expression": "amount >= threshold", + "grip_class": "strongly_gripped", + "headline_eligible": false, + "evidence": { + "reach": "yes", + "activate": "yes", + "propagate": "yes", + "observe": "yes", + "discriminate": "yes" + }, + "related_tests_total": 1, + "related_tests": [ + {"name": "aliased_owner_boundary", "file": "tests/control.rs", "line": 4, "oracle_kind": "exact_value", "oracle_strength": "strong", "evidence_summary": "exact value assertion", "relation_reason": "direct_owner_call", "relation_confidence": "high"} + ], + "observed_values": ["100"], + "missing_discriminators": [], + "evidence_record": {"actionability":{"class":"not_policy_relevant","has_concrete_guidance":false,"reason":"seam is already gripped or intentionally non-actionable under current policy","signals":{"assertion_shape":false,"candidate_value":true,"missing_discriminator":false,"recommended_test_target":true,"related_test":true,"verification_command":false}},"calibration":{"agreement":"no_runtime_data","availability":"not_imported","confidence":"unknown"},"canonical_gap_group_size":null,"canonical_gap_id":null,"canonical_gap_reason":null,"canonical_item":{"actionability":"already_observed","canonical_gap_id":null,"canonical_item_kind":"observed","command_specs":{"receipt":null,"verify":null},"confidence":{"basis":"static_only","notes":["no imported runtime calibration data"]},"evidence_class":"predicate_boundary","gap_state":"already_observed","group_reason":null,"primary_anchor":{"file":"src/lib.rs","kind":"strongly_gripped","line":2,"reason":"record_location","source_id":"67f9714ba37b3967"},"raw_group_size":1,"raw_spans":[{"end_line":2,"file":"src/lib.rs","kind":"strongly_gripped","source_id":"67f9714ba37b3967","start_line":2}],"receipt_command":null,"recommended_repair":"No new RIPR action; current static evidence already observes this seam.","related_test":{"file":"tests/control.rs","line":4,"name":"aliased_owner_boundary","reason":"direct_owner_call"},"repair_command":null,"repair_route":null,"static_limitations":[],"verify_command":null,"why":"seam is already gripped or intentionally non-actionable under current policy"},"evidence_path":{"activate":{"confidence":"medium","state":"yes","summary":"Observed 1 concrete activation value(s) for seam `amount >= threshold`"},"discriminate":{"confidence":"medium","state":"yes","summary":"Strongest oracle for seam kind `predicate_boundary` is `strong` (kind-match true)"},"observe":{"confidence":"medium","state":"yes","summary":"Observation evidence is `yes`"},"propagate":{"confidence":"low","state":"yes","summary":"Static propagation to `return_value` sink is yes"},"reach":{"confidence":"medium","state":"yes","summary":"Related tests appear to reach `src/lib.rs::discounted_total`: aliased_owner_boundary"}},"grip_class":"strongly_gripped","headline_eligible":false,"location":{"file":"src/lib.rs","line":2},"missing_discriminators":[],"observed_values":[{"context":"function_argument","line":5,"text":"assert_eq!(dt(100, 100), 90);","value":"100"}],"owner":"src/lib.rs::discounted_total","presentation_text":null,"raw_findings":[{"evidence_record_ref":"67f9714ba37b3967","expression":"amount >= threshold","file":"src/lib.rs","kind":"strongly_gripped","language":"rust","language_status":"stable","line":2,"probe_kind":"predicate_boundary","source_id":"67f9714ba37b3967"}],"recommendation":{"action":"no_action","assertion_shape":null,"candidate_values":[{"reason":"observed function_argument value from existing tests","value":"100"}],"nearest_test_to_imitate":{"evidence_summary":"exact value assertion","file":"tests/control.rs","line":4,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"},"reason":"seam is already gripped or intentionally non-actionable under current policy","recommended_test":null,"verify_command":null},"related_tests":[{"evidence_summary":"exact value assertion","file":"tests/control.rs","line":4,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"}],"related_tests_total":1,"schema_version":"0.1","seam_id":"67f9714ba37b3967","seam_kind":"predicate_boundary","static_limitations":[]} + } + ] +} diff --git a/policy/doc-artifacts.d/RIPR-SPEC-0442.toml b/policy/doc-artifacts.d/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..7adfa13312c --- /dev/null +++ b/policy/doc-artifacts.d/RIPR-SPEC-0442.toml @@ -0,0 +1,7 @@ +[[artifact]] +id = "RIPR-SPEC-0442" +kind = "spec" +path = "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md" +status = "accepted" +owner = "product-analysis" +standalone_reason = "Issue #14508 makes an aliased direct import of the owner credit the owner only when the import names its module in the same compilation unit; no existing spec states the alias rule." diff --git a/xtask/src/evidence_promotion.rs b/xtask/src/evidence_promotion.rs index ab47baa87eb..097df7ba8cd 100644 --- a/xtask/src/evidence_promotion.rs +++ b/xtask/src/evidence_promotion.rs @@ -4299,6 +4299,9 @@ pub(crate) fn check_evidence_promotion_honesty(args: &[String]) -> Result<(), St let corpus_path = Path::new(EVIDENCE_PROMOTION_HONESTY_CORPUS); let mut pure_violations = Vec::new(); validate_evidence_promotion_honesty_corpus_at(corpus_path, &mut pure_violations)?; + // A control that only pins a stored class cannot notice a removed guard; + // cases that name a live subject are re-run with the current binary. + check_live_check_cases(&mut pure_violations)?; // The repo-seam reports are hand-captured; regenerate each from its // subject so a stale capture or an analyzer regression turns red (#12144). repo_seam_reports::check_regenerated_reports(&mut pure_violations)?; @@ -4382,6 +4385,135 @@ pub(crate) fn check_evidence_promotion_honesty(args: &[String]) -> Result<(), St } } +/// Cases that pin a live `ripr check --diff` class, not only a stored report. +/// +/// A case with `live_check_subject` names a Cargo subject whose `diff.patch` +/// the gate passes to `ripr check --diff` with the current binary; the case's +/// `expected_class` assertion must hold on that live run. A stored report +/// alone cannot tell a guard that still works from one that was removed, +/// because the report is what was captured, not what the analyzer says now +/// (#14508 review). +fn check_live_check_cases(violations: &mut Vec) -> Result<(), String> { + let corpus = read_evidence_promotion_corpus(Path::new(EVIDENCE_PROMOTION_HONESTY_CORPUS))?; + let Some(cases) = corpus.get("cases").and_then(Value::as_array) else { + return Ok(()); + }; + let mut live = Vec::new(); + for case in cases { + let Some(subject) = case.get("live_check_subject").and_then(Value::as_str) else { + continue; + }; + let id = case + .get("id") + .and_then(Value::as_str) + .unwrap_or(""); + let expected = case + .get("assertions") + .and_then(Value::as_array) + .and_then(|assertions| { + assertions.iter().find_map(|assertion| { + (assertion.get("type").and_then(Value::as_str) == Some("expected_class")) + .then(|| assertion.get("class").and_then(Value::as_str)) + .flatten() + }) + }); + let Some(expected) = expected else { + violations.push(format!( + "evidence promotion honesty case `{id}`: `live_check_subject` requires an \ + `expected_class` assertion so the live run has a class to check" + )); + continue; + }; + live.push((id.to_string(), subject.to_string(), expected.to_string())); + } + if live.is_empty() { + return Ok(()); + } + run("cargo", &["build", "-p", "ripr", "--quiet"]).map_err(|error| { + format!("failed to build ripr for live evidence-promotion checks: {error}") + })?; + let binary = ripr_debug_binary(); + for (id, subject, expected) in live { + let case_label = format!("evidence promotion case `{id}`"); + let subject_path = Path::new(&subject); + let patch = subject_path.join("diff.patch"); + if !subject_path.join("Cargo.toml").is_file() || !patch.is_file() { + violations.push(format!( + "{case_label}: `live_check_subject` `{subject}` must be a Cargo subject with a `diff.patch`" + )); + continue; + } + let args = vec![ + "check".to_string(), + "--root".to_string(), + normalize_path(subject_path), + "--diff".to_string(), + normalize_path(&patch), + "--mode".to_string(), + "fast".to_string(), + "--json".to_string(), + ]; + let output = match capture_output_with_timeout( + &binary.to_string_lossy(), + &args, + &[], + Duration::from_mins(2), + "check-evidence-promotion-honesty live check", + ) { + Ok(output) => output, + Err(error) => { + violations.push(format!( + "{case_label}: live ripr check failed to start: {error}" + )); + continue; + } + }; + if output.timed_out { + violations.push(format!("{case_label}: live ripr check timed out")); + continue; + } + if !output.status.is_some_and(|status| status.success()) { + violations.push(format!( + "{case_label}: live ripr check exited non-zero: {}", + output.stderr.trim() + )); + continue; + } + let parsed: Value = match serde_json::from_str(&output.stdout) { + Ok(parsed) => parsed, + Err(error) => { + violations.push(format!( + "{case_label}: live ripr check stdout was not JSON: {error}" + )); + continue; + } + }; + let findings = parsed + .get("findings") + .and_then(Value::as_array) + .cloned() + .unwrap_or_default(); + if findings.len() != 1 { + violations.push(format!( + "{case_label}: live ripr check reported {} findings, but the case pins one", + findings.len() + )); + continue; + } + let actual = findings[0] + .get("classification") + .and_then(Value::as_str) + .unwrap_or(""); + if actual != expected { + violations.push(format!( + "{case_label}: live ripr check classifies the finding as `{actual}`, but the \ + corpus pins `{expected}`; the guard this control protects is not active" + )); + } + } + Ok(()) +} + pub(crate) fn validate_evidence_promotion_honesty_corpus( violations: &mut Vec, ) -> Result<(), String> { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index e4197a53369..c188add019e 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -14927,10 +14927,15 @@ fn check_rust_source_role_authority() -> Result<(), String> { /// authority may be consumed only by this inventoried set; new consumers /// extend the inventory here with a reason so role consumers stay /// reviewable. - const IS_TEST_FILE_CONSUMERS: [&str; 14] = [ + const IS_TEST_FILE_CONSUMERS: [&str; 15] = [ "crates/ripr/src/analysis/classify/owner_shape.rs", "crates/ripr/src/analysis/test_grip_evidence.rs", "crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs", + // #14508: a crate-relative direct-owner alias in an integration-test + // file names the test crate's own modules, never the library's; the + // layout authority stays `is_test_file` and the module decides no + // role of its own. + "crates/ripr/src/analysis/test_grip_evidence/related_tests.rs", "crates/ripr/src/analysis/source_role_corpus.rs", "crates/ripr/src/analysis/mod.rs", "crates/ripr/src/analysis/language/rust/mod.rs", From fd720fb2f69f48ea3f1c9bdfe978f018502ac62e Mon Sep 17 00:00:00 2001 From: EffortlessSteven <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:36:17 -0500 Subject: [PATCH 02/14] test(corpus): scope RIPR-SPEC-0442 in the verdict coverage ledgers The new aliased-owner-import spec carries numbered acceptance examples, so the committed-ledger gate refused it in every language ledger. Each entry is out of scope: the examples assert related-test credit and direct-owner evidence kind, not an exposure verdict a corpus case labels. --- fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml | 3 +++ fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml | 3 +++ fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml | 3 +++ .../typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml | 3 +++ 4 files changed, 12 insertions(+) create mode 100644 fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml create mode 100644 fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml create mode 100644 fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml create mode 100644 fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml diff --git a/fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/perl-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/python-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/rust-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." diff --git a/fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml b/fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml new file mode 100644 index 00000000000..915770dbc17 --- /dev/null +++ b/fixtures/typescript-verdict-corpus/spec-scopes/RIPR-SPEC-0442.toml @@ -0,0 +1,3 @@ +id = "RIPR-SPEC-0442" +scope = "out" +reason = "Related-test credit and direct-owner evidence kind for an import alias of the owner; the examples assert an evidence classification, not an exposure verdict a Rust diff plus runtime mutant truth labels. Pinned by crates/ripr/src/analysis/test_grip_evidence/tests.rs and the analysis::extract::shadow import-shadow table." From b92ea645cf3e29f5a05c340de9cd825e46fe35cf Mon Sep 17 00:00:00 2001 From: EffortlessSteven <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:38:17 -0500 Subject: [PATCH 03/14] fix(analysis): clear the clippy -D warnings failures at the reviewed head shadow.rs assigned the closure-scan cursor before every branch that rewrites it (unused_assignments) and kept the match brace lookup nested (collapsible_if); direct_owner_alias_module_matches takes nine independent inputs and is allowed with a reason. --- crates/ripr/src/analysis/extract/shadow.rs | 27 +++++++++---------- .../test_grip_evidence/related_tests.rs | 4 +++ 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index dba182ba14e..429213906f5 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -334,27 +334,26 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool } } // `match .. { => .. }` - if let Some(open) = body.find("match ") { - if let Some(brace) = body[open..].find('{') { - let arms = &body[open + brace + 1..]; - // Only text before a `=>` is a pattern; the final segment is the - // last arm's body and must not be scanned as a pattern (#14508 - // review). - let mut rest = arms; - while let Some((pattern, after)) = rest.split_once("=>") { - let pattern = pattern.rsplit(['{', ',', ';']).next().unwrap_or(pattern); - if pattern_contains_word(pattern, callee) { - return true; - } - rest = after; + if let Some(open) = body.find("match ") + && let Some(brace) = body[open..].find('{') + { + let arms = &body[open + brace + 1..]; + // Only text before a `=>` is a pattern; the final segment is the + // last arm's body and must not be scanned as a pattern (#14508 + // review). + let mut rest = arms; + while let Some((pattern, after)) = rest.split_once("=>") { + let pattern = pattern.rsplit(['{', ',', ';']).next().unwrap_or(pattern); + if pattern_contains_word(pattern, callee) { + return true; } + rest = after; } } // `|| ..` let mut search = 0usize; while let Some(offset) = body[search..].find('|') { let start = search + offset; - search = start + 1; if body.as_bytes().get(start + 1) == Some(&b'|') { search = start + 2; continue; diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index b536d487d79..1d2f7639f5b 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -444,6 +444,10 @@ pub(super) fn match_direct_owner_call( } } +#[allow( + clippy::too_many_arguments, + reason = "the alias spelling, the owner's module identity and the test crate unit are separate inputs; a struct would only rename them" +)] fn direct_owner_alias_module_matches( alias_module: &str, alias_crate_relative: bool, From 32b0455935cec85e22bc458cf8f2d2c5ca235afd Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:55:05 -0500 Subject: [PATCH 04/14] fix(analysis): resolve a nested mod beside a non-mod.rs file `resolve_module_chain` looked for a default `mod x;` under the declaring file's directory for every file, so `src/pricing.rs` declaring `mod inner;` sent the chain to `src/inner.rs`; a `crate::pricing::inner::owner` import then failed to resolve and a genuine aliased owner silently lost its `direct_owner_call` credit. Resolve under the stem-named directory unless the declaring file is a crate root or `mod.rs`; a `#[path]` target stays relative to the declaring file's directory, as rustc does. The nested-module test now runs both layouts (`pricing/mod.rs` and `pricing.rs`). With the old resolution the `pricing.rs` case credits nothing (`left: []`); with the fix both credit `["aliased", "aliased_from_root"]`. Also folds the five near-identical shadowing-form tests into one table and tightens duplicated comment prose, keeping the candidate inside the 3000-line admission cap: 2998 counted. --- .ripr/traceability.d/RIPR-SPEC-0442.toml | 2 +- .../test_grip_evidence/related_tests.rs | 51 ++++---- .../src/analysis/test_grip_evidence/tests.rs | 123 +++++++++--------- ...R-SPEC-0442-aliased-owner-import-credit.md | 10 +- 4 files changed, 89 insertions(+), 97 deletions(-) diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml index b34c3660ecd..88f93877e2d 100644 --- a/.ripr/traceability.d/RIPR-SPEC-0442.toml +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -18,7 +18,7 @@ tests = [ "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test", - "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_owner_takes_no_value_from_it", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it", "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_table_covers_each_scanned_form", diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 1d2f7639f5b..c29bebcce74 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -459,19 +459,13 @@ fn direct_owner_alias_module_matches( owner_prefix: Option<&str>, index: &RustIndex, ) -> bool { - // `src/pricing/mod.rs` names the `pricing` module, but - // `module_path_for_index` keeps the file stem (`pricing/mod`). Fold the - // `mod` leaf so a `mod.rs` owner matches its `crate::pricing` import - // (#14508 review). + // `src/pricing/mod.rs` names `pricing`, but `module_path_for_index` keeps + // the file stem (`pricing/mod`); fold the leaf so the owner matches its + // `crate::pricing` import (#14508 review). let owner_module = owner_module.strip_suffix("/mod").unwrap_or(owner_module); if alias_crate_relative { - // `crate::` resolves against the crate that compiles the test file. - // An integration test (`tests/...`) is its own crate, so its - // `crate::pricing` names `tests/pricing.rs`, never the library's - // `src/pricing.rs`; a unit test inside `src/` shares the library - // crate with the owner. Requiring compilation-unit identity before - // the equality check is what stops a test crate's own module from - // crediting the library owner (#14508 review). + // `crate::` resolves against the crate that compiles the test file, so + // compilation-unit identity must hold before the equality check. if rust_index::is_test_file(test_file) { return false; } @@ -482,10 +476,8 @@ fn direct_owner_alias_module_matches( if test_package != owner_package { return false; } - // Package identity alone does not establish library-versus-binary - // compilation-unit identity: a package can hold both a library and a - // binary, and `crate::` in the binary names the binary's own modules - // (#14508 review). + // A package can hold both a library and a binary, and `crate::` in the + // binary names the binary's own modules. if !crate_relative_alias_shares_compilation_unit( test_file, alias_module, @@ -499,9 +491,8 @@ fn direct_owner_alias_module_matches( if alias_module.is_empty() { return owner_is_crate_root; } - // The chain resolution above already compared the resolved file with - // the owner file; the index's module path for a binary target - // (`bin/pricing`) is not the crate-relative spelling (`pricing`). + // The chain above already compared files; the index's binary-target + // module path (`bin/pricing`) is not the crate-relative spelling. return true; } // An external import names a package first: `subject::pricing`. Only the @@ -535,13 +526,10 @@ fn direct_owner_alias_module_matches( /// test file, so package identity alone is not enough: a binary target is a /// separate compilation unit from the library beside it. /// -/// Two shapes are definite negatives: -/// - the test file is an established binary target root, so `crate::` names -/// that binary and never another crate root (the library root or a sibling -/// binary's root); -/// - the test file belongs to a `src/bin/` target, whose module tree is -/// confined to its own directory, so `crate::` never names a -/// library module. +/// Two shapes are definite negatives: the test file is an established binary +/// target root, so `crate::` names that binary and never another crate root; +/// or it belongs to a `src/bin/` target, whose module tree is confined +/// to its own directory, so `crate::` never names a library module. /// /// A binary root that reaches a *different* file for the same module name /// through `#[path]` stays unresolved here; the inline-module shadow guard @@ -622,8 +610,17 @@ fn resolve_module_chain(index: &RustIndex, root_file: &Path, module_path: &str) let dir = current.parent()?; current = match &declaration.path_target { ModulePathTarget::Default => { - let file = dir.join(format!("{segment}.rs")); - let mod_file = dir.join(segment).join("mod.rs"); + // `pricing.rs` declaring `mod x;` resolves under `pricing/`. + let root_like = module_stem(¤t).is_none() + || current.ends_with("mod.rs") + || index.member_crates.is_binary_target_root(¤t); + let base = if root_like { + dir.to_path_buf() + } else { + dir.join(current.file_stem()?) + }; + let file = base.join(format!("{segment}.rs")); + let mod_file = base.join(segment).join("mod.rs"); let file_exists = index_has_file(index, &file); let mod_exists = index_has_file(index, &mod_file); match (file_exists, mod_exists) { diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 983d6035a46..b2f6b601630 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23281,48 +23281,36 @@ fn given_direct_owner_alias_when_a_block_binding_shadows_it_then_owner_takes_no_ } #[test] -fn given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_owner_takes_no_value_from_it() +fn given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it() -> Result<(), String> { - assert_scoped_alias_shadow( - "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let f = |dt: fn(i32, i32) -> i32| dt(7, 7);\n assert_eq!(f(|a, b| a + b), 14);\n}\n", - "closure parameter", - ) -} - -#[test] -fn given_direct_owner_alias_when_a_for_pattern_shadows_it_then_owner_takes_no_value_from_it() --> Result<(), String> { - assert_scoped_alias_shadow( - "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n for dt in [|a: i32, b: i32| a + b] {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", - "for pattern", - ) -} - -#[test] -fn given_direct_owner_alias_when_a_match_arm_shadows_it_then_owner_takes_no_value_from_it() --> Result<(), String> { - assert_scoped_alias_shadow( - "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let x = |a: i32, b: i32| a + b;\n match x {\n dt => assert_eq!(dt(7, 7), 14),\n };\n}\n", - "match arm", - ) -} - -#[test] -fn given_direct_owner_alias_when_an_if_let_pattern_shadows_it_then_owner_takes_no_value_from_it() --> Result<(), String> { - assert_scoped_alias_shadow( - "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n if let Some(dt) = Some(|a: i32, b: i32| a + b) {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", - "if let pattern", - ) -} - -#[test] -fn given_direct_owner_alias_when_a_nested_fn_parameter_shadows_it_then_owner_takes_no_value_from_it() --> Result<(), String> { - assert_scoped_alias_shadow( - "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n fn helper(dt: fn(i32, i32) -> i32) -> i32 {\n dt(7, 7)\n }\n assert_eq!(helper(|a, b| a + b), 14);\n}\n", - "nested fn parameter", - ) + // One table over every scanned shadowing form keeps each form and its + // expected value covered without five near-identical functions. + let cases = [ + ( + "closure parameter", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let f = |dt: fn(i32, i32) -> i32| dt(7, 7);\n assert_eq!(f(|a, b| a + b), 14);\n}\n", + ), + ( + "for pattern", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n for dt in [|a: i32, b: i32| a + b] {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + ), + ( + "match arm", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n let x = |a: i32, b: i32| a + b;\n match x {\n dt => assert_eq!(dt(7, 7), 14),\n };\n}\n", + ), + ( + "if let pattern", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n if let Some(dt) = Some(|a: i32, b: i32| a + b) {\n assert_eq!(dt(7, 7), 14);\n }\n}\n", + ), + ( + "nested fn parameter", + "use lib_proptest::discounted_total as dt;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n fn helper(dt: fn(i32, i32) -> i32) -> i32 {\n dt(7, 7)\n }\n assert_eq!(helper(|a, b| a + b), 14);\n}\n", + ), + ]; + for (label, tests_src) in cases { + assert_scoped_alias_shadow(tests_src, label)?; + } + Ok(()) } #[test] @@ -23882,32 +23870,37 @@ fn given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_r -> Result<(), String> { // #14508 review: the alias table stores the import with `::` while the // owner's module path comes from the index with `/`; the nested owner - // (`pricing/inner`) must still resolve its `crate::pricing::inner` import. + // (`pricing/inner`) must still resolve its `crate::pricing::inner` import + // whether `pricing` is `pricing/mod.rs` or `pricing.rs`, whose + // `pub mod inner;` rustc resolves under `pricing/`, not `src/`. let inner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; let lib = "pub mod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::inner::owner as dt;\n\n #[test]\n fn aliased_from_root() {\n assert_eq!(dt(100), 90);\n }\n}\n"; - let root = alias_workspace_with_files( - "lib_proptest", - &[ - ("src/lib.rs", lib), - ("src/pricing/mod.rs", "pub mod inner;\n"), - ("src/pricing/inner.rs", inner), - ], - )?; - let files = [ - PathBuf::from("src/lib.rs"), - PathBuf::from("src/pricing/mod.rs"), - PathBuf::from("src/pricing/inner.rs"), - ]; - let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/inner.rs")?; - let mut related = direct_owner_call_tests(&evidence); - related.sort_unstable(); - assert_eq!(related, vec!["aliased", "aliased_from_root"]); - assert!( - evidence - .observed_values - .iter() - .any(|fact| fact.value == "100") - ); + for module in ["src/pricing/mod.rs", "src/pricing.rs"] { + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + (module, "pub mod inner;\n"), + ("src/pricing/inner.rs", inner), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from(module), + PathBuf::from("src/pricing/inner.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing/inner.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!(related, vec!["aliased", "aliased_from_root"], "{module}"); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "{module}" + ); + } Ok(()) } diff --git a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md index 9b21ff4757a..509b228e7eb 100644 --- a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md +++ b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md @@ -58,7 +58,8 @@ A direct import of the owner's function under an alias credits the owner as Both sides of the module comparison use one `/`-segment representation. `src/pricing/mod.rs` names the `pricing` module; a crate root has the empty -path. +path. A nested `mod x;` resolves as rustc does: under `pricing/` when declared +in `pricing.rs`, and under the declaring file's directory for `#[path]`. ### Refusal @@ -94,8 +95,9 @@ read the test's assertions and the owner's body. the observed argument. - An integration test's genuine package-qualified alias credits the owner; the same test crate's own `crate::` module does not. -- A nested owner (`src/pricing/inner.rs`) and a `mod.rs` owner - (`src/pricing/mod.rs`) credit their `crate::` imports. +- A nested owner (`src/pricing/inner.rs`) reached through `pricing/mod.rs` or + `pricing.rs`, and a `mod.rs` owner (`src/pricing/mod.rs`), credit their + `crate::` imports. - A same-named local function in the import's module or a nested module, or a lexical binding, withholds the owner; an enclosing-module declaration is shadowed by the import and keeps credit; a later genuine alias call keeps @@ -136,7 +138,7 @@ read the test's assertions and the owner's body. - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test` - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test` - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test` -- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_closure_parameter_shadows_it_then_owner_takes_no_value_from_it`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it` +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it` - `fixtures/evidence-promotion-honesty-corpus/corpus.json` `report_digest_required` report fixtures `rust-repo-exposure-alias-crate` and `rust-repo-exposure-alias-external` From ca7e65dba2c06b2aa2fd02b28cfca091082a8d59 Mon Sep 17 00:00:00 2001 From: EffortlessSteven <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 18:59:40 -0500 Subject: [PATCH 05/14] fix(analysis): treat only the compilation-unit root as root-like --- .../test_grip_evidence/related_tests.rs | 5 ++-- .../src/analysis/test_grip_evidence/tests.rs | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index c29bebcce74..659bf5e4a37 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -610,8 +610,9 @@ fn resolve_module_chain(index: &RustIndex, root_file: &Path, module_path: &str) let dir = current.parent()?; current = match &declaration.path_target { ModulePathTarget::Default => { - // `pricing.rs` declaring `mod x;` resolves under `pricing/`. - let root_like = module_stem(¤t).is_none() + // `pricing.rs` declaring `mod x;` resolves under `pricing/`; + // only the compilation-unit root keeps the declaring directory. + let root_like = current == root_file || current.ends_with("mod.rs") || index.member_crates.is_binary_target_root(¤t); let base = if root_like { diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index b2f6b601630..b244fafbc6e 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23904,6 +23904,35 @@ fn given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_r Ok(()) } +#[test] +fn given_direct_owner_alias_when_a_nested_main_module_declares_the_owner_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: a nested `main.rs` is a module, not a crate root, so its + // `pub mod inner;` resolves under `main/`, not beside it. + let inner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\n#[cfg(test)]\nmod tests {\n use crate::outer::main::inner::owner as dt;\n\n #[test]\n fn aliased() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let lib = "pub mod outer;\n\n#[cfg(test)]\nmod tests {\n use crate::outer::main::inner::owner as dt;\n\n #[test]\n fn aliased_from_root() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib), + ("src/outer.rs", "pub mod main;\n"), + ("src/outer/main.rs", "pub mod inner;\n"), + ("src/outer/main/inner.rs", inner), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/outer.rs"), + PathBuf::from("src/outer/main.rs"), + PathBuf::from("src/outer/main/inner.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/outer/main/inner.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!(related, vec!["aliased", "aliased_from_root"]); + Ok(()) +} + #[test] fn given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test() -> Result<(), String> { From e51311bd468010980caa29e9552d57c98209db61 Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:44:04 -0500 Subject: [PATCH 06/14] fix(analysis): close the nested-bin and tuple-pattern false credits --- crates/ripr/src/analysis/extract/shadow.rs | 36 ++++++++++++++++- .../test_grip_evidence/related_tests.rs | 5 ++- .../src/analysis/test_grip_evidence/tests.rs | 39 +++++++++++++++++++ 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index 429213906f5..9aff14b4729 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -307,6 +307,30 @@ pub(crate) fn body_shadows_callee_at_line(body: &str, callee: &str, body_line: u || test_body_scoped_shadow_at_line(body, callee) } +/// The current match arm's pattern: the text after the last top-level `,`, +/// `;` or `{` in the pre-`=>` text. Depth tracking keeps a tuple or struct +/// pattern's bindings, which a plain `rsplit` on `,` would drop (#14508 +/// review). +fn arm_pattern_before_arrow(text: &str) -> &str { + let mut depth = 0i32; + let mut cut = 0usize; + for (index, byte) in text.bytes().enumerate() { + match byte { + b')' | b']' | b'}' => depth -= 1, + b'(' | b'[' => depth += 1, + b'{' => { + if depth == 0 { + cut = index + 1; + } + depth += 1; + } + b',' | b';' if depth == 0 => cut = index + 1, + _ => {} + } + } + &text[cut..] +} + /// Lexical fallback for the scoped binding forms the parser facts cover /// (#14508 review): a closure, `for`, match-arm, `if let`/`while let` or /// nested-fn parameter that names `callee`. The lexical path is a @@ -343,7 +367,7 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool // review). let mut rest = arms; while let Some((pattern, after)) = rest.split_once("=>") { - let pattern = pattern.rsplit(['{', ',', ';']).next().unwrap_or(pattern); + let pattern = arm_pattern_before_arrow(pattern); if pattern_contains_word(pattern, callee) { return true; } @@ -629,6 +653,16 @@ mod fact_authority_tests { "match v { Some(x) => helper(x), owner => owner(1) }", true, ), + ( + "tuple pattern binding", + "match pair { (owner, _) => owner(100, 100), _ => 0 }", + true, + ), + ( + "struct pattern binding", + "match pair { Foo { owner, .. } => owner(100, 100), _ => 0 }", + true, + ), ]; for (label, body, expected) in cases { assert_eq!( diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 659bf5e4a37..3a171eed613 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -549,7 +549,10 @@ fn crate_relative_alias_shares_compilation_unit( } } if alias_module.is_empty() { - return true; + // `crate::owner` names the crate root of the compilation unit that + // compiles the test, so an empty alias module credits only when that + // root is the owner's crate root (#14508 review). + return context::crate_root_file_key(test_file).as_deref() == owner_crate_root; } let Some(owner_file) = owner_file else { return false; diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index b244fafbc6e..96d85d231fd 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23707,6 +23707,45 @@ fn given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owne Ok(()) } +#[test] +fn given_direct_owner_alias_when_a_nested_bin_module_imports_the_library_root_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a module inside a `src/bin/` target is not the + // target root, but its `crate::owner` still names the binary crate, never + // the library root `src/lib.rs`. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary_root = "mod work;\n\nfn main() {}\n"; + let nested = "use crate::owner as dt;\n\n#[test]\nfn nested_bin_rival() {\n assert_eq!(dt(7), 7);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", library), + ("src/bin/cli.rs", binary_root), + ("src/bin/cli/work.rs", nested), + ], + )?; + let files = [ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/bin/cli.rs"), + PathBuf::from("src/bin/cli/work.rs"), + ]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty(), + "a nested bin module's `crate::owner` must not credit the library root: {:?}", + evidence.related_tests + ); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the nested bin rival's argument must not become an observed value: {:?}", + evidence.observed_values + ); + Ok(()) +} + #[test] fn given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test() -> Result<(), String> { From 2837a336d4e4307dc97acea8fab82a86fc03c8e0 Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:44:04 -0500 Subject: [PATCH 07/14] recompose: move the evidence-promotion honesty corpus to a follow-up --- .ripr/traceability.d/RIPR-SPEC-0442.toml | 2 - ...R-SPEC-0442-aliased-owner-import-credit.md | 3 +- ...t_test_local_rival_import_alias_crate.json | 26 ---- ...est_local_rival_import_alias_external.json | 26 ---- .../corpus.json | 4 +- .../Cargo.toml | 10 -- .../src/lib.rs | 17 --- .../Cargo.toml | 10 -- .../src/lib.rs | 7 - .../tests/control.rs | 6 - .../rust-repo-exposure-alias-crate.json | 52 ------- .../rust-repo-exposure-alias-external.json | 52 ------- xtask/src/evidence_promotion.rs | 132 ------------------ 13 files changed, 2 insertions(+), 345 deletions(-) delete mode 100644 fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json delete mode 100644 fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json delete mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml delete mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs delete mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml delete mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs delete mode 100644 fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs delete mode 100644 fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json delete mode 100644 fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml index 88f93877e2d..b2c958c8f76 100644 --- a/.ripr/traceability.d/RIPR-SPEC-0442.toml +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -27,8 +27,6 @@ tests = [ ] fixtures = [ "fixtures/evidence-promotion-honesty-corpus/corpus.json", - "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json", - "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json", ] code = [ "crates/ripr/src/analysis/test_grip_evidence/related_tests.rs", diff --git a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md index 509b228e7eb..34331a38f19 100644 --- a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md +++ b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md @@ -140,8 +140,7 @@ read the test's assertions and the owner's body. - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test` - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it` - `fixtures/evidence-promotion-honesty-corpus/corpus.json` `report_digest_required` - report fixtures `rust-repo-exposure-alias-crate` and - `rust-repo-exposure-alias-external` + report fixtures move with the honesty-corpus follow-up. ## Implementation Mapping diff --git a/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json b/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json deleted file mode 100644 index 50b7b1b9c62..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_crate.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "id": "rust_test_local_rival_import_alias_crate", - "language": "rust", - "tier": "pure", - "source_report": "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json", - "report_subject": "fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate", - "vector": "crate_alias_of_the_owner_resolves_to_direct_owner_call", - "assertions": [ - { - "type": "expected_repo_seam_grip", - "owner": "src/lib.rs::discounted_total", - "expression": "amount >= threshold", - "grip_class": "strongly_gripped", - "reach": "yes" - }, - { - "type": "expected_repo_seam_related_test", - "owner": "src/lib.rs::discounted_total", - "expression": "amount >= threshold", - "test": "aliased_owner_boundary", - "file": "src/lib.rs", - "oracle_strength": "strong", - "relation_reason": "direct_owner_call" - } - ] -} diff --git a/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json b/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json deleted file mode 100644 index 30aec1df41c..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/cases/rust_test_local_rival_import_alias_external.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "id": "rust_test_local_rival_import_alias_external", - "language": "rust", - "tier": "pure", - "source_report": "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json", - "report_subject": "fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external", - "vector": "external_alias_of_the_owner_resolves_to_direct_owner_call", - "assertions": [ - { - "type": "expected_repo_seam_grip", - "owner": "src/lib.rs::discounted_total", - "expression": "amount >= threshold", - "grip_class": "strongly_gripped", - "reach": "yes" - }, - { - "type": "expected_repo_seam_related_test", - "owner": "src/lib.rs::discounted_total", - "expression": "amount >= threshold", - "test": "aliased_owner_boundary", - "file": "tests/control.rs", - "oracle_strength": "strong", - "relation_reason": "direct_owner_call" - } - ] -} diff --git a/fixtures/evidence-promotion-honesty-corpus/corpus.json b/fixtures/evidence-promotion-honesty-corpus/corpus.json index 648c688e63e..90fcd7c9b7a 100644 --- a/fixtures/evidence-promotion-honesty-corpus/corpus.json +++ b/fixtures/evidence-promotion-honesty-corpus/corpus.json @@ -262,9 +262,7 @@ "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-panic-marker-neutral.json", "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-test-local-rival-bare-use.json", "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-test-local-rival-glob-use.json", - "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-wrapper-fed-error.json", - "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json", - "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json" + "fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-wrapper-fed-error.json" ], "cases": [ { diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml deleted file mode 100644 index a5bd9510bf8..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "test_local_rival_import_alias_crate_subject" -version = "0.0.0" -edition = "2024" - -[lib] -name = "test_local_rival_import_alias_crate_subject" -path = "src/lib.rs" - -[workspace] diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs deleted file mode 100644 index 7d694fba3c9..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-crate/src/lib.rs +++ /dev/null @@ -1,17 +0,0 @@ -pub fn discounted_total(amount: i32, threshold: i32) -> i32 { - if amount >= threshold { - amount - 10 - } else { - amount - } -} - -#[cfg(test)] -mod tests { - use crate::discounted_total as dt; - - #[test] - fn aliased_owner_boundary() { - assert_eq!(dt(100, 100), 90); - } -} diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml deleted file mode 100644 index 7ccb9c715c5..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "test_local_rival_import_alias_external_subject" -version = "0.0.0" -edition = "2024" - -[lib] -name = "test_local_rival_import_alias_external_subject" -path = "src/lib.rs" - -[workspace] diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs deleted file mode 100644 index 1ca671a5aa6..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/src/lib.rs +++ /dev/null @@ -1,7 +0,0 @@ -pub fn discounted_total(amount: i32, threshold: i32) -> i32 { - if amount >= threshold { - amount - 10 - } else { - amount - } -} diff --git a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs b/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs deleted file mode 100644 index 47547a48527..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/repo-exposure-subjects/test-local-rival-import-alias-external/tests/control.rs +++ /dev/null @@ -1,6 +0,0 @@ -use test_local_rival_import_alias_external_subject::discounted_total as dt; - -#[test] -fn aliased_owner_boundary() { - assert_eq!(dt(100, 100), 90); -} diff --git a/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json b/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json deleted file mode 100644 index 9ba9f80351a..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-crate.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "schema_version": "0.5", - "artifact": {"analysis":{"base_revision":null,"command":"ripr check --format repo-exposure-json","format":"repo-exposure-json","input_identity":"input:v4:fnv1a64:9e844298a0b1f5fd","mode":"draft","profile":"draft","worktree":"unavailable"},"canonicalization":"raw_json_placeholder_v1","content_sha256":"sha256:77769302427300f8b486534a246eaeaa32969fa90baef390ab4dc5690aba17a9","generated_at":"unix_ms:1794584393247","kind":"repo_exposure","producer":{"tool":"ripr","version":"0.11.0"},"repository":{"head":"unavailable","root":"/tmp/test-local-rival-import-alias-crate"},"schema_version":"1","snapshot_identity":"snapshot:input:v4:fnv1a64:9e844298a0b1f5fd;revision:unavailable"}, - "source_subject": {"corpus":{"analyzed_production_files":["src/lib.rs"],"cache_schema_version":"1.181","files_content_hash":"b2e0a0abcf9113f5","scope":"rust_workspace"},"digest_algorithm":"sha256","files":[{"digest":"sha256:b1d83c56f9241e5abb3ab4cc8ad96dee54c9c4a16e5ae8f78ea0bd68735c747c","path":"src/lib.rs"}]}, - "analysis_inputs": {"analyzer_version":"0.11.0+83da5a7577113f588ce17ffddc9fe2bcaa852ea6-dirty+src:a34ee991b0f684e9+languages:rust=1,typescript=1,python=1,perl=0","cfg_features_hash":"cbf29ce484222325","config_hash":"881255e2f498d9f2","lockfile_hash":"0b74165b4cea4f09","suppressions_hash":"cbf29ce484222325","test_intent_hash":"cbf29ce484222325","toolchain_hash":"833996a486514c49","workspace_manifests_hash":"9b4f3c6dd797bb62"}, - "scope": "repo", - "run_status": "complete", - "metrics": { - "seams_total": 1, - "headline_eligible": 0, - "strongly_gripped": 1, - "weakly_gripped": 0, - "ungripped": 0, - "reachable_unrevealed": 0, - "activation_unknown": 0, - "propagation_unknown": 0, - "observation_unknown": 0, - "discrimination_unknown": 0, - "opaque": 0, - "intentional": 0, - "suppressed": 0 - }, - "seams": [ - { - "seam_id": "67f9714ba37b3967", - "kind": "predicate_boundary", - "file": "src/lib.rs", - "line": 2, - "column": 8, - "end_line": 2, - "end_column": 27, - "owner": "src/lib.rs::discounted_total", - "expression": "amount >= threshold", - "grip_class": "strongly_gripped", - "headline_eligible": false, - "evidence": { - "reach": "yes", - "activate": "yes", - "propagate": "yes", - "observe": "yes", - "discriminate": "yes" - }, - "related_tests_total": 1, - "related_tests": [ - {"name": "aliased_owner_boundary", "file": "src/lib.rs", "line": 14, "oracle_kind": "exact_value", "oracle_strength": "strong", "evidence_summary": "exact value assertion", "relation_reason": "direct_owner_call", "relation_confidence": "high"} - ], - "observed_values": ["100"], - "missing_discriminators": [], - "evidence_record": {"actionability":{"class":"not_policy_relevant","has_concrete_guidance":false,"reason":"seam is already gripped or intentionally non-actionable under current policy","signals":{"assertion_shape":false,"candidate_value":true,"missing_discriminator":false,"recommended_test_target":true,"related_test":true,"verification_command":false}},"calibration":{"agreement":"no_runtime_data","availability":"not_imported","confidence":"unknown"},"canonical_gap_group_size":null,"canonical_gap_id":null,"canonical_gap_reason":null,"canonical_item":{"actionability":"already_observed","canonical_gap_id":null,"canonical_item_kind":"observed","command_specs":{"receipt":null,"verify":null},"confidence":{"basis":"static_only","notes":["no imported runtime calibration data"]},"evidence_class":"predicate_boundary","gap_state":"already_observed","group_reason":null,"primary_anchor":{"file":"src/lib.rs","kind":"strongly_gripped","line":2,"reason":"record_location","source_id":"67f9714ba37b3967"},"raw_group_size":1,"raw_spans":[{"end_line":2,"file":"src/lib.rs","kind":"strongly_gripped","source_id":"67f9714ba37b3967","start_line":2}],"receipt_command":null,"recommended_repair":"No new RIPR action; current static evidence already observes this seam.","related_test":{"file":"src/lib.rs","line":14,"name":"aliased_owner_boundary","reason":"direct_owner_call"},"repair_command":null,"repair_route":null,"static_limitations":[],"verify_command":null,"why":"seam is already gripped or intentionally non-actionable under current policy"},"evidence_path":{"activate":{"confidence":"medium","state":"yes","summary":"Observed 1 concrete activation value(s) for seam `amount >= threshold`"},"discriminate":{"confidence":"medium","state":"yes","summary":"Strongest oracle for seam kind `predicate_boundary` is `strong` (kind-match true)"},"observe":{"confidence":"medium","state":"yes","summary":"Observation evidence is `yes`"},"propagate":{"confidence":"low","state":"yes","summary":"Static propagation to `return_value` sink is yes"},"reach":{"confidence":"medium","state":"yes","summary":"Related tests appear to reach `src/lib.rs::discounted_total`: aliased_owner_boundary"}},"grip_class":"strongly_gripped","headline_eligible":false,"location":{"file":"src/lib.rs","line":2},"missing_discriminators":[],"observed_values":[{"context":"function_argument","line":15,"text":"assert_eq!(dt(100, 100), 90);","value":"100"}],"owner":"src/lib.rs::discounted_total","presentation_text":null,"raw_findings":[{"evidence_record_ref":"67f9714ba37b3967","expression":"amount >= threshold","file":"src/lib.rs","kind":"strongly_gripped","language":"rust","language_status":"stable","line":2,"probe_kind":"predicate_boundary","source_id":"67f9714ba37b3967"}],"recommendation":{"action":"no_action","assertion_shape":null,"candidate_values":[{"reason":"observed function_argument value from existing tests","value":"100"}],"nearest_test_to_imitate":{"evidence_summary":"exact value assertion","file":"src/lib.rs","line":14,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"},"reason":"seam is already gripped or intentionally non-actionable under current policy","recommended_test":null,"verify_command":null},"related_tests":[{"evidence_summary":"exact value assertion","file":"src/lib.rs","line":14,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"}],"related_tests_total":1,"schema_version":"0.1","seam_id":"67f9714ba37b3967","seam_kind":"predicate_boundary","static_limitations":[]} - } - ] -} diff --git a/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json b/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json deleted file mode 100644 index 145508a5d86..00000000000 --- a/fixtures/evidence-promotion-honesty-corpus/reports/rust-repo-exposure-alias-external.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "schema_version": "0.5", - "artifact": {"analysis":{"base_revision":null,"command":"ripr check --format repo-exposure-json","format":"repo-exposure-json","input_identity":"input:v4:fnv1a64:aa5beb28925f14ea","mode":"draft","profile":"draft","worktree":"unavailable"},"canonicalization":"raw_json_placeholder_v1","content_sha256":"sha256:5b38036a6ae0e3e8841329532392324544e5f5f5f6bb9919ca2c5ace3cf5c050","generated_at":"unix_ms:1794584396804","kind":"repo_exposure","producer":{"tool":"ripr","version":"0.11.0"},"repository":{"head":"unavailable","root":"/tmp/test-local-rival-import-alias-external"},"schema_version":"1","snapshot_identity":"snapshot:input:v4:fnv1a64:aa5beb28925f14ea;revision:unavailable"}, - "source_subject": {"corpus":{"analyzed_production_files":["src/lib.rs"],"cache_schema_version":"1.181","files_content_hash":"48dd1c951dd54872","scope":"rust_workspace"},"digest_algorithm":"sha256","files":[{"digest":"sha256:858593f0ceccb8663eff702f2aba4cfe384a6692e7f4befc072a4fd301ba4c15","path":"src/lib.rs"},{"digest":"sha256:51d5eae3c14db89fd5c3decc07479b22a0ec122bbd9e701f2f83bcb746cbc7eb","path":"tests/control.rs"}]}, - "analysis_inputs": {"analyzer_version":"0.11.0+83da5a7577113f588ce17ffddc9fe2bcaa852ea6-dirty+src:a34ee991b0f684e9+languages:rust=1,typescript=1,python=1,perl=0","cfg_features_hash":"cbf29ce484222325","config_hash":"881255e2f498d9f2","lockfile_hash":"0b74165b4cea4f09","suppressions_hash":"cbf29ce484222325","test_intent_hash":"cbf29ce484222325","toolchain_hash":"833996a486514c49","workspace_manifests_hash":"59fe076704c11c7d"}, - "scope": "repo", - "run_status": "complete", - "metrics": { - "seams_total": 1, - "headline_eligible": 0, - "strongly_gripped": 1, - "weakly_gripped": 0, - "ungripped": 0, - "reachable_unrevealed": 0, - "activation_unknown": 0, - "propagation_unknown": 0, - "observation_unknown": 0, - "discrimination_unknown": 0, - "opaque": 0, - "intentional": 0, - "suppressed": 0 - }, - "seams": [ - { - "seam_id": "67f9714ba37b3967", - "kind": "predicate_boundary", - "file": "src/lib.rs", - "line": 2, - "column": 8, - "end_line": 2, - "end_column": 27, - "owner": "src/lib.rs::discounted_total", - "expression": "amount >= threshold", - "grip_class": "strongly_gripped", - "headline_eligible": false, - "evidence": { - "reach": "yes", - "activate": "yes", - "propagate": "yes", - "observe": "yes", - "discriminate": "yes" - }, - "related_tests_total": 1, - "related_tests": [ - {"name": "aliased_owner_boundary", "file": "tests/control.rs", "line": 4, "oracle_kind": "exact_value", "oracle_strength": "strong", "evidence_summary": "exact value assertion", "relation_reason": "direct_owner_call", "relation_confidence": "high"} - ], - "observed_values": ["100"], - "missing_discriminators": [], - "evidence_record": {"actionability":{"class":"not_policy_relevant","has_concrete_guidance":false,"reason":"seam is already gripped or intentionally non-actionable under current policy","signals":{"assertion_shape":false,"candidate_value":true,"missing_discriminator":false,"recommended_test_target":true,"related_test":true,"verification_command":false}},"calibration":{"agreement":"no_runtime_data","availability":"not_imported","confidence":"unknown"},"canonical_gap_group_size":null,"canonical_gap_id":null,"canonical_gap_reason":null,"canonical_item":{"actionability":"already_observed","canonical_gap_id":null,"canonical_item_kind":"observed","command_specs":{"receipt":null,"verify":null},"confidence":{"basis":"static_only","notes":["no imported runtime calibration data"]},"evidence_class":"predicate_boundary","gap_state":"already_observed","group_reason":null,"primary_anchor":{"file":"src/lib.rs","kind":"strongly_gripped","line":2,"reason":"record_location","source_id":"67f9714ba37b3967"},"raw_group_size":1,"raw_spans":[{"end_line":2,"file":"src/lib.rs","kind":"strongly_gripped","source_id":"67f9714ba37b3967","start_line":2}],"receipt_command":null,"recommended_repair":"No new RIPR action; current static evidence already observes this seam.","related_test":{"file":"tests/control.rs","line":4,"name":"aliased_owner_boundary","reason":"direct_owner_call"},"repair_command":null,"repair_route":null,"static_limitations":[],"verify_command":null,"why":"seam is already gripped or intentionally non-actionable under current policy"},"evidence_path":{"activate":{"confidence":"medium","state":"yes","summary":"Observed 1 concrete activation value(s) for seam `amount >= threshold`"},"discriminate":{"confidence":"medium","state":"yes","summary":"Strongest oracle for seam kind `predicate_boundary` is `strong` (kind-match true)"},"observe":{"confidence":"medium","state":"yes","summary":"Observation evidence is `yes`"},"propagate":{"confidence":"low","state":"yes","summary":"Static propagation to `return_value` sink is yes"},"reach":{"confidence":"medium","state":"yes","summary":"Related tests appear to reach `src/lib.rs::discounted_total`: aliased_owner_boundary"}},"grip_class":"strongly_gripped","headline_eligible":false,"location":{"file":"src/lib.rs","line":2},"missing_discriminators":[],"observed_values":[{"context":"function_argument","line":5,"text":"assert_eq!(dt(100, 100), 90);","value":"100"}],"owner":"src/lib.rs::discounted_total","presentation_text":null,"raw_findings":[{"evidence_record_ref":"67f9714ba37b3967","expression":"amount >= threshold","file":"src/lib.rs","kind":"strongly_gripped","language":"rust","language_status":"stable","line":2,"probe_kind":"predicate_boundary","source_id":"67f9714ba37b3967"}],"recommendation":{"action":"no_action","assertion_shape":null,"candidate_values":[{"reason":"observed function_argument value from existing tests","value":"100"}],"nearest_test_to_imitate":{"evidence_summary":"exact value assertion","file":"tests/control.rs","line":4,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"},"reason":"seam is already gripped or intentionally non-actionable under current policy","recommended_test":null,"verify_command":null},"related_tests":[{"evidence_summary":"exact value assertion","file":"tests/control.rs","line":4,"name":"aliased_owner_boundary","oracle_kind":"exact_value","oracle_semantics":{"missing":"no obvious value-shape discriminator gap under static scope","observes":"the exact value or value pattern asserted by the test","upgrade_suggestion":null},"oracle_strength":"strong","relation_confidence":"high","relation_reason":"direct_owner_call"}],"related_tests_total":1,"schema_version":"0.1","seam_id":"67f9714ba37b3967","seam_kind":"predicate_boundary","static_limitations":[]} - } - ] -} diff --git a/xtask/src/evidence_promotion.rs b/xtask/src/evidence_promotion.rs index 097df7ba8cd..ab47baa87eb 100644 --- a/xtask/src/evidence_promotion.rs +++ b/xtask/src/evidence_promotion.rs @@ -4299,9 +4299,6 @@ pub(crate) fn check_evidence_promotion_honesty(args: &[String]) -> Result<(), St let corpus_path = Path::new(EVIDENCE_PROMOTION_HONESTY_CORPUS); let mut pure_violations = Vec::new(); validate_evidence_promotion_honesty_corpus_at(corpus_path, &mut pure_violations)?; - // A control that only pins a stored class cannot notice a removed guard; - // cases that name a live subject are re-run with the current binary. - check_live_check_cases(&mut pure_violations)?; // The repo-seam reports are hand-captured; regenerate each from its // subject so a stale capture or an analyzer regression turns red (#12144). repo_seam_reports::check_regenerated_reports(&mut pure_violations)?; @@ -4385,135 +4382,6 @@ pub(crate) fn check_evidence_promotion_honesty(args: &[String]) -> Result<(), St } } -/// Cases that pin a live `ripr check --diff` class, not only a stored report. -/// -/// A case with `live_check_subject` names a Cargo subject whose `diff.patch` -/// the gate passes to `ripr check --diff` with the current binary; the case's -/// `expected_class` assertion must hold on that live run. A stored report -/// alone cannot tell a guard that still works from one that was removed, -/// because the report is what was captured, not what the analyzer says now -/// (#14508 review). -fn check_live_check_cases(violations: &mut Vec) -> Result<(), String> { - let corpus = read_evidence_promotion_corpus(Path::new(EVIDENCE_PROMOTION_HONESTY_CORPUS))?; - let Some(cases) = corpus.get("cases").and_then(Value::as_array) else { - return Ok(()); - }; - let mut live = Vec::new(); - for case in cases { - let Some(subject) = case.get("live_check_subject").and_then(Value::as_str) else { - continue; - }; - let id = case - .get("id") - .and_then(Value::as_str) - .unwrap_or(""); - let expected = case - .get("assertions") - .and_then(Value::as_array) - .and_then(|assertions| { - assertions.iter().find_map(|assertion| { - (assertion.get("type").and_then(Value::as_str) == Some("expected_class")) - .then(|| assertion.get("class").and_then(Value::as_str)) - .flatten() - }) - }); - let Some(expected) = expected else { - violations.push(format!( - "evidence promotion honesty case `{id}`: `live_check_subject` requires an \ - `expected_class` assertion so the live run has a class to check" - )); - continue; - }; - live.push((id.to_string(), subject.to_string(), expected.to_string())); - } - if live.is_empty() { - return Ok(()); - } - run("cargo", &["build", "-p", "ripr", "--quiet"]).map_err(|error| { - format!("failed to build ripr for live evidence-promotion checks: {error}") - })?; - let binary = ripr_debug_binary(); - for (id, subject, expected) in live { - let case_label = format!("evidence promotion case `{id}`"); - let subject_path = Path::new(&subject); - let patch = subject_path.join("diff.patch"); - if !subject_path.join("Cargo.toml").is_file() || !patch.is_file() { - violations.push(format!( - "{case_label}: `live_check_subject` `{subject}` must be a Cargo subject with a `diff.patch`" - )); - continue; - } - let args = vec![ - "check".to_string(), - "--root".to_string(), - normalize_path(subject_path), - "--diff".to_string(), - normalize_path(&patch), - "--mode".to_string(), - "fast".to_string(), - "--json".to_string(), - ]; - let output = match capture_output_with_timeout( - &binary.to_string_lossy(), - &args, - &[], - Duration::from_mins(2), - "check-evidence-promotion-honesty live check", - ) { - Ok(output) => output, - Err(error) => { - violations.push(format!( - "{case_label}: live ripr check failed to start: {error}" - )); - continue; - } - }; - if output.timed_out { - violations.push(format!("{case_label}: live ripr check timed out")); - continue; - } - if !output.status.is_some_and(|status| status.success()) { - violations.push(format!( - "{case_label}: live ripr check exited non-zero: {}", - output.stderr.trim() - )); - continue; - } - let parsed: Value = match serde_json::from_str(&output.stdout) { - Ok(parsed) => parsed, - Err(error) => { - violations.push(format!( - "{case_label}: live ripr check stdout was not JSON: {error}" - )); - continue; - } - }; - let findings = parsed - .get("findings") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - if findings.len() != 1 { - violations.push(format!( - "{case_label}: live ripr check reported {} findings, but the case pins one", - findings.len() - )); - continue; - } - let actual = findings[0] - .get("classification") - .and_then(Value::as_str) - .unwrap_or(""); - if actual != expected { - violations.push(format!( - "{case_label}: live ripr check classifies the finding as `{actual}`, but the \ - corpus pins `{expected}`; the guard this control protects is not active" - )); - } - } - Ok(()) -} - pub(crate) fn validate_evidence_promotion_honesty_corpus( violations: &mut Vec, ) -> Result<(), String> { From 175ebc42aea06d24e1fbff1e96dfccb1c2897141 Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:07:56 -0500 Subject: [PATCH 08/14] test(analysis): cover nested tuple and slice shadow patterns --- crates/ripr/src/analysis/extract/shadow.rs | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index 9aff14b4729..fcbfd03f963 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -663,6 +663,16 @@ mod fact_authority_tests { "match pair { Foo { owner, .. } => owner(100, 100), _ => 0 }", true, ), + ( + "nested tuple pattern binding", + "match pair { Some((owner, _)) => owner(100, 100), _ => 0 }", + true, + ), + ( + "slice pattern binding", + "match pair { [owner, _] => owner(100, 100), _ => 0 }", + true, + ), ]; for (label, body, expected) in cases { assert_eq!( @@ -672,4 +682,28 @@ mod fact_authority_tests { ); } } + + #[test] + fn scoped_shadow_sees_a_flat_tuple_pattern_binding() { + assert!(test_body_scoped_shadow_at_line( + "match pair { (owner, _) => owner(100, 100), _ => 0 }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_nested_tuple_pattern_binding() { + assert!(test_body_scoped_shadow_at_line( + "match pair { Some((owner, _)) => owner(100, 100), _ => 0 }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_slice_pattern_binding() { + assert!(test_body_scoped_shadow_at_line( + "match pair { [owner, _] => owner(100, 100), _ => 0 }", + "owner" + )); + } } From 1086e7ce2c68bd9866127f16448ac6c631194200 Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:02:50 -0500 Subject: [PATCH 09/14] fix(analysis): resolve the test crate root for empty-alias credit --- .../test_grip_evidence/related_tests.rs | 8 +++- .../src/analysis/test_grip_evidence/tests.rs | 48 +++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 3a171eed613..5aaaabbfcac 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -552,7 +552,13 @@ fn crate_relative_alias_shares_compilation_unit( // `crate::owner` names the crate root of the compilation unit that // compiles the test, so an empty alias module credits only when that // root is the owner's crate root (#14508 review). - return context::crate_root_file_key(test_file).as_deref() == owner_crate_root; + let Some(owner_root) = owner_crate_root else { + return false; + }; + let Some(test_root) = crate_root_file_for_test(index, test_file) else { + return false; + }; + return normalize_path(&test_root) == normalize_path(Path::new(owner_root)); } let Some(owner_file) = owner_file else { return false; diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 96d85d231fd..3936888d9fc 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23746,6 +23746,54 @@ fn given_direct_owner_alias_when_a_nested_bin_module_imports_the_library_root_th Ok(()) } +#[test] +fn given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: `crate::owner` in a library child module names the + // library root, so the alias must credit the root owner. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\npub mod child;\n"; + let child = "use crate::owner as dt;\n\n#[test]\nfn child_module_uses_the_root_owner() {\n assert_eq!(dt(100), 90);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[("src/lib.rs", library), ("src/child.rs", child)], + )?; + let files = [PathBuf::from("src/lib.rs"), PathBuf::from("src/child.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!( + related, + vec!["child_module_uses_the_root_owner"], + "a library child module's `crate::owner` credits the root owner: {:?}", + evidence.related_tests + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test() +-> Result<(), String> { + // #14508 review: with no library target, `crate::owner` in a child module + // names the binary root `src/main.rs`, so the alias must credit it. + let main = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n\npub mod child;\n\nfn main() {}\n"; + let child = "use crate::owner as dt;\n\n#[test]\nfn bin_child_uses_the_root_owner() {\n assert_eq!(dt(100), 90);\n}\n"; + let root = alias_workspace_with_files( + "bin_only", + &[("src/main.rs", main), ("src/child.rs", child)], + )?; + let files = [PathBuf::from("src/main.rs"), PathBuf::from("src/child.rs")]; + let evidence = evidence_for_alias_seam(&root, &files, "src/main.rs")?; + let mut related = direct_owner_call_tests(&evidence); + related.sort_unstable(); + assert_eq!( + related, + vec!["bin_child_uses_the_root_owner"], + "a bin-only child module's `crate::owner` credits the binary root owner: {:?}", + evidence.related_tests + ); + Ok(()) +} + #[test] fn given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test() -> Result<(), String> { From d2896b0b0ad1799c370f7f72f7d88f1eb9860a7f Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:31:37 -0500 Subject: [PATCH 10/14] fix(analysis): scan every scoped-shadow form and fix the nested-bin fixture --- .ripr/traceability.d/RIPR-SPEC-0442.toml | 6 +++ crates/ripr/src/analysis/extract/shadow.rs | 46 +++++++++++++------ .../src/analysis/test_grip_evidence/tests.rs | 4 +- ...R-SPEC-0442-aliased-owner-import-credit.md | 1 + 4 files changed, 41 insertions(+), 16 deletions(-) diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml index b2c958c8f76..9a758c62142 100644 --- a/.ripr/traceability.d/RIPR-SPEC-0442.toml +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -24,6 +24,12 @@ tests = [ "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_table_covers_each_scanned_form", "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_ignores_a_genuine_call_in_the_last_match_arm", "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_keeps_a_real_match_arm_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_flat_tuple_pattern_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_nested_tuple_pattern_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_slice_pattern_binding", + "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_binding_in_a_later_loop", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test", ] fixtures = [ "fixtures/evidence-promotion-honesty-corpus/corpus.json", diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index fcbfd03f963..c8f882f39aa 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -344,23 +344,22 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool return false; } // `for in ..` - if let Some(pattern) = between_keywords(body, "for ", " in ") - && pattern_contains_word(pattern, callee) - { + if any_between_keywords(body, "for ", " in ", callee) { return true; } // `if let = ..` and `while let = ..` for keyword in ["if let ", "while let "] { - if let Some(pattern) = between_keywords(body, keyword, " = ") - && pattern_contains_word(pattern, callee) - { + if any_between_keywords(body, keyword, " = ", callee) { return true; } } // `match .. { => .. }` - if let Some(open) = body.find("match ") - && let Some(brace) = body[open..].find('{') - { + let mut search = 0usize; + while let Some(offset) = body[search..].find("match ") { + let open = search + offset; + let Some(brace) = body[open..].find('{') else { + break; + }; let arms = &body[open + brace + 1..]; // Only text before a `=>` is a pattern; the final segment is the // last arm's body and must not be scanned as a pattern (#14508 @@ -373,6 +372,7 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool } rest = after; } + search = open + brace + 1; } // `|| ..` let mut search = 0usize; @@ -410,11 +410,21 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool false } -/// The text between the first `start` keyword and the next `end` keyword. -fn between_keywords<'a>(body: &'a str, start: &str, end: &str) -> Option<&'a str> { - let start = body.find(start)? + start.len(); - let end = body[start..].find(end)?; - Some(&body[start..start + end]) +/// Whether any `` occurrence names `callee`, so a later +/// loop or `if let` binding is not invisible (#14508 review). +fn any_between_keywords(body: &str, start: &str, end: &str, callee: &str) -> bool { + let mut search = 0usize; + while let Some(offset) = body[search..].find(start) { + let pattern_start = search + offset + start.len(); + let Some(end_offset) = body[pattern_start..].find(end) else { + return false; + }; + if pattern_contains_word(&body[pattern_start..pattern_start + end_offset], callee) { + return true; + } + search = pattern_start + end_offset + end.len(); + } + false } /// Whole-word containment: `word` delimited by non-identifier characters on @@ -706,4 +716,12 @@ mod fact_authority_tests { "owner" )); } + + #[test] + fn scoped_shadow_sees_a_binding_in_a_later_loop() { + assert!(test_body_scoped_shadow_at_line( + "for item in first { consume(item); } for owner in callbacks { owner(100, 100); }", + "owner" + )); + } } diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 3936888d9fc..d611226521b 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23720,13 +23720,13 @@ fn given_direct_owner_alias_when_a_nested_bin_module_imports_the_library_root_th "lib_proptest", &[ ("src/lib.rs", library), - ("src/bin/cli.rs", binary_root), + ("src/bin/cli/main.rs", binary_root), ("src/bin/cli/work.rs", nested), ], )?; let files = [ PathBuf::from("src/lib.rs"), - PathBuf::from("src/bin/cli.rs"), + PathBuf::from("src/bin/cli/main.rs"), PathBuf::from("src/bin/cli/work.rs"), ]; let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; diff --git a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md index 34331a38f19..437442ee47c 100644 --- a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md +++ b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md @@ -139,6 +139,7 @@ read the test's assertions and the owner's body. - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test` - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test` - `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it` +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_flat_tuple_pattern_binding`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_nested_tuple_pattern_binding`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_slice_pattern_binding`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_binding_in_a_later_loop` - `fixtures/evidence-promotion-honesty-corpus/corpus.json` `report_digest_required` report fixtures move with the honesty-corpus follow-up. From bb40f494afab2c1862568d121aabd6e514458aa0 Mon Sep 17 00:00:00 2001 From: EffortlessSteven <15812269+EffortlessSteven@users.noreply.github.com> Date: Sat, 14 Nov 2026 00:32:06 -0500 Subject: [PATCH 11/14] fix(analysis): resolve the crate root that declares a mixed-target child module A package with both src/lib.rs and src/main.rs has two compilation units. crate_root_file_for_test preferred src/lib.rs for any src/ child, so a module declared only by the binary was credited to the library owner. Resolve the test file's module chain from each root and use the one that declares it; ambiguous or undeclared fails closed. --- .ripr/traceability.d/RIPR-SPEC-0442.toml | 1 + changelog.d/14508-aliased-owner-import.md | 11 +-- .../test_grip_evidence/related_tests.rs | 29 ++++++- .../src/analysis/test_grip_evidence/tests.rs | 29 +++++++ ...R-SPEC-0442-aliased-owner-import-credit.md | 81 ++++++------------- 5 files changed, 84 insertions(+), 67 deletions(-) diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml index 9a758c62142..de7e319c910 100644 --- a/.ripr/traceability.d/RIPR-SPEC-0442.toml +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -30,6 +30,7 @@ tests = [ "crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_binding_in_a_later_loop", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_child_module_imports_the_binary_root_then_library_owner_gets_no_related_test", ] fixtures = [ "fixtures/evidence-promotion-honesty-corpus/corpus.json", diff --git a/changelog.d/14508-aliased-owner-import.md b/changelog.d/14508-aliased-owner-import.md index c1db2263adf..0bbea5ee967 100644 --- a/changelog.d/14508-aliased-owner-import.md +++ b/changelog.d/14508-aliased-owner-import.md @@ -1,10 +1,7 @@ - `ripr pilot` and the repo-exposure grip path credit a test that imports the changed owner under an alias as a direct owner call when the import names the - owner's module (crate root, nested file module, `mod.rs`, or an integration - test's package-qualified import). A `crate::` import in an integration test - names that test crate's own module, so it does not credit the library owner - (#14508). The alias credits only when the resolved `crate::` chain file is - the owner file; a missing declaration or a non-literal `#[path]` on any - segment is withheld. Inline-module owners stay uncredited, tracked in - #14558. + owner's module in the same compilation unit (crate root, nested file module, + `mod.rs`, or an integration test's package-qualified import). A `crate::` + import in an integration test or a binary target names that unit's own + module, so it does not credit the library owner (#14508). diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 5aaaabbfcac..7b6c26002b0 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -595,14 +595,35 @@ fn crate_root_file_for_test(index: &RustIndex, test_file: &Path) -> Option Some(lib), + (false, true) => Some(main), + _ => None, + } } /// Resolve a slash-separated `crate::` chain from `root_file` the way rustc diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index d611226521b..798996872bd 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23794,6 +23794,35 @@ fn given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_ Ok(()) } +#[test] +fn given_direct_owner_alias_when_a_binary_child_module_imports_the_binary_root_then_library_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a package with both `src/lib.rs` and `src/main.rs` has + // two compilation units. `src/child.rs` is declared only by the binary, so + // `crate::owner` in it names the binary's re-export, never the library + // owner. + let library = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let binary = "pub fn binary_value(_: i32) -> i32 { 800 }\n\npub use crate::binary_value as owner;\n\nmod child;\n\nfn main() {}\n"; + let child = "use crate::owner as dt;\n\n#[test]\nfn binary_child() {\n assert_eq!(dt(100), 800);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", library), + ("src/main.rs", binary), + ("src/child.rs", child), + ], + )?; + let files = ["src/lib.rs", "src/main.rs", "src/child.rs"].map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty() && evidence.observed_values.is_empty(), + "a binary-only child module's `crate::owner` must not credit the library root: {:?} / {:?}", + evidence.related_tests, + evidence.observed_values + ); + Ok(()) +} + #[test] fn given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test() -> Result<(), String> { diff --git a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md index 437442ee47c..0fd5b02f70e 100644 --- a/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md +++ b/docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md @@ -12,20 +12,15 @@ selective control for test-local rival imports). Linked PRs: #14513 -Support-tier impact: +Support-tier impact: no tier change. The change decides which existing +`direct_owner_call` relation a test already-spelled call earns; it adds no +grip class, `static_limit_kind` value or exposure class. Claim boundaries +remain governed by [support tiers](../status/SUPPORT_TIERS.md). -- No tier change. The change decides which existing `direct_owner_call` - relation a test already-spelled call earns; it adds no grip class, - `static_limit_kind` value or exposure class. Claim boundaries remain - governed by [support tiers](../status/SUPPORT_TIERS.md). - -Policy impact: - -- Register this spec in `policy/doc-artifacts.d/RIPR-SPEC-0442.toml` and - `.ripr/traceability.d/RIPR-SPEC-0442.toml`. -- No schema or JSON field change. The judged repo-exposure fields stay - `grip_class`, `evidence.reach`, `related_tests[].relation_reason` and - `observed_values`. +Policy impact: register this spec in `policy/doc-artifacts.d/RIPR-SPEC-0442.toml` +and `.ripr/traceability.d/RIPR-SPEC-0442.toml`. No schema or JSON field +change; the judged repo-exposure fields stay `grip_class`, `evidence.reach`, +`related_tests[].relation_reason` and `observed_values`. ## Problem @@ -34,15 +29,10 @@ A test that writes `use crate::pricing::discounted_total as dt;` and calls it. The owner module path joined segments with `/` while the import used `::`, so a nested owner stayed `activation_unknown`; and a test crate's own `crate::pricing` resolved to `tests/pricing.rs` yet a bare module-name -comparison credited the library's `src/pricing.rs::owner`. A same-named local -binding, a sibling inline module and an enclosing-module declaration were the -other edges; the guard compares the import's module depth with the -declaration's module chain. +comparison credited the library's `src/pricing.rs::owner`. ## Behavior -### Credit - A direct import of the owner's function under an alias credits the owner as `direct_owner_call` when both hold: @@ -58,10 +48,7 @@ A direct import of the owner's function under an alias credits the owner as Both sides of the module comparison use one `/`-segment representation. `src/pricing/mod.rs` names the `pricing` module; a crate root has the empty -path. A nested `mod x;` resolves as rustc does: under `pricing/` when declared -in `pricing.rs`, and under the declaring file's directory for `#[path]`. - -### Refusal +path. A nested `mod x;` resolves as rustc does, following `#[path]`. The alias does not credit the owner when: @@ -81,29 +68,22 @@ The alias does not credit the owner when: A test that also spells a genuine local call of the alias name keeps the generic direct-call credit for that call; only the alias-shaped calls are -routed to the import. - -### Scope - -The rule decides `related_tests[].relation_reason` in the seam-grip and -repo-exposure paths. It does not add a reach edge by itself: the stages still -read the test's assertions and the owner's body. +routed to the import. The rule decides `related_tests[].relation_reason` in +the seam-grip and repo-exposure paths and adds no reach edge by itself. ## Required Evidence - An aliased unit-test call credits the owner with `direct_owner_call` and - the observed argument. -- An integration test's genuine package-qualified alias credits the owner; - the same test crate's own `crate::` module does not. + the observed argument; an integration test's genuine package-qualified + alias credits the owner, while the same test crate's own `crate::` module + does not. - A nested owner (`src/pricing/inner.rs`) reached through `pricing/mod.rs` or - `pricing.rs`, and a `mod.rs` owner (`src/pricing/mod.rs`), credit their - `crate::` imports. + `pricing.rs`, and a `mod.rs` owner, credit their `crate::` imports. - A same-named local function in the import's module or a nested module, or a lexical binding, withholds the owner; an enclosing-module declaration is shadowed by the import and keeps credit; a later genuine alias call keeps - credit. -- A sibling inline module's same-named function neither shadows the alias - nor receives the alias credit. + credit. A sibling inline module's same-named function neither shadows the + alias nor receives the alias credit. - Only a bare `alias(..)` spelling binds to the import: a same-line `rival::alias(..)` on a lowercase module names that module's function and lends the owner no argument. @@ -112,20 +92,17 @@ read the test's assertions and the owner's body. ## Non-Goals -- Grouped (`use a::{b as c}`), chained (`use a::b as c; use c::d;`) and - renamed module aliases (`use a as b;`). +- Grouped (`use a::{b as c}`), chained (`use a::b as c; use c::d;`) and renamed module aliases (`use a as b;`). - The diff-mode `ripr check` relation path, which is a separate gap. - Trait or impl alias credit; the alias must name a free function. - In a lib+bin package whose binary root declares the module with the default path, the binary's `crate::` compiles the same source file as the - library owner, and the alias still credits the library owner. Tracked in - #14558. + library owner, and the alias still credits it. Tracked in #14558. ## Acceptance Examples 1. `src/pricing.rs::owner`, `tests/control.rs` with its own `mod pricing;` - and `use crate::pricing::owner as dt; assert_eq!(dt(100), 100);`: the - library owner stays `activation_unknown`; the call does not credit it. + and `use crate::pricing::owner as dt; assert_eq!(dt(100), 100);`: no credit. 2. `src/pricing/inner.rs::owner`, a unit test with `use crate::pricing::inner::owner as dt; assert_eq!(dt(100), 90);`: `direct_owner_call`, observed `["100"]`. @@ -135,23 +112,15 @@ read the test's assertions and the owner's body. ## Test Mapping -- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_an_integration_test_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_nested_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_owner_is_a_mod_rs_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_sibling_module_declares_the_alias_name_then_owner_keeps_related_test` -- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_module_declares_the_alias_name_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_local_function_shadows_it_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_inline_module_shadows_the_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_root_imports_the_library_root_then_owner_gets_no_related_test` -- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_target_imports_a_library_module_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_package_imports_its_own_module_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_crate_root_redirects_the_module_with_path_then_owner_gets_no_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test` -- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_integration_test_when_owner_is_imported_under_an_alias_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_scoped_binding_shadows_it_then_owner_takes_no_value_from_it`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_free_and_an_associated_owner_share_the_name_then_associated_takes_no_value`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it` -- `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test`, `crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_flat_tuple_pattern_binding`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_nested_tuple_pattern_binding`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_slice_pattern_binding`, `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests::scoped_shadow_sees_a_binding_in_a_later_loop` -- `fixtures/evidence-promotion-honesty-corpus/corpus.json` `report_digest_required` - report fixtures move with the honesty-corpus follow-up. +- `crates/ripr/src/analysis/test_grip_evidence/tests.rs`: the `given_direct_owner_alias_when_*` and `given_integration_test_when_owner_is_imported_under_an_alias_*` cases, including the library-child, bin-only-child and binary-child crate-root controls. +- `crates/ripr/src/analysis/extract/shadow.rs::fact_authority_tests`: the `scoped_shadow_*` cases. ## Implementation Mapping - `crates/ripr/src/analysis/test_grip_evidence/related_tests.rs`: - `match_direct_owner_call`, `direct_owner_alias_module_matches`, - `crate_relative_alias_shares_compilation_unit`. + `match_direct_owner_call`, `direct_owner_alias_module_matches`, `crate_relative_alias_shares_compilation_unit`, `crate_root_file_for_test`. - `crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs`: - `direct_owner_import_aliases`, `normalize_direct_owner_module_path`, - `local_function_shadows_call`, `alias_binding_shadows_call`, - `alias_spelling_binds_other_owner`, `local_module_shadows_alias`. + `direct_owner_import_aliases`, `normalize_direct_owner_module_path`, `local_function_shadows_call`, `alias_binding_shadows_call`, `alias_spelling_binds_other_owner`, `local_module_shadows_alias`. - `crates/ripr/src/analysis/classify/const_flow.rs`: `ModuleScopes::declaration_shadows_import`. From 7d3163344d3ea3b50da49bf0b3b3d8dca05caeda Mon Sep 17 00:00:00 2001 From: EffortlessSteven <15812269+EffortlessSteven@users.noreply.github.com> Date: Sat, 14 Nov 2026 01:45:29 -0500 Subject: [PATCH 12/14] fix(analysis): close four alias false-credit paths - A nearer unsupported import (self::/super::/::) that binds the alias now shadows the outer owner alias instead of being discarded. - A closure parameter inside a macro token tree is recorded as a scoped binding, so the callback call no longer credits the owner. - The enclosing test function's own parameters (e.g. #[rstest]) shadow the alias for the whole body. - Two #[cfg]-gated mod declarations with different #[path] targets fail closed instead of resolving to the first declaration. Each control fails on the pre-repair code and passes restored. --- .ripr/traceability.d/RIPR-SPEC-0442.toml | 5 ++ crates/ripr/src/analysis/syntax/ra.rs | 48 ++++++++++ .../test_grip_evidence/related_tests.rs | 11 ++- .../related_tests/context.rs | 59 +++++++++++-- .../src/analysis/test_grip_evidence/tests.rs | 88 +++++++++++++++++++ 5 files changed, 203 insertions(+), 8 deletions(-) diff --git a/.ripr/traceability.d/RIPR-SPEC-0442.toml b/.ripr/traceability.d/RIPR-SPEC-0442.toml index de7e319c910..b2b99df4ade 100644 --- a/.ripr/traceability.d/RIPR-SPEC-0442.toml +++ b/.ripr/traceability.d/RIPR-SPEC-0442.toml @@ -31,6 +31,10 @@ tests = [ "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_library_child_module_imports_the_crate_root_owner_then_owner_keeps_related_test", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_bin_only_child_module_imports_its_crate_root_owner_then_owner_keeps_related_test", "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_binary_child_module_imports_the_binary_root_then_library_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_nearer_unsupported_import_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_closure_in_a_macro_token_tree_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_the_test_function_parameter_shadows_it_then_owner_gets_no_related_test", + "crates/ripr/src/analysis/test_grip_evidence/tests.rs::given_direct_owner_alias_when_a_cfg_gated_module_has_two_paths_then_owner_gets_no_related_test", ] fixtures = [ "fixtures/evidence-promotion-honesty-corpus/corpus.json", @@ -40,6 +44,7 @@ code = [ "crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs", "crates/ripr/src/analysis/classify/const_flow.rs", "crates/ripr/src/analysis/extract/shadow.rs", + "crates/ripr/src/analysis/syntax/ra.rs", ] outputs = [ "docs/specs/RIPR-SPEC-0442-aliased-owner-import-credit.md", diff --git a/crates/ripr/src/analysis/syntax/ra.rs b/crates/ripr/src/analysis/syntax/ra.rs index bfa4b3d4346..39f3182506b 100644 --- a/crates/ripr/src/analysis/syntax/ra.rs +++ b/crates/ripr/src/analysis/syntax/ra.rs @@ -1408,6 +1408,54 @@ fn collect_body_shadow_facts( } } } + // The enclosing function's own parameters shadow the alias for its whole + // body; a `#[rstest]` fixture parameter named like the alias is the + // compiling case (#14508 review). + if let (Some(body), Some(params)) = (function.body(), function.param_list()) { + for param in params.params() { + push_scoped_binding_facts( + &mut let_bindings, + param.pat(), + body.syntax().text_range().end(), + line_of, + fn_line, + ); + } + } + // A closure inside a macro token tree is not a `ClosureExpr` node, so the + // AST walk above cannot see its parameters. Read each token tree's masked + // text for `|params|` pairs and bind each name for the rest of the tree + // (fail closed, #14508 review). + for tree in function + .syntax() + .descendants() + .filter(|node| node.kind() == SyntaxKind::TOKEN_TREE) + { + let text = crate::analysis::extract::mask_comments_and_strings(&tree.text().to_string()); + let last = TextSize::from(u32::from(tree.text_range().end()).saturating_sub(1)); + let (Some(line), Some(end_line)) = ( + line_of(tree.text_range().start()).checked_sub(fn_line), + line_of(last).checked_sub(fn_line), + ) else { + continue; + }; + let mut rest = text.as_str(); + while let Some(open) = rest.find('|') { + let after = &rest[open + 1..]; + let Some(close) = after.find('|') else { break }; + for segment in after[..close].split(',') { + let name_part = segment.split(':').next().unwrap_or(segment); + for name in extract_pattern_words(name_part) { + let_bindings.push(LetBindingFact { + line, + scope_end: Some(end_line), + name, + }); + } + } + rest = &after[close + 1..]; + } + } let_bindings.sort_by(|left, right| left.line.cmp(&right.line).then(left.name.cmp(&right.name))); let_bindings.dedup(); (nested_fn_names, let_bindings) diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index 7b6c26002b0..e0ada69d63d 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -633,10 +633,17 @@ fn resolve_module_chain(index: &RustIndex, root_file: &Path, module_path: &str) let mut current = root_file.to_path_buf(); for segment in module_path.split('/') { let facts = index.files().get(¤t)?; - let declaration = facts + let mut matching = facts .module_declarations .iter() - .find(|declaration| declaration.name == segment)?; + .filter(|declaration| declaration.name == segment); + let declaration = matching.next()?; + // Two `#[cfg]`-gated declarations of one module with different + // `#[path]` targets compile different files per configuration; no + // static single target exists, so fail closed (#14508 review). + if matching.any(|other| other.path_target != declaration.path_target) { + return None; + } let dir = current.parent()?; current = match &declaration.path_target { ModulePathTarget::Default => { diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs index 14b3cd4bb82..b666ec09b56 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests/context.rs @@ -3342,12 +3342,6 @@ pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases( let scan = scan_lexical_use_statements(source); let mut aliases: BTreeMap = BTreeMap::new(); for statement in &scan.statements { - let Some(parsed) = collect_direct_owner_import_aliases_from_use(&statement.text) else { - continue; - }; - if parsed.is_empty() { - continue; - } let end_line = scan.end_line(statement); let mut nested_module_lines = nested_module_line_ranges( &scan.line_module_depths, @@ -3360,6 +3354,34 @@ pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases( nested_module_lines.push((*line, *line)); } } + let Some(parsed) = collect_direct_owner_import_aliases_from_use(&statement.text) else { + // A nearer import that binds the same spelling but names an + // unsupported module path (`self::`, `super::`, `::`) still + // shadows an outer owner alias. Record a binding that can never + // match an owner module, so the call fails closed (#14508 review). + for alias in use_statement_alias_names(&statement.text) { + aliases + .entry(alias) + .or_insert_with(|| ScopedImportedFunctionAlias { + bindings: Vec::new(), + }) + .bindings + .push(ScopedImportedFunctionBinding { + module_path: String::new(), + crate_relative: false, + name: String::new(), + start_line: statement.start_line, + end_line, + module_depth: statement.module_depth, + nested_module_lines: nested_module_lines.clone(), + end_is_partial: scan.end_is_partial(end_line), + }); + } + continue; + }; + if parsed.is_empty() { + continue; + } for (alias, imported) in parsed { aliases .entry(alias) @@ -3382,6 +3404,31 @@ pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases( aliases } +/// The `as` aliases a `use` statement binds, even when its module path is not +/// a supported owner path. A nearer unsupported import still shadows an outer +/// owner alias (#14508 review). A non-aliased import binds the imported name +/// itself, which the bare-call reading already handles. +fn use_statement_alias_names(import: &str) -> Vec { + let import = import.trim_end_matches(';').trim(); + let items: Vec<&str> = match import.split_once("::{") { + Some((_, rest)) => rest + .strip_suffix('}') + .map(|body| body.split(',').map(str::trim).collect()) + .unwrap_or_default(), + None => import + .rsplit_once("::") + .map(|(_, item)| vec![item.trim()]) + .unwrap_or_default(), + }; + items + .into_iter() + .filter(|item| !item.contains("::") && !item.contains('{') && !item.contains('}')) + .filter_map(|item| item.split_once(" as ").map(|(_, alias)| alias.trim())) + .filter(|alias| !alias.is_empty()) + .map(str::to_string) + .collect() +} + pub(in crate::analysis::test_grip_evidence) fn direct_owner_import_aliases_by_file( index: &RustIndex, ) -> ScopedDirectFunctionImportAliasesByFile { diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 798996872bd..935275ab66b 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -25021,3 +25021,91 @@ fn field_write_facts_with_tail( .map(|fact| fact.value.clone()) .collect()) } + +/// Build the lib+integration-test fixture and read the alias seam's evidence. +fn alias_evidence_for_lib_and_test( + lib_src: &str, + tests_src: &str, +) -> Result { + let root = alias_workspace_with_files( + "lib_proptest", + &[("src/lib.rs", lib_src), ("tests/boundary.rs", tests_src)], + )?; + evidence_for_alias_seam( + &root, + &[ + PathBuf::from("src/lib.rs"), + PathBuf::from("tests/boundary.rs"), + ], + "src/lib.rs", + ) +} + +#[test] +fn given_direct_owner_alias_when_a_nearer_unsupported_import_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: `use self::rival::different as dt;` is not a supported + // owner path, but it still binds `dt` nearer than the outer owner alias. + let lib_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::owner as dt;\n\nmod rival {\n pub fn different(_amount: i32) -> i32 { 0 }\n}\n\n#[test]\nfn shadowed() {\n use self::rival::different as dt;\n assert_eq!(dt(100), 0);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(dt(100), 90);\n}\n"; + let evidence = alias_evidence_for_lib_and_test(lib_src, tests_src)?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_closure_in_a_macro_token_tree_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a closure inside an assertion macro is an opaque token + // tree, so its parameter is not a `ClosureExpr` node. + let lib_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::owner as dt;\n\n#[test]\nfn shadowed() {\n assert_eq!((|dt: fn(i32) -> i32| dt(100))(fake), 0);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(dt(100), 90);\n}\n"; + let evidence = alias_evidence_for_lib_and_test(lib_src, tests_src)?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_the_test_function_parameter_shadows_it_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: a `#[rstest]` fixture parameter named like the alias + // shadows it for the whole body. + let lib_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let tests_src = "use lib_proptest::owner as dt;\n\n#[rstest]\nfn shadowed(dt: fn(i32) -> i32) {\n assert_eq!(dt(100), 0);\n}\n\n#[test]\nfn genuine() {\n assert_eq!(dt(100), 90);\n}\n"; + let evidence = alias_evidence_for_lib_and_test(lib_src, tests_src)?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["genuine"]); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_a_cfg_gated_module_has_two_paths_then_owner_gets_no_related_test() +-> Result<(), String> { + // #14508 review: two `#[cfg]`-gated `mod pricing;` declarations with + // different `#[path]` targets compile different files per configuration. + let lib_src = "#[cfg(unix)]\n#[path = \"pricing_unix.rs\"]\nmod pricing;\n#[cfg(windows)]\n#[path = \"pricing_windows.rs\"]\nmod pricing;\n\n#[cfg(test)]\nmod tests {\n use crate::pricing::owner as dt;\n\n #[test]\n fn shadowed() {\n assert_eq!(dt(100), 90);\n }\n}\n"; + let unix_src = + "pub fn owner(amount: i32) -> i32 { if amount >= 100 { amount - 10 } else { amount } }\n"; + let windows_src = "pub fn owner(amount: i32) -> i32 { amount }\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", lib_src), + ("src/pricing_unix.rs", unix_src), + ("src/pricing_windows.rs", windows_src), + ], + )?; + let evidence = evidence_for_alias_seam( + &root, + &[ + PathBuf::from("src/lib.rs"), + PathBuf::from("src/pricing_unix.rs"), + PathBuf::from("src/pricing_windows.rs"), + ], + "src/pricing_unix.rs", + )?; + assert!(direct_owner_call_tests(&evidence).is_empty()); + Ok(()) +} From cd89bfe615a7f2e5643438e1a29f01e5db3af68e Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:13:39 -0500 Subject: [PATCH 13/14] fix(analysis): fail closed on aliased owner lookalikes (#14508) --- .../src/analysis/classify/related_tests.rs | 7 +- .../test_grip_evidence/related_tests.rs | 5 +- .../src/analysis/test_grip_evidence/tests.rs | 90 ++++++++++++++++++- 3 files changed, 99 insertions(+), 3 deletions(-) diff --git a/crates/ripr/src/analysis/classify/related_tests.rs b/crates/ripr/src/analysis/classify/related_tests.rs index 56960f34374..c8141eccc1c 100644 --- a/crates/ripr/src/analysis/classify/related_tests.rs +++ b/crates/ripr/src/analysis/classify/related_tests.rs @@ -8122,7 +8122,12 @@ pub(in crate::analysis) fn call_text_spells_bare_free_call(text: &str, name: &st .map(|(at, _)| at) .filter(|&at| is_free_function_call_at(&masked, at, name)) .peekable(); - calls.peek().is_some() && calls.all(|at| !masked[..at].trim_end().ends_with("::")) + calls.peek().is_some() + && calls.all(|at| { + let qualifier = masked[..at].trim_end(); + let qualifier = qualifier.strip_suffix("r#").unwrap_or(qualifier); + !qualifier.trim_end().ends_with("::") + }) } /// The text a captured call named like `owner` contributes as an owner diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index e0ada69d63d..b7e07e9c8cb 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -517,7 +517,10 @@ fn direct_owner_alias_module_matches( } match rest { None => owner_is_crate_root, - Some(rest) => rest.strip_suffix("/mod").unwrap_or(rest) == owner_module, + Some(rest) => owner_file.is_some_and(|owner_file| { + resolve_module_chain(index, Path::new(&owner_root), rest) + .is_some_and(|resolved| normalize_path(&resolved) == normalize_path(owner_file)) + }), } } diff --git a/crates/ripr/src/analysis/test_grip_evidence/tests.rs b/crates/ripr/src/analysis/test_grip_evidence/tests.rs index 935275ab66b..d1bf2ca4704 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/tests.rs @@ -23098,7 +23098,7 @@ fn given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_ta // otherwise accepts. The relation still credits the owner through the bare // alias, but the qualified call's arguments must not become its values. let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; - let rival_src = "pub fn discounted_total(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let rival_src = "pub fn dt(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; let tests_src = "use lib_proptest::discounted_total as dt;\nuse lib_proptest::rival;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n assert_eq!(rival::dt(7, 7), 777);\n}\n"; let root = alias_workspace_root("lib_proptest")?; fs::write(root.join("src/lib.rs"), prod_src).map_err(|error| error.to_string())?; @@ -23143,6 +23143,94 @@ fn given_direct_owner_alias_when_a_qualified_call_shares_the_alias_then_owner_ta Ok(()) } +#[test] +fn given_direct_owner_alias_when_a_raw_escaped_qualified_call_shares_the_alias_then_owner_takes_no_value_from_it() +-> Result<(), String> { + // The raw identifier is still module-qualified, so its arguments belong + // to the rival and not to the genuine bare alias call beside it. + let prod_src = "pub mod rival;\n\npub fn discounted_total(amount: i32, threshold: i32) -> i32 { if amount >= threshold { amount - 10 } else { amount } }\n"; + let rival_src = "pub fn r#dt(_amount: i32, _threshold: i32) -> i32 { 777 }\n"; + let tests_src = "use lib_proptest::discounted_total as dt;\nuse lib_proptest::rival;\n\n#[test]\nfn mixed() {\n assert_eq!(dt(100, 100), 90);\n assert_eq!(rival::r#dt(7, 7), 777);\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ("src/lib.rs", prod_src), + ("src/rival.rs", rival_src), + ("tests/boundary.rs", tests_src), + ], + )?; + let files = [ + "src/lib.rs", + "src/rival.rs", + "tests/boundary.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/lib.rs")?; + assert_eq!(direct_owner_call_tests(&evidence), vec!["mixed"]); + assert!( + evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "a qualified `rival::r#dt(..)` must not lend the owner its argument: {:?}", + evidence.observed_values + ); + assert!( + evidence + .observed_values + .iter() + .any(|fact| fact.value == "100"), + "the bare alias call still supplies the owner's activation value: {:?}", + evidence.observed_values + ); + Ok(()) +} + +#[test] +fn given_direct_owner_alias_when_external_import_crate_root_redirects_with_path_then_original_owner_gets_no_related_test() +-> Result<(), String> { + // `lib_proptest::pricing` resolves to the redirected file as rustc does, + // not to the original physical `src/pricing.rs` owner. + let owner = "pub fn owner(amount: i32) -> i32 {\n if amount >= 100 { amount - 10 } else { amount }\n}\n"; + let root = alias_workspace_with_files( + "lib_proptest", + &[ + ( + "src/lib.rs", + "#[path = \"redirected_pricing.rs\"]\npub mod pricing;\n", + ), + ("src/pricing.rs", owner), + ( + "src/redirected_pricing.rs", + "pub fn owner(amount: i32) -> i32 { amount }\n", + ), + ( + "tests/boundary.rs", + "use lib_proptest::pricing::owner as dt;\n\n#[test]\nfn redirected() {\n assert_eq!(dt(7), 7);\n}\n", + ), + ], + )?; + let files = [ + "src/lib.rs", + "src/pricing.rs", + "src/redirected_pricing.rs", + "tests/boundary.rs", + ] + .map(PathBuf::from); + let evidence = evidence_for_alias_seam(&root, &files, "src/pricing.rs")?; + assert!( + direct_owner_call_tests(&evidence).is_empty() + && evidence + .observed_values + .iter() + .all(|fact| fact.value != "7"), + "the redirected import must not credit the original physical owner: {:?} / {:?}", + evidence.related_tests, + evidence.observed_values + ); + Ok(()) +} + #[test] fn given_two_indexed_packages_when_alias_names_a_sibling_package_then_owner_gets_no_related_test() -> Result<(), String> { From 2d8b5f52b3b2dfc425abfe284f35cda0da78ea0c Mon Sep 17 00:00:00 2001 From: "Steven Zimmerman, CPA" <15812269+EffortlessSteven@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:23:08 -0500 Subject: [PATCH 14/14] fix(analysis): close alias shadowing edge cases --- .../ripr/src/analysis/classify/const_flow.rs | 7 ++++ .../src/analysis/classify/const_flow/tests.rs | 14 +++++++ crates/ripr/src/analysis/extract/shadow.rs | 41 ++++++++++++++++++- .../test_grip_evidence/related_tests.rs | 13 ++++-- 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/crates/ripr/src/analysis/classify/const_flow.rs b/crates/ripr/src/analysis/classify/const_flow.rs index 3fab2b9c6a3..5d1d14be406 100644 --- a/crates/ripr/src/analysis/classify/const_flow.rs +++ b/crates/ripr/src/analysis/classify/const_flow.rs @@ -236,6 +236,13 @@ impl ModuleScopes { else { return false; }; + // A non-module block (`impl`, `fn`, or a bare block) around the + // declaration is not a module scope. Dropping that marker would make + // an associated or block-local function look like a root declaration + // and falsely shadow a genuine import (#14508 review). + if declared.iter().any(Option::is_none) { + return false; + } let declared = declared .iter() .filter_map(|name| name.as_deref()) diff --git a/crates/ripr/src/analysis/classify/const_flow/tests.rs b/crates/ripr/src/analysis/classify/const_flow/tests.rs index 57d2925f5d5..1a14625d0b0 100644 --- a/crates/ripr/src/analysis/classify/const_flow/tests.rs +++ b/crates/ripr/src/analysis/classify/const_flow/tests.rs @@ -431,6 +431,20 @@ fn modules_with_the_same_chain_share_a_scope() { assert!(super::shares_module_scope(source, 2, &[3])); } +#[test] +fn an_associated_function_does_not_shadow_a_module_level_import() { + let source = "use crate::owner as dt;\n\ + impl Rival {\n\ + fn dt() {}\n\ + }\n\ + #[test]\n\ + fn genuine() { dt(); }\n"; + assert!( + !super::module_scopes(source).declaration_shadows_import(3, 0, 6), + "an associated function cannot rebind the module-level `dt` import" + ); +} + /// Run the whole decision on a one-file crate: its production functions that /// name `LIMIT` are the readers and its `#[test]`s the related tests. fn decide(tests: &str, old: &str, new: &str) -> Result, String> { diff --git a/crates/ripr/src/analysis/extract/shadow.rs b/crates/ripr/src/analysis/extract/shadow.rs index c8f882f39aa..f2ee5884ae3 100644 --- a/crates/ripr/src/analysis/extract/shadow.rs +++ b/crates/ripr/src/analysis/extract/shadow.rs @@ -399,10 +399,26 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool let Some(open) = body[start..].find('(') else { continue; }; - let Some(close) = body[start + open..].find(')') else { + let parameter_list = &body[start + open..]; + let mut depth = 0usize; + let mut close = None; + for (offset, byte) in parameter_list.bytes().enumerate() { + match byte { + b'(' => depth += 1, + b')' => { + depth = depth.saturating_sub(1); + if depth == 0 { + close = Some(offset); + break; + } + } + _ => {} + } + } + let Some(close) = close else { continue; }; - let params = &body[start + open + 1..start + open + close]; + let params = ¶meter_list[1..close]; if pattern_contains_word(params, callee) { return true; } @@ -413,6 +429,11 @@ pub(crate) fn test_body_scoped_shadow_at_line(body: &str, callee: &str) -> bool /// Whether any `` occurrence names `callee`, so a later /// loop or `if let` binding is not invisible (#14508 review). fn any_between_keywords(body: &str, start: &str, end: &str, callee: &str) -> bool { + // Rust tokens may be separated by newlines as well as spaces. Only this + // boolean lexical query needs the normalized text; callers retain the + // original body and its offsets (#14508 review). + let normalized = body.split_whitespace().collect::>().join(" "); + let body = normalized.as_str(); let mut search = 0usize; while let Some(offset) = body[search..].find(start) { let pattern_start = search + offset + start.len(); @@ -693,6 +714,22 @@ mod fact_authority_tests { } } + #[test] + fn scoped_shadow_sees_a_loop_binding_with_newline_before_in() { + assert!(test_body_scoped_shadow_at_line( + "for owner\nin items { owner(1); }", + "owner" + )); + } + + #[test] + fn scoped_shadow_sees_a_parameter_after_nested_parentheses() { + assert!(test_body_scoped_shadow_at_line( + "fn helper(pair: (u8, u8), owner: fn(i32, i32) -> i32) { owner(1, 2); }", + "owner" + )); + } + #[test] fn scoped_shadow_sees_a_flat_tuple_pattern_binding() { assert!(test_body_scoped_shadow_at_line( diff --git a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs index b7e07e9c8cb..f47f710244c 100644 --- a/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs +++ b/crates/ripr/src/analysis/test_grip_evidence/related_tests.rs @@ -517,10 +517,15 @@ fn direct_owner_alias_module_matches( } match rest { None => owner_is_crate_root, - Some(rest) => owner_file.is_some_and(|owner_file| { - resolve_module_chain(index, Path::new(&owner_root), rest) - .is_some_and(|resolved| normalize_path(&resolved) == normalize_path(owner_file)) - }), + Some(rest) => { + rest.strip_suffix("/mod").unwrap_or(rest) == owner_module + && owner_file.is_some_and(|owner_file| { + resolve_module_chain(index, Path::new(&owner_root), rest) + .is_some_and(|resolved| { + normalize_path(&resolved) == normalize_path(owner_file) + }) + }) + } } }