Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog.d/helper-behind-tested-caller-precision-12900.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!-- section: Fixed -->
- A private helper whose only related tests share its file or a name token no
longer reads `reachable_unrevealed` when a chain of production callers leads
to a function the tests do call (a helper behind a public entry). Those
nearby tests are not shown to run the helper, so their missing assertion is
no evidence the change goes unnoticed; the finding reads `weakly_exposed`
instead. On the five-crate cargo-mutants corpus this removes 61 false
positive gaps; 8 boundary misses on helpers the tests do run move to
`weakly_exposed` with them (#12900).
129 changes: 129 additions & 0 deletions crates/ripr/src/analysis/classifier/evidence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

/// Evidence line for a finding kept out of `reachable_unrevealed` because its
/// related tests are proximity guesses and a production caller chain leads to
/// a function tests call (#12900).
const PROXIMITY_REACH_OF_TESTED_CALLER_NOTE: &str = "Related tests share only a file or name token with this function, and a production caller that tests call leads to it; their missing assertion does not show the change goes unnoticed";

mod side_flip;
mod tuple_match;

Expand Down Expand Up @@ -58,6 +63,15 @@ pub(in crate::analysis) struct ClassifiedProbeEvidence {
/// change. An owner with an unresolved caller chain keeps its
/// shape-based class even when no related test was found.
pub(in crate::analysis) reach_ruled_out: bool,
/// Reach is `Weak` only because every related test is a proximity guess
/// (same file, name token, module), the owner is not a trait-impl method,
/// and a chain of production callers leads to a function tests call
/// (`owner_tested_through_production_caller`). The guessed tests are not
/// shown to run the owner, so their missing assertion is not evidence
/// that the change goes unnoticed: tests may run the owner through that
/// caller chain (a private helper behind a public entry).
/// `classify` keeps such a finding out of `reachable_unrevealed` (#12900).
pub(in crate::analysis) proximity_reach_of_named_owner: bool,
/// #11870: a related test reads the field this probe's assignment writes
/// with a weak relational check, under the one start policy the seam side
/// asks too (`assigned_field_weak_read_start`). Only then does a weakly
Expand Down Expand Up @@ -1821,6 +1835,34 @@ impl ClassifiedProbeEvidence {
};
let mut evidence =
evidence_summaries([&reach, &infect, &propagate, &observe, &discriminate]);
// #12900: computed last, on the final stages, and only when the shared
// decision reads `reachable_unrevealed` on weak, proximity-only
// reach, so the caller walk runs for those alone and the evidence
// line never sits beside an infection/propagation unknown class.
let proximity_reach_of_named_owner = reach.state == StageState::Weak
&& observe.state == StageState::No
&& classify(
&reach,
&infect,
&propagate,
&observe,
&discriminate,
context.probe,
) == ExposureClass::ReachableUnrevealed
&& !context.related_tests.is_empty()
&& context.related_tests.iter().all(|(_, reason)| {
*reason != RelationReason::SeamCalleeCall && !reason.establishes_reach(true)
})
&& context.owner_fn.is_some_and(|owner| {
!crate::analysis::classify::is_trait_impl_method(owner)
&& crate::analysis::classify::owner_tested_through_production_caller(
owner,
context.index,
)
});
if proximity_reach_of_named_owner {
evidence.push(PROXIMITY_REACH_OF_TESTED_CALLER_NOTE.to_string());
}
// Disclose a refused related assertion whenever the refusal can
// matter: the reveal is not fully established. See
// `preferred_refusal_note` for which one.
Expand Down Expand Up @@ -2042,6 +2084,7 @@ impl ClassifiedProbeEvidence {
observe,
discriminate,
reach_ruled_out,
proximity_reach_of_named_owner,
assigned_field_weakly_read,
assertion_refusal,
refusals_are_analyzer_limits,
Expand Down Expand Up @@ -2267,6 +2310,13 @@ impl ClassifiedProbeEvidence {
&self.discriminate,
probe,
);
// #12900: a "reached but not noticed" claim needs a test shown to run
// the owner. When only proximity guesses are related and something
// else names the owner, the missing assertion was read on tests that
// may never call it, so the gap is unconfirmed, not revealed.
if class == ExposureClass::ReachableUnrevealed && self.proximity_reach_of_named_owner {
return ExposureClass::WeaklyExposed;
}
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
// RIPR-SPEC-0228: a field assignment is credited only through a
// confirmed read of that field after the owner call. A weak reading
// there means ripr could not tell whether a related assertion reads
Expand Down Expand Up @@ -2965,6 +3015,85 @@ mod tests {
Ok(())
}

/// #12900: a private helper whose only related test is a same-file guess
/// reads `weakly_exposed`, with the evidence line, when a production
/// caller that a test calls leads to it; with no such caller it stays
/// `reachable_unrevealed` and carries no line.
#[test]
fn proximity_tests_beside_a_helper_behind_a_tested_caller_are_not_a_revealed_gap()
-> Result<(), String> {
use crate::domain::ExposureClass;

let run = |test_body: &str| -> Result<(ExposureClass, bool), String> {
let source = format!(
"pub fn parse(x: u32) -> u32 {{\n step(x)\n}}\n\nfn step(x: u32) -> u32 {{\n x + 1\n}}\n\n#[test]\nfn nearby() {{\n {test_body}\n}}\n"
);
let path = PathBuf::from("src/lib.rs");
let facts = crate::analysis::syntax::ra::summarize_file_with_parser(&path, &source)?;
let mut index = RustIndex::from_owned(crate::analysis::facts::OwnedRustIndex {
functions: facts.functions.clone(),
tests: facts.tests.clone(),
files: [(path, facts)].into_iter().collect(),
..Default::default()
});
crate::analysis::facts::compose_fixture_source_roles(
&mut index,
std::path::Path::new(""),
);
let owner = index
.functions()
.iter()
.find(|function| function.name == "step")
.ok_or("missing owner")?;
let test = index
.tests()
.iter()
.find(|test| test.name == "nearby")
.ok_or("missing test")?;
let probe = Probe {
id: ProbeId("probe:helper-behind-caller".to_string()),
location: SourceLocation::new("src/lib.rs", 6, 5),
owner: Some(owner.id.clone()),
family: ProbeFamily::ReturnValue,
delta: DeltaKind::Value,
before: Some("x + 2".to_string()),
after: Some("x + 1".to_string()),
expression: "x + 1".to_string(),
expected_sinks: Vec::new(),
required_oracles: Vec::new(),
};
let context = ProbeContext::new(
&probe,
Some(owner),
vec![(test, RelationReason::SameTestFile)],
false,
&index,
true,
);
let evidence = ClassifiedProbeEvidence::gather(
&context,
&probe.expression,
&crate::analysis::classify::TransitiveReachIndex::new(context.index),
);
let noted = evidence
.evidence
.iter()
.any(|line| line == super::PROXIMITY_REACH_OF_TESTED_CALLER_NOTE);
Ok((evidence.classify(&probe), noted))
};
assert_eq!(
run("let _ = parse(2);")?,
(ExposureClass::WeaklyExposed, true),
"a test calls `parse`, which calls the helper"
);
assert_eq!(
run("let _ = 2;")?,
(ExposureClass::ReachableUnrevealed, false),
"no test calls `parse`, so the gap stays revealed and unannotated"
);
Ok(())
}

/// #8084: a sibling element field built from a block may exit before the
/// test reaches its assertion, so `return_value` on the array must not
/// stay exposed through the generic oracle path.
Expand Down
1 change: 1 addition & 0 deletions crates/ripr/src/analysis/classifier/finding.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,6 +1266,7 @@ mod tests {
observe: yes.clone(),
discriminate: yes,
reach_ruled_out: true,
proximity_reach_of_named_owner: false,
assigned_field_weakly_read: false,
assertion_refusal: None,
refusals_are_analyzer_limits: false,
Expand Down
3 changes: 2 additions & 1 deletion crates/ripr/src/analysis/classify/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ pub(in crate::analysis) use reach::take_external_docs_parse_count;
pub(in crate::analysis) use reach::{
UnseenReachNames, includes_external_docs_with, invokes_opaque_macro, is_proximity_only,
is_trait_impl_method, names_identifier_outside_fn_definition, owner_may_be_reached_unseen,
owner_runs_through_language_dispatch, reach_evidence, relation_establishes_reach,
owner_runs_through_language_dispatch, owner_tested_through_production_caller, reach_evidence,
relation_establishes_reach,
};
pub(in crate::analysis) use receiver_unestablished::{
mark_receiver_unestablished, withhold_receiver_unestablished_gap,
Expand Down
175 changes: 175 additions & 0 deletions crates/ripr/src/analysis/classify/reach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,98 @@ fn imported_names(source: &str, keep_root: impl Fn(&str) -> bool) -> Vec<String>
names
}

/// How many production caller hops [`owner_tested_through_production_caller`]
/// walks up from the owner before giving up.
const PRODUCTION_CALLER_HOPS: usize = 6;

/// A caller name that more production functions define than this is not
/// followed as a link. Three keeps a small overload family on one path
/// (semver's `matches` on `VersionReq`, `Comparator` and the free helper all
/// lead to `matches_impl`), while a common name such as `new`, `get` or `len`
/// cannot stand in for a path. Measured on the five-crate cargo-mutants
/// corpus (#12900): at 1 and 2 the rule removes 21 and 28 false gaps; at 3 it
/// removes 61 and moves 8 boundary misses on `matches_*` helpers, which the
/// tests do run, to `weakly_exposed`; above 3 it changes 6 more.
const MAX_LINK_DEFINITIONS: usize = 3;

/// Whether a chain of production callers (at most
/// [`PRODUCTION_CALLER_HOPS`] hops) leads from `owner` to a function that a
/// test, or a test-side helper, calls by name.
///
/// This is a name-level lookalike of transitive reach: it never establishes
/// reach and never credits an oracle. It only answers whether tests that
/// merely sit near the owner are the whole story. When the owner sits behind
/// a production caller that tests do call (a private helper behind a public
/// entry), a missing assertion on the nearby tests is no evidence that the
/// change goes unnoticed (#12900).
///
/// `CallFact::name` is the bare callee identifier, so a link is matched by
/// name. A caller whose name more than [`MAX_LINK_DEFINITIONS`] production
/// functions define (`new`, `get`, `len`) is not followed: a same-named call
/// could be any of them, and following it would let a common name stand for a
/// real path. A caller no test calls (an unexercised sibling) does not count
/// either.
pub(in crate::analysis) fn owner_tested_through_production_caller(
owner: &FunctionSummary,
index: &RustIndex,
) -> bool {
use super::super::facts::FunctionSourceRole;
if owner.name.is_empty() {
return false;
}
let production = || {
index
.functions()
.iter()
.filter(|function| function.source_role == FunctionSourceRole::Production)
};
let mut definitions: HashMap<&str, usize> = HashMap::new();
for function in production() {
*definitions.entry(function.name.as_str()).or_default() += 1;
}
let tested = |name: &str| {
index
.tests()
.iter()
.any(|test| test.calls.iter().any(|call| call.name == name))
|| index.functions().iter().any(|function| {
function.source_role != FunctionSourceRole::Production
&& function.calls.iter().any(|call| call.name == name)
})
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
};
let mut seen: BTreeSet<&str> = BTreeSet::from([owner.name.as_str()]);
let mut frontier: Vec<&str> = vec![owner.name.as_str()];
for _ in 0..PRODUCTION_CALLER_HOPS {
let mut next: Vec<&str> = Vec::new();
for function in production() {
let name = function.name.as_str();
if function.id == owner.id
|| name.is_empty()
|| seen.contains(name)
|| definitions.get(name).copied().unwrap_or(0) > MAX_LINK_DEFINITIONS
{
continue;
}
if function
.calls
.iter()
.any(|call| frontier.contains(&call.name.as_str()))
{
seen.insert(name);
next.push(name);
}
}
if next.iter().any(|name| tested(name)) {
return true;
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
}
if next.is_empty() {
return false;
}
frontier = next;
}
false
}

/// Parser-backed owner ids carry their impl segment
/// (`src/lib.rs::impl Display for Money::fmt`).
pub(in crate::analysis) fn is_trait_impl_method(owner: &FunctionSummary) -> bool {
Expand Down Expand Up @@ -937,6 +1029,89 @@ mod tests {
use std::collections::BTreeMap;
use std::path::PathBuf;

fn parsed_index(files: &[(&str, &str)]) -> Result<RustIndex, String> {
use crate::analysis::syntax::{RaRustSyntaxAdapter, RustSyntaxAdapter};
let mut index = RustIndex::default();
for (path, source) in files {
let facts = RaRustSyntaxAdapter.summarize_file(Path::new(path), source)?;
let functions = facts.functions.clone();
let tests = facts.tests.clone();
index.insert_file_only(PathBuf::from(path), facts);
index.extend_functions(functions);
index.extend_tests(tests);
}
Ok(index)
}

fn owner_named<'a>(index: &'a RustIndex, name: &str) -> Result<&'a FunctionSummary, String> {
index
.functions()
.iter()
.find(|function| function.name == name)
.ok_or_else(|| format!("owner {name} indexed"))
}

/// #12900: a private helper behind a public entry that a test calls is
/// tested through that caller chain, at any hop up to the bound.
#[test]
fn helper_behind_a_tested_public_entry_is_tested_through_a_caller() -> Result<(), String> {
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
let lib = "pub fn parse(s: &str) -> u32 { step(s) }\n\
fn step(s: &str) -> u32 { digits(s) + 1 }\n\
fn digits(s: &str) -> u32 { s.len() as u32 }\n";
let test = "#[test]\nfn parses() { assert!(parse(\"ab\") > 0); }\n";
let index = parsed_index(&[("src/lib.rs", lib), ("tests/parse.rs", test)])?;
for owner in ["step", "digits"] {
assert!(
owner_tested_through_production_caller(owner_named(&index, owner)?, &index),
"{owner} is reached through the tested entry `parse`"
);
}
Ok(())
}

/// The negative: a caller that no test calls (an unexercised sibling, the
/// `compile_time_marker_test_no_observation` shape) gives no such chain,
/// and neither does an owner with no production caller at all.
#[test]
fn unexercised_sibling_caller_or_no_caller_is_not_a_tested_chain() -> Result<(), String> {
let lib = "struct W(u32);\n\
impl W {\n fn peek(&self) -> u32 { self.get() }\n fn get(&self) -> u32 { self.0 }\n}\n\
pub fn lonely() -> u32 { 1 }\n";
let test = "#[test]\nfn unrelated() { assert_eq!(2, 2); }\n";
let index = parsed_index(&[("src/lib.rs", lib), ("tests/t.rs", test)])?;
for owner in ["get", "lonely"] {
assert!(
!owner_tested_through_production_caller(owner_named(&index, owner)?, &index),
"{owner} has no production caller that tests call"
);
}
Ok(())
}

/// A caller in a test-only module is a test-side lookalike, not a
/// production link, and a caller name that more than
/// `MAX_LINK_DEFINITIONS` production functions define is not followed: a
/// test calling `run` could mean any of them.
#[test]
fn test_module_caller_and_ambiguous_caller_name_are_not_links() -> Result<(), String> {
let lib = "fn helper() -> u32 { 1 }\n\
pub mod a { pub fn run() -> u32 { super::helper() } }\n\
pub mod b { pub fn run() -> u32 { 2 } }\n\
pub mod c { pub fn run() -> u32 { 3 } }\n\
pub mod d { pub fn run() -> u32 { 4 } }\n\
fn lonely() -> u32 { 3 }\n\
#[cfg(test)]\nmod tests {\n fn wrap() -> u32 { super::lonely() }\n #[test]\n fn calls_wrap() { assert_eq!(wrap(), 3); }\n}\n";
let test = "#[test]\nfn runs() { assert!(ripr_fixture::a::run() > 0); }\n";
let index = parsed_index(&[("src/lib.rs", lib), ("tests/run.rs", test)])?;
for owner in ["helper", "lonely"] {
assert!(
!owner_tested_through_production_caller(owner_named(&index, owner)?, &index),
"{owner} must not be tested through an ambiguous or test-side caller"
);
}
Ok(())
}

#[test]
fn given_no_related_tests_when_building_reach_evidence_then_stage_is_no() {
let evidence = reach_evidence(&[], None, || false);
Expand Down
Loading
Loading