Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
94 changes: 87 additions & 7 deletions crates/ripr/src/analysis/rust_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,13 +178,45 @@ pub fn find_owner_function<'a>(
file: &Path,
line: usize,
) -> Option<&'a FunctionSummary> {
index.files.get(file).and_then(|summary| {
let owner_in = |summary: &'a FileFacts| {
summary
.functions
.iter()
.filter(|f| f.start_line <= line && line <= f.end_line)
.max_by_key(|f| f.start_line)
})
};
if let Some(summary) = index.files.get(file) {
return owner_in(summary);
}
// Repo seams normalize their file identity to `/` separators
// (#3469 family) while index keys keep the producing host's
// separators. On the opposite-separator host the component-wise
// lookup above misses (`src\pricing.rs` is a single component on
// Linux), so fall back to matching normalized key forms. The scan
// only runs after the direct lookup missed, so native-separator
// inputs keep the exact-lookup cost. Non-UTF-8 paths fail closed:
// lossy replacement characters can collapse distinct names into
// one form and attribute the wrong owner, so neither side of the
// comparison may pass through lossy conversion.
let target = file.to_str()?.replace('\\', "/");
index
.files
.iter()
.find_map(|(key, summary)| {
let key_text = key.to_str()?;
(key_text.replace('\\', "/") == target).then_some(summary)
})
.and_then(owner_in)
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
}

/// `/`-separated display form of a path, independent of the host's
/// native separator. Used by [`is_test_file`] to judge the normalized
/// form; lossy text is safe here because replacement characters can
/// never become separators. The [`find_owner_function`] fallback does
/// NOT use this helper — identity attribution must not pass through
/// lossy conversion.
fn normalize_display(path: &Path) -> String {
path.to_string_lossy().replace('\\', "/")
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
}

pub fn changed_nodes_for_lines(
Expand All @@ -208,17 +240,65 @@ pub fn changed_nodes_for_lines(
}

pub(crate) fn is_test_file(path: &Path) -> bool {
path.starts_with("tests")
|| path
.to_string_lossy()
.replace('\\', "/")
.contains("/tests/")
let normalized = normalize_display(path);
normalized == "tests" || normalized.starts_with("tests/") || normalized.contains("/tests/")
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn find_owner_function_resolves_normalized_seam_paths() {
let facts = summarize_file(
PathBuf::from("src\\pricing.rs"),
"fn apply_discount(amount: i32, threshold: i32) -> i32 { \
if amount >= threshold { amount - 10 } else { amount } }\n"
.to_string(),
);
let mut index = RustIndex::default();
index.files.insert(PathBuf::from("src\\pricing.rs"), facts);
// Repo seams carry `/`-normalized file identity; on Linux this is
// not component-equal to the `\`-separator index key, so the
// direct lookup misses and the normalized fallback must resolve.
let owner = find_owner_function(&index, Path::new("src/pricing.rs"), 1);
assert_eq!(owner.map(|f| f.name.as_str()), Some("apply_discount"));
}

#[test]
fn is_test_file_judges_foreign_separator_forms_like_native_ones() {
assert!(is_test_file(Path::new("tests\\pricing_test.rs")));
assert!(is_test_file(Path::new("tests/pricing_test.rs")));
assert!(is_test_file(Path::new("crates\\demo\\tests\\main.rs")));
assert!(!is_test_file(Path::new("src\\pricing.rs")));
// A `tests`-prefixed sibling directory name stays production.
assert!(!is_test_file(Path::new("testing\\pricing.rs")));
}

#[test]
#[cfg(unix)]
fn find_owner_function_fails_closed_on_non_utf8_fallback() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let facts = summarize_file(
PathBuf::from(OsStr::from_bytes(b"src/pricing_\xff.rs")),
"fn apply_discount(amount: i32) -> i32 { amount }\n".to_string(),
);
let mut index = RustIndex::default();
index.files.insert(
PathBuf::from(OsStr::from_bytes(b"src/pricing_\xff.rs")),
facts,
);
// A query whose lossy rendering collides with the indexed key
// must not attribute the owner through lossy text: the fallback
// requires valid UTF-8 on both sides.
let colliding = Path::new(OsStr::from_bytes(b"src\\pricing_\xfe.rs"));
assert_eq!(
find_owner_function(&index, colliding, 1).map(|f| f.name.as_str()),
None
);
}

#[test]
fn finds_tests_and_assertions() {
let file = summarize_file(
Expand Down
35 changes: 26 additions & 9 deletions crates/ripr/src/analysis/test_grip_evidence/related_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,7 @@ impl OwnerContext {
let name = owner_fn.map(|f| f.name.as_str()).unwrap_or("").to_string();
let name_lower = name.to_ascii_lowercase();
let owner_file = owner_fn.map(|f| f.file.as_path());
let file_stem = owner_file
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str())
.unwrap_or("")
.to_string();
let file_stem = owner_file.map(normalized_file_stem).unwrap_or_default();
let module_path = owner_file.and_then(|file| module_path_for_index(context.index, file));
let prefix = owner_fn.and_then(|f| package_prefix(&f.file));
let fixture_names = owner_file
Expand Down Expand Up @@ -569,10 +565,10 @@ pub(super) fn assertion_targets_seam(test: &TestSummary, tokens: &[String]) -> b

#[cfg(test)]
pub(super) fn same_test_file(test_file: &Path, owner_stem: &str) -> bool {
let stem = match test_file.file_stem().and_then(|s| s.to_str()) {
Some(s) => s,
None => return false,
};
let stem = normalized_file_stem(test_file);
if stem.is_empty() {
return false;
}
if stem == owner_stem {
return true;
}
Expand Down Expand Up @@ -772,6 +768,27 @@ pub(super) fn normalize_path(path: &Path) -> String {
.to_string()
}

/// Extract a source-file stem after normalizing separators from either
/// host. Grip inputs can carry paths produced on a different platform
/// than the host resolving the association (#3469); a foreign separator
/// makes [`std::path::Path::file_stem`] treat an entire relative path as
/// one file name, so same-test-file lookups miss on exactly one host.
/// Non-UTF-8 paths fail closed: lossy replacement characters could
/// collapse distinct file names into one stem and fabricate a
/// same-test-file relation (the #3545 `cross_host_stem` guard).
pub(super) fn normalized_file_stem(path: &Path) -> String {
let Some(text) = path.to_str() else {
return String::new();
};
let unified = text.replace('\\', "/");
let file = unified.rsplit('/').next().unwrap_or_default();
Path::new(file)
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or_default()
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
.to_string()
}

pub(super) fn package_prefix(path: &Path) -> Option<String> {
let normalized = normalize_path(path);
if let Some(rest) = normalized.strip_prefix("crates/")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,9 @@ impl<'a> CompactGripContext<'a> {
.or_default()
.push(test_index);
}
if let Some(stem) = test.file.file_stem().and_then(|stem| stem.to_str()) {
tests_by_file_stem
.entry(stem.to_string())
.or_default()
.push(test_index);
let stem = normalized_file_stem(&test.file);
if !stem.is_empty() {
tests_by_file_stem.entry(stem).or_default().push(test_index);
}
for token in import_affinity_tokens(&code_lines) {
tests_by_import_token
Expand Down
93 changes: 93 additions & 0 deletions crates/ripr/src/analysis/test_grip_evidence/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10230,6 +10230,99 @@ fn given_same_module_test_without_direct_call_when_related_tests_are_ranked_then
Ok(())
}

#[test]
fn given_foreign_separator_paths_when_grip_associates_then_same_test_file_still_matches()
-> Result<(), String> {
// #3469: a path carrying the other platform's separator (facts
// materialized on Windows, analyzed on Linux, or vice versa) broke
// the SameTestFile relation in two stacked places: the owner lookup
// compared the seam's `/`-normalized file identity against raw
// host-separator index keys (`Path` component equality only
// absorbs this on `\`-native hosts), and both association stems
// were derived with the host-native `Path::file_stem`. Every
// separator combination must associate; the test body stays free
// of owner/discriminator identifiers so SameTestFile is the only
// reason that can fire.
let prod_src = "pub fn apply_discount(amount: i32, threshold: i32) -> i32 \
{ if amount >= threshold { amount - 10 } else { amount } }\n";
let test_src = "#[test] fn bounds_smoke() { assert_eq!(1, 1); }\n";
let combinations = [
("src/pricing.rs", "tests/pricing_test.rs"),
("src\\pricing.rs", "tests\\pricing_test.rs"),
("src/pricing.rs", "tests\\pricing_test.rs"),
("src\\pricing.rs", "tests/pricing_test.rs"),
];
for (owner_path, test_path) in combinations {
let files: Vec<(PathBuf, &str)> = vec![
(PathBuf::from(owner_path), prod_src),
(PathBuf::from(test_path), test_src),
];
let index = index_from_files(&files)?;
let seams = inventory_seams_from_index(&[PathBuf::from(owner_path)], &index);
let predicate = seams
.iter()
.find(|s| s.kind() == SeamKind::PredicateBoundary)
.ok_or_else(|| "predicate seam present".to_string())?;
let evidence = evidence_for_seam(predicate, &index);
let context = CompactGripContext::new(&index);
let owner_fn = crate::analysis::rust_index::find_owner_function(
&index,
predicate.file(),
predicate.display_line(),
);
let ctx_tests: Vec<String> = context
.tests
.iter()
.map(|t| t.test.file.to_string_lossy().to_string())
.collect();
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved
assert!(
evidence
.related_tests
.iter()
.any(|grip| grip.relation_reason == RelationReason::SameTestFile),
"same-test-file association must hold for owner `{owner_path}` / test \
`{test_path}`; got {:?} | diag: index_files={:?} index_tests={} \
ctx_tests={ctx_tests:?} stem_keys={:?} seam_file={:?} seam_line={} \
owner={owner_fn:?} owner_stem_norm={:?} owner_stem_native={:?} \
test_stem_norm={:?} test_stem_native={:?}",
evidence.related_tests,
index.files.keys().collect::<Vec<_>>(),
index.tests.len(),
context.tests_by_file_stem.keys().collect::<Vec<_>>(),
predicate.file(),
predicate.display_line(),
normalized_file_stem_to_string(Path::new(owner_path)),
Path::new(owner_path)
.file_stem()
.map(|s| s.to_string_lossy().to_string()),
normalized_file_stem_to_string(Path::new(test_path)),
Path::new(test_path)
.file_stem()
.map(|s| s.to_string_lossy().to_string()),
);
}
Ok(())
}

fn normalized_file_stem_to_string(path: &Path) -> String {
super::related_tests::normalized_file_stem(path)
}
Comment thread
EffortlessSteven marked this conversation as resolved.
Resolved

#[test]
#[cfg(unix)]
fn given_non_utf8_stems_when_grip_associates_then_lossy_collision_fails_closed() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
// Two distinct non-UTF-8 names can share one lossy rendering;
// deriving stems through lossy conversion would fabricate a
// same-test-file relation between unrelated entities, so stem
// extraction must fail closed instead.
let first = Path::new(OsStr::from_bytes(b"tests/pricing_\xff.rs"));
let second = Path::new(OsStr::from_bytes(b"tests/pricing_\xfe.rs"));
assert_eq!(normalized_file_stem(first), "");
assert_eq!(normalized_file_stem(second), "");
}

// -- helper coverage ---------------------------------------------
//
// Targeted unit tests for the small private helpers introduced by
Expand Down
Loading