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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ are scoped or reviewed.

### Fixed

- `ripr check` is faster on large repositories, with byte-identical JSON on
12 real commits of tokio, vite, Django and ripr. TypeScript test selection
walked the directory tree for `package.json` twice per owner and test;
a vite commit went from 6.7 s to 3.2 s. Rust classification no longer
reparses the owner's file per probe unless the file could admit the
derived tuple slice, and computes each related test's value facts once
per owner instead of once per probe; a ripr commit went
from 11.1 s to 8.1 s.
- Security: Rust source discovery skips symlinked `.rs` entries, as the
Python and TypeScript readers already did. A cloned repository or pull
request that committed `src/zero.rs -> /dev/zero` made `ripr check` read
Expand Down
3 changes: 2 additions & 1 deletion crates/ripr/src/analysis/classifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ pub(in crate::analysis) fn classify_probe_with_candidate_index(
workspace_complete,
)
.with_helper_chain(helper_chain)
.with_file_use_statements(candidate_index.file_use_statements());
.with_file_use_statements(candidate_index.file_use_statements())
.with_test_value_facts(candidate_index.test_value_facts());
let reveal_expression = parser_expression_for_probe(
index,
&probe.location.file,
Expand Down
9 changes: 5 additions & 4 deletions crates/ripr/src/analysis/classifier/evidence.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::analysis::classify::{
ProbeContext, PropagationWitnessV1, activation_evidence, classify, confidence_score,
current_path_witness, infection_evidence, local_flow_sinks, owner_may_be_reached_unseen,
package_prefix, propagation_evidence_with_witness, reach_evidence,
ProbeContext, PropagationWitnessV1, activation_evidence_with_value_facts, classify,
confidence_score, current_path_witness, infection_evidence, local_flow_sinks,
owner_may_be_reached_unseen, package_prefix, propagation_evidence_with_witness, reach_evidence,
reveal_evidence_with_expression,
};
use crate::domain::*;
Expand Down Expand Up @@ -43,14 +43,15 @@ impl ClassifiedProbeEvidence {
let flow_sinks = local_flow_sinks(context.probe, context.owner_fn);
let propagation_witness = current_path_witness(context.probe, &flow_sinks)
.map(PropagationWitnessDiagnostic::from_witness);
let activation = activation_evidence(
let activation = activation_evidence_with_value_facts(
context.probe,
context.owner_fn,
&test_summaries,
&flow_sinks,
context.helper_chain.as_ref(),
context.index,
context.workspace_complete,
context.test_value_facts,
);
let infect = infection_evidence(context.probe, &test_summaries, &activation);
let valid_witness = propagation_witness
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ pub(super) fn admits(context: &ProbeContext<'_>) -> bool {
fn admits_inner(context: &ProbeContext<'_>) -> Option<bool> {
let owner = context.owner_fn?;
let facts = find_file_facts(context.index, &owner.file)?;
// `canonical_owner_roles` requires these exact parameter names, so a
// file that never spells one cannot admit. Checking before the parse
// skips a whole-file reparse per probe (profiled: ~16% of a `ripr
// check` on this repository) without changing any verdict.
if !CANONICAL_PARAMETER_NAMES
.iter()
.all(|name| facts.source.contains(name))
{
return Some(false);
}
let root = parsed(&facts.source)?;
let function = named_function(&root, &owner.name)?;
if !canonical_owner_roles(&function)? {
Expand All @@ -41,17 +51,20 @@ fn admits_inner(context: &ProbeContext<'_>) -> Option<bool> {
top_level_projection_observes(&test_function, &owner.name, &result)
}

/// The parameter names `canonical_owner_roles` pins with `has_exact_parameter`.
const CANONICAL_PARAMETER_NAMES: [&str; 3] = ["receipt_request_ids", "request_set", "task_id"];

/// First-slice authority is the canonical helper boundary only. Merely finding
/// any owner parameter or any `.contains` call cannot assign semantic roles.
fn canonical_owner_roles(function: &ast::Fn) -> Option<bool> {
if !canonical_receipt_iteration(function)?
|| !has_exact_parameter(
function,
"receipt_request_ids",
CANONICAL_PARAMETER_NAMES[0],
"&BTreeMap<String,Vec<String>>",
)?
|| !has_exact_parameter(function, "request_set", "&BTreeSet<String>")?
|| !has_exact_parameter(function, "task_id", "&str")?
|| !has_exact_parameter(function, CANONICAL_PARAMETER_NAMES[1], "&BTreeSet<String>")?
|| !has_exact_parameter(function, CANONICAL_PARAMETER_NAMES[2], "&str")?
{
return Some(false);
}
Expand Down
200 changes: 199 additions & 1 deletion crates/ripr/src/analysis/classify/activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use super::super::rust_index::{FunctionSummary, TestSummary};
use super::text::{delimited_contents_at, enum_variant_values, exact_error_variant};
use crate::domain::*;

#[cfg(test)]
pub(in crate::analysis) fn activation_evidence(
probe: &Probe,
owner_fn: Option<&FunctionSummary>,
Expand All @@ -10,10 +11,42 @@ pub(in crate::analysis) fn activation_evidence(
helper_chain: Option<&super::helper_transfer::HelperChain>,
index: &crate::analysis::rust_index::RustIndex,
workspace_complete: bool,
) -> ActivationEvidence {
activation_evidence_with_value_facts(
probe,
owner_fn,
related_tests,
flow_sinks,
helper_chain,
index,
workspace_complete,
None,
)
}

/// `activation_evidence`, reading each related test's owner-independent
/// value facts through `value_facts` when the classifier supplies its
/// run-scoped memo.
#[allow(
clippy::too_many_arguments,
reason = "activation_evidence's inputs plus the optional run-scoped memo"
)]
pub(in crate::analysis) fn activation_evidence_with_value_facts(
probe: &Probe,
owner_fn: Option<&FunctionSummary>,
related_tests: &[&TestSummary],
flow_sinks: &[FlowSinkFact],
helper_chain: Option<&super::helper_transfer::HelperChain>,
index: &crate::analysis::rust_index::RustIndex,
workspace_complete: bool,
value_facts: Option<&TestValueFacts>,
) -> ActivationEvidence {
let mut observed_values = related_tests
.iter()
.flat_map(|test| value_facts_for_test(test, owner_fn))
.flat_map(|test| match value_facts {
Some(memo) => memo.facts_for(index, test, owner_fn),
None => value_facts_for_test(test, owner_fn),
})
.collect::<Vec<_>>();
observed_values.extend(observed_discriminator_values(
probe,
Expand Down Expand Up @@ -63,6 +96,88 @@ struct ParameterValue {
text: String,
}

/// `value_facts_for_test` per (related test, owner), computed at most once
/// for as long as the memo lives.
///
/// The facts depend only on the test and the owner, never on the probe, and
/// every probe in an owner relates to largely the same tests, so a
/// classification run shares one memo across its probes (it rides the
/// run-scoped `RelatedTestCandidateIndex`). Entries are keyed by the test's
/// and owner's slots in the index the memo was first queried with; a test
/// or owner that is not an element of that index, or a query against
/// another index, is computed fresh and never cached, so a key can only
/// ever name the same fact values.
/// A related test's slot in `RustIndex::tests` and its owner's slot in
/// `RustIndex::functions` (`None` for an ownerless probe).
type TestOwnerSlot = (usize, Option<usize>);

#[derive(Clone, Debug, Default)]
pub(in crate::analysis) struct TestValueFacts {
index_identity: std::cell::Cell<Option<(usize, usize)>>,
by_slot: std::cell::RefCell<std::collections::BTreeMap<TestOwnerSlot, Vec<ValueFact>>>,
}

impl TestValueFacts {
/// `value_facts_for_test(test, owner_fn)`.
pub(in crate::analysis) fn facts_for(
&self,
index: &crate::analysis::rust_index::RustIndex,
test: &TestSummary,
owner_fn: Option<&FunctionSummary>,
) -> Vec<ValueFact> {
let Some(key) = self.slot_key(index, test, owner_fn) else {
return value_facts_for_test(test, owner_fn);
};
if let Some(facts) = self.by_slot.borrow().get(&key) {
return facts.clone();
}
let facts = value_facts_for_test(test, owner_fn);
self.by_slot.borrow_mut().insert(key, facts.clone());
facts
}

fn slot_key(
&self,
index: &crate::analysis::rust_index::RustIndex,
test: &TestSummary,
owner_fn: Option<&FunctionSummary>,
) -> Option<TestOwnerSlot> {
let identity = (
index.tests.as_ptr() as usize,
index.functions.as_ptr() as usize,
);
match self.index_identity.get() {
None => self.index_identity.set(Some(identity)),
Some(bound) if bound != identity => return None,
Some(_) => {}
}
let test_slot = slot_in(&index.tests, test)?;
let owner_slot = match owner_fn {
Some(owner) => Some(slot_in(&index.functions, owner)?),
None => None,
};
Some((test_slot, owner_slot))
}
}

/// The position of `item` in `items` when `item` is one of its elements
/// (by address, not by value).
fn slot_in<T>(items: &[T], item: &T) -> Option<usize> {
let size = std::mem::size_of::<T>();
if size == 0 {
return None;
}
let offset = (item as *const T as usize).checked_sub(items.as_ptr() as usize)?;
if offset % size != 0 {
return None;
}
let slot = offset / size;
items
.get(slot)
.is_some_and(|candidate| std::ptr::eq(candidate, item))
.then_some(slot)
}

fn value_facts_for_test(test: &TestSummary, owner_fn: Option<&FunctionSummary>) -> Vec<ValueFact> {
let owner_name = owner_fn.map(|owner| owner.name.as_str()).unwrap_or("");
let parameters = owner_fn.map(function_parameters).unwrap_or_default();
Expand Down Expand Up @@ -2707,6 +2822,89 @@ assert_eq!(input.amount, 100);"#
assert!(!facts.iter().any(|fact| fact.value == "AuthError::Ignored"));
}

/// The run-scoped memo answers every (test, owner) query exactly as a
/// fresh `value_facts_for_test` does, on the first (computing) query and
/// every later (cached) one; owners that differ only in their parameter
/// names get different facts, and a test or index the memo is not bound
/// to is computed fresh without being cached.
#[test]
fn test_value_facts_memo_matches_fresh_facts_for_every_test_and_owner() {
let call = |line: usize, text: &str| CallFact {
line,
name: "score".to_string(),
text: text.to_string(),
};
let test = |name: &str, body: &str, calls: Vec<CallFact>| TestSummary {
name: name.to_string(),
file: PathBuf::from("tests/value.rs"),
start_line: 10,
end_line: 14,
body: body.to_string(),
calls,
assertions: vec![oracle_fact(
"assert_eq!(total, 100);",
OracleKind::ExactValue,
)],
literals: Vec::new(),
attrs: Vec::new(),
nested_fn_names: Vec::new(),
let_bindings: Vec::new(),
};
let index = crate::analysis::rust_index::RustIndex {
tests: vec![
test(
"enum_call",
"score(AuthError::RevokedToken);",
vec![call(11, "score(AuthError::RevokedToken);")],
),
test(
"literal_call",
"let rows = [(99, 100)];\nscore(7);",
vec![call(12, "score(7);")],
),
],
functions: vec![
function("pub fn score(error: AuthError) -> u32 {\n 0\n}"),
function("pub fn score(code: AuthError) -> u32 {\n 0\n}"),
],
..crate::analysis::rust_index::RustIndex::default()
};
let memo = TestValueFacts::default();
let owners = [None, Some(&index.functions[0]), Some(&index.functions[1])];
for round in 0..2 {
for test in &index.tests {
for owner in owners {
assert_eq!(
memo.facts_for(&index, test, owner),
value_facts_for_test(test, owner),
"round {round}: {} / {:?}",
test.name,
owner.map(|owner| owner.body.as_str())
);
}
}
}
assert_ne!(
memo.facts_for(&index, &index.tests[1], owners[1]),
memo.facts_for(&index, &index.tests[1], owners[2]),
"the owner's parameter names are part of the facts"
);
let cached = memo.by_slot.borrow().len();
assert_eq!(cached, index.tests.len() * owners.len());

let detached = index.tests[0].clone();
assert_eq!(
memo.facts_for(&index, &detached, owners[1]),
value_facts_for_test(&detached, owners[1])
);
let other_index = index.clone();
assert_eq!(
memo.facts_for(&other_index, &other_index.tests[0], None),
value_facts_for_test(&other_index.tests[0], None)
);
assert_eq!(memo.by_slot.borrow().len(), cached);
}

// #4228: a reversed literal (`100 < amount`) and a local boundary
// (`let limit = 100;`) close at the boundary input and stay open one
// step off it; a local no row can evaluate names no repair at all.
Expand Down
14 changes: 14 additions & 0 deletions crates/ripr/src/analysis/classify/context.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::super::rust_index::{FunctionSummary, RustIndex, TestSummary};
use super::activation::TestValueFacts;
use super::helper_transfer::HelperChain;
use super::reveal::FileUseStatements;
use crate::domain::{Probe, RelationReason};
Expand Down Expand Up @@ -27,6 +28,9 @@ pub(in crate::analysis) struct ProbeContext<'a> {
/// Run-scoped per-file `use` scan, attached by the classifier; `None`
/// (unit-test contexts) scans on every query.
pub file_use_statements: Option<&'a FileUseStatements>,
/// Run-scoped per-(test, owner) value facts, attached by the
/// classifier; `None` (unit-test contexts) computes them per probe.
pub test_value_facts: Option<&'a TestValueFacts>,
}

impl<'a> ProbeContext<'a> {
Expand All @@ -47,6 +51,7 @@ impl<'a> ProbeContext<'a> {
index,
workspace_complete,
file_use_statements: None,
test_value_facts: None,
}
}

Expand All @@ -59,6 +64,15 @@ impl<'a> ProbeContext<'a> {
self
}

/// Share one classification run's per-test value facts across probes.
pub(in crate::analysis) fn with_test_value_facts(
mut self,
test_value_facts: &'a TestValueFacts,
) -> Self {
self.test_value_facts = Some(test_value_facts);
self
}

/// Attach the #3296 helper-transfer chain (computed once by the
/// classifier, where the index is available).
pub(in crate::analysis) fn with_helper_chain(
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 @@ -16,7 +16,8 @@ mod transitive_reach;
mod value_transfer;

pub(in crate::analysis) use activation::{
LocalBoundary, activation_evidence, literal_operand_value, local_boundary,
LocalBoundary, TestValueFacts, activation_evidence_with_value_facts, literal_operand_value,
local_boundary,
};
pub(in crate::analysis) use context::ProbeContext;
pub(in crate::analysis) use decision::{
Expand Down
Loading
Loading