Repository navigation
fix(engine): honor row policies and prepare Similar in background #2480
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
43fbe5b
20bd5cd
fc74b0b
7a2e61c
827e68f
2f5047a
4a75ecd
ba65cf9
fa60c48
58d0427
5547427
9200970
3e6cd0e
86033f8
a69fa29
53ea95a
6c46efd
b12e8a5
62cc4cb
66f21b7
2e1b38c
6dd20d5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -800,29 +800,105 @@ pub fn profile_fields(ds: &Dataset) -> Vec<FieldProfile> { | |||||||||
| .collect() | ||||||||||
| } | ||||||||||
|
|
||||||||||
| /// Ranked rows and the count of other resident rows lacking a finite value in at least one | ||||||||||
| /// compared field. Per-field standardization still uses every finite value in that field. | ||||||||||
| #[derive(Debug)] | ||||||||||
| pub struct Similarity { | ||||||||||
| pub matches: Vec<(usize, f64)>, | ||||||||||
| pub skipped: usize, | ||||||||||
| } | ||||||||||
|
|
||||||||||
| /// Rows ranked by how close their numeric attributes are to a row's (z-scored Euclidean | ||||||||||
| /// distance over `fields`), nearest first, excluding the row itself. | ||||||||||
| pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Vec<(usize, f64)> { | ||||||||||
| let stats: Vec<(f64, f64)> = fields | ||||||||||
| .iter() | ||||||||||
| .map(|fi| { | ||||||||||
| let vals: Vec<f64> = (0..ds.features.len()).filter_map(|r| ds.value(r, *fi).as_f64()).filter(|v| v.is_finite()).collect(); | ||||||||||
| let m = vals.iter().sum::<f64>() / vals.len().max(1) as f64; | ||||||||||
| let sd = (vals.iter().map(|v| (v - m).powi(2)).sum::<f64>() / vals.len().max(1) as f64).sqrt(); | ||||||||||
| (m, if sd > 0.0 { sd } else { 1.0 }) | ||||||||||
| }) | ||||||||||
| .collect(); | ||||||||||
| let vec_of = |r: usize| -> Option<Vec<f64>> { | ||||||||||
| fields.iter().zip(&stats).map(|(fi, (m, sd))| ds.value(r, *fi).as_f64().filter(|v| v.is_finite()).map(|v| (v - m) / sd)).collect() | ||||||||||
| /// distance over `fields`), nearest first, excluding the row itself. Counts progress and checks | ||||||||||
| /// Cancel between rows and within wide vectors. The stable library sort is one indivisible step, | ||||||||||
| /// checked immediately before and after; equal-distance rows keep their original order. | ||||||||||
| /// Non-finite standardization statistics are refused before ranking any candidates. | ||||||||||
| pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result<Similarity, String> { | ||||||||||
| use crate::control; | ||||||||||
| control::begin(ds.features.len().saturating_mul(fields.len().saturating_mul(3).saturating_add(1))); | ||||||||||
| let mut stats = Vec::with_capacity(fields.len()); | ||||||||||
| for fi in fields { | ||||||||||
| let mut vals = Vec::new(); | ||||||||||
| for r in 0..ds.features.len() { | ||||||||||
| control::check()?; | ||||||||||
| control::advance(1); | ||||||||||
| if let Some(v) = ds.value(r, *fi).as_f64().filter(|v| v.is_finite()) { | ||||||||||
| vals.push(v); | ||||||||||
| } | ||||||||||
| } | ||||||||||
| // Result's sum delegates to the same f64 reduction as the original iterator sum; | ||||||||||
| // cancellation changes neither its order nor its identity value. | ||||||||||
| let m = vals | ||||||||||
| .iter() | ||||||||||
| .map(|v| { | ||||||||||
| control::check()?; | ||||||||||
| control::advance(1); | ||||||||||
| Ok(*v) | ||||||||||
| }) | ||||||||||
| .sum::<Result<f64, control::Cancelled>>()? | ||||||||||
| / vals.len().max(1) as f64; | ||||||||||
| let sd = (vals | ||||||||||
| .iter() | ||||||||||
| .map(|v| { | ||||||||||
| control::check()?; | ||||||||||
| control::advance(1); | ||||||||||
| Ok((v - m).powi(2)) | ||||||||||
| }) | ||||||||||
| .sum::<Result<f64, control::Cancelled>>()? | ||||||||||
| / vals.len().max(1) as f64) | ||||||||||
| .sqrt(); | ||||||||||
| if !m.is_finite() || !sd.is_finite() { | ||||||||||
| return Err("a compared field's values are too large to standardize (its mean or spread overflows)".into()); | ||||||||||
| } | ||||||||||
| stats.push((m, if sd > 0.0 { sd } else { 1.0 })); | ||||||||||
| } | ||||||||||
| let mut vector_pace = control::Pace::default(); | ||||||||||
| let mut vec_of = |r: usize| -> Result<Option<Vec<f64>>, control::Cancelled> { | ||||||||||
| fields | ||||||||||
| .iter() | ||||||||||
| .zip(&stats) | ||||||||||
| .map(|(fi, (m, sd))| { | ||||||||||
| if vector_pace.stop(1) { | ||||||||||
| return Err(control::Cancelled); | ||||||||||
| } | ||||||||||
| Ok(ds.value(r, *fi).as_f64().filter(|v| v.is_finite()).map(|v| (v - m) / sd)) | ||||||||||
| }) | ||||||||||
| .collect() | ||||||||||
| }; | ||||||||||
| let Some(target) = vec_of(row) else { return Vec::new() }; | ||||||||||
| let mut out: Vec<(usize, f64)> = (0..ds.features.len()) | ||||||||||
| .filter(|r| *r != row) | ||||||||||
| .filter_map(|r| vec_of(r).map(|v| (r, v.iter().zip(&target).map(|(a, b)| (a - b).powi(2)).sum::<f64>().sqrt()))) | ||||||||||
| .collect(); | ||||||||||
| let Some(target) = vec_of(row)? else { | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Silent unusable result: a reference row with a missing value returns an empty ranking (confidence: high). When the reference row has a null or non-finite value in any compared field, this returns The same applies to candidates: rows with a missing value in any field are dropped silently at line 821 ( Minimal fix for the reference case:
Suggested change
For candidates, count the skipped rows and return the count to
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 2f5047aff refuses a reference missing a finite compared value and counts skipped incomplete candidates, including with |
||||||||||
| return Err("the reference row needs a finite numeric value in every compared field".into()); | ||||||||||
| }; | ||||||||||
| let mut distance_pace = control::Pace::default(); | ||||||||||
| let mut out = Vec::new(); | ||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Performance (low confidence, mostly pre-existing): every candidate's distance is kept in
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The established sort and distance loop are unchanged. A top-k/parallel implementation needs its own measured work while preserving reduction order, stable ties, cancellation and scratch accounting; it is left for the release quality pass, as in the earlier summary disposition. |
||||||||||
| let mut skipped = 0; | ||||||||||
| for r in 0..ds.features.len() { | ||||||||||
| control::check()?; | ||||||||||
| control::advance(1); | ||||||||||
| if r != row { | ||||||||||
| let Some(v) = vec_of(r)? else { | ||||||||||
| skipped += 1; | ||||||||||
| continue; | ||||||||||
| }; | ||||||||||
| let distance = v | ||||||||||
| .iter() | ||||||||||
| .zip(&target) | ||||||||||
| .map(|(a, b)| { | ||||||||||
| if distance_pace.stop(1) { | ||||||||||
| return Err(control::Cancelled); | ||||||||||
| } | ||||||||||
| Ok((a - b).powi(2)) | ||||||||||
| }) | ||||||||||
| .sum::<Result<f64, control::Cancelled>>()? | ||||||||||
| .sqrt(); | ||||||||||
| out.push((r, distance)); | ||||||||||
| } | ||||||||||
| } | ||||||||||
| control::check()?; | ||||||||||
| out.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); | ||||||||||
| control::check()?; | ||||||||||
| out.truncate(n); | ||||||||||
| out | ||||||||||
| control::finish(); | ||||||||||
| Ok(Similarity { matches: out, skipped }) | ||||||||||
| } | ||||||||||
|
|
||||||||||
| fn radius_scale(at: Coord) -> f64 { | ||||||||||
|
|
@@ -1533,8 +1609,8 @@ mod tests { | |||||||||
| assert_eq!(random_points(&poly, &[0], 25, 7), pts, "reproducible"); | ||||||||||
| let p = profile_fields(&ds); | ||||||||||
| assert_eq!((p[0].min, p[0].max, p[0].distinct), (Some(1.0), Some(5.0), 2)); | ||||||||||
| let sim = similar(&ds, 0, &[0], 2); | ||||||||||
| assert_eq!(sim[0].0, 1); | ||||||||||
| let sim = similar(&ds, 0, &[0], 2).unwrap(); | ||||||||||
| assert_eq!(sim.matches[0].0, 1); | ||||||||||
| let near = within(&ds, &rows, Coord::new(0.5, 0.001), 500.0); | ||||||||||
| assert_eq!(near.first().map(|x| x.0), Some(0)); | ||||||||||
| } | ||||||||||
|
|
||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1219,15 +1219,16 @@ mod tests { | |
| fn a_querys_credentials_stay_out_of_duckdbs_arguments() { | ||
| let dir = tempfile::tempdir().unwrap(); | ||
| let exe = recording_duckdb(dir.path()); | ||
| let secret = "X-Amz-Signature=0123456789abcdef-synthetic"; | ||
| let secret = "dummy"; | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Unexplained weakening of a credential-leak test (confidence: high that it is unexplained; medium that it weakens the check). The secret was changed from a distinctive synthetic signature to the common word If the original value was flagged by secret scanning, keep the test specific with a different synthetic token that no other argument contains, for example
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The former long fixture tripped publication scanning; it was replaced with an obvious dummy value, with no scanner configuration changes. In 3e6cd0e47, the test now compares the entire recorded argument list against the expected init-file path and
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| let sql = format!("SELECT * FROM read_parquet('https://bucket.example/data.parquet?{secret}')\nWHERE 'line;\n.shell no' <> ''"); | ||
| let script = | ||
| format!("{} CREATE TEMP TABLE r AS SELECT * FROM query({});", prelude(dir.path(), None, false).unwrap(), literal(&sql)); | ||
| run_with_stand_in(&exe, dir.path(), &script).unwrap(); | ||
| let args = std::fs::read_to_string(dir.path().join("args.txt")).unwrap(); | ||
| let input = std::fs::read_to_string(dir.path().join("input.txt")).unwrap(); | ||
| assert!(!args.contains(secret) && !args.contains("read_parquet"), "{args}"); | ||
| assert!(args.lines().any(|a| a == "-bail") && !args.lines().any(|a| a == "-c"), "{args}"); | ||
| // A path may contain the dummy value too. Only these arguments are allowed; all SQL, | ||
| // including its test credential, must arrive on standard input instead. | ||
| assert_eq!(args.lines().collect::<Vec<_>>(), ["-init", dir.path().join("init.sql").to_str().unwrap(), "-bail"]); | ||
| assert_eq!(input, script, "the whole script, as it was"); | ||
| } | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug (medium confidence, arithmetic unchanged from before this PR, reached by finite inputs): the mean and spread are plain
f64sums of squares. A field holding a finite sentinel near the top of the range, such as the common nodata value-1.7976931348623157e308, makes(v - m).powi(2)overflow, sosdbecomesinfand every z-score collapses to 0. For example, the values1, 2, -1.7976931348623157e308rank rows 1 and 2 with distance 0 and report no notice. Ifmitself overflows, z becomes NaN, and the NaN distances reach the sort at line 849 (partial_cmp(..).unwrap_or(Equal)is not a total order). The reference check added here does not catch it, because it tests the raw value rather than z.AGENTS.md says an unusable result is an error. Refusing when the standardization is not finite leaves every normal input bit-identical:
A regression test with a
1e308-scale value should assert this error. Usinga.1.total_cmp(&b.1)at line 849 would also keep the sort total for any future NaN.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reproduced through
Session::run: the sentinel case returned zero distances and an overflowing mean returned null distances, both without notices. 4a75ecdcd refuses non-finite mean/spread before any selection change. The command regression covers both overflow paths, preserved selection/error delivery, and a quiet clean retry. The updated probe preserves 2,142 finite-statistics rankings bit for bit and refuses 333 overflowing-statistics cases plus 189 unusable references. Targeted checks and full fork CI pass.