Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
43fbe5b
fix(engine): report topology query fallbacks and preserve row contracts
Mavrick-F Nov 19, 2026
20bd5cd
Merge upstream main into fix/topology-consumer-contracts
Mavrick-F Nov 19, 2026
fc74b0b
fix(engine): keep Similar selection within drawn rows
Mavrick-F Nov 19, 2026
7a2e61c
fix(engine): report Similar selection filter fallback
Mavrick-F Nov 20, 2026
827e68f
fix(engine): compute Similar on the desktop read queue
Mavrick-F Nov 20, 2026
2f5047a
fix(engine): preserve prepared read ownership and completion
Mavrick-F Nov 20, 2026
4a75ecd
fix(engine): retain workflow results and reject numeric overflow
Mavrick-F Nov 20, 2026
ba65cf9
fix(engine): preserve queued Similar intent and Trend output
Mavrick-F Nov 20, 2026
fa60c48
fix(engine): preserve popup clears and newer Similar selections
Mavrick-F Nov 21, 2026
58d0427
fix(engine): keep script admission and Similar pane ownership
Mavrick-F Nov 21, 2026
5547427
Merge main and preserve script fallback and project output boundaries
Mavrick-F Nov 21, 2026
9200970
Merge current main CRS handling into queued topology validation
Mavrick-F Nov 21, 2026
3e6cd0e
fix(engine): accept verified script-created Similar inputs
Mavrick-F Nov 21, 2026
86033f8
fix(ui): clear Similar output on automatic layer fallback
Mavrick-F Nov 21, 2026
a69fa29
Merge main image-grid replay with queued Similar reads
Mavrick-F Nov 21, 2026
53ea95a
fix(engine): retain identities of removed prepared outputs
Mavrick-F Nov 21, 2026
6c46efd
Merge main into topology and Similar review fixes
Mavrick-F Nov 22, 2026
b12e8a5
docs(engine): state topology conversion and cancellation costs
Mavrick-F Nov 22, 2026
62cc4cb
fix(engine): refuse invalid Similar reference and count
Mavrick-F Nov 22, 2026
66f21b7
Merge main with Windows file-revision test repair
Mavrick-F Nov 22, 2026
2e1b38c
fix(engine): preserve history-restored selection during Similar
Mavrick-F Nov 22, 2026
6dd20d5
Merge main release quality fixes into Similar and topology
Mavrick-F Nov 22, 2026
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
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ is out of scope.
- A new background raster command or export, or a tool whose work grows with its input, goes in
the lists in `long_commands` (`crates/engine/src/tests/cancellation.rs`), which both cancel tests
run; the raster and export lists must match the background registries. A read-ahead command
(`reads::prepare`, such as `service.layers` or `edit.previewShapeConversion`) has no registry:
add its call to `long_commands` by hand.
(`reads::prepare`, such as `service.layers`, `edit.previewShapeConversion` or `data.similar`)
has no registry: add its call to `long_commands` by hand.
`long_commands_stop_when_cancelled_while_they_run` fails one that never looks at Cancel;
`cancelling_at_each_check_leaves_nothing_behind` cancels at every check in turn until the command
finishes before reaching it, on small fixtures, failing if one needs 256 or more checks. It
Expand Down
118 changes: 97 additions & 21 deletions crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));

Copy link
Copy Markdown
Contributor

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 f64 sums 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, so sd becomes inf and every z-score collapses to 0. For example, the values 1, 2, -1.7976931348623157e308 rank rows 1 and 2 with distance 0 and report no notice. If m itself 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:

Suggested change
stats.push((m, if sd > 0.0 { sd } else { 1.0 }));
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 }));

A regression test with a 1e308-scale value should assert this error. Using a.1.total_cmp(&b.1) at line 849 would also keep the sort total for any future NaN.

Copy link
Copy Markdown
Member Author

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.

}
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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 Ok(Vec::new()) with no notice. Embeddings then answers {"similar": []} and, with the default select: true, selects only the reference row. AGENTS.md says unusable results are errors, so this should refuse.

The same applies to candidates: rows with a missing value in any field are dropped silently at line 821 (if r != row && let Some(v) = vec_of(r)?), and they also drop out of the standardization statistics at line ~771. The "features skipped" rule asks for a count. This predates the PR, but the PR rewrites this function and the rule says existing silent losses are bugs.

Minimal fix for the reference case:

Suggested change
let Some(target) = vec_of(row)? else {
let Some(target) = vec_of(row)? else {
return Err("the reference row has no finite value in every compared field".into());
};

For candidates, count the skipped rows and return the count to similar.rs so gather can emit one notice.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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 select: false. Null/NaN/infinite reference and candidate regressions pass. The comparison probe verifies 2,475 valid rankings retain identical row order and distance bits, and 189 unusable references are refused. Focused checks and full fork CI pass.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 out (16 bytes per row) and then fully sorted, and only count (at most 1,000) rows survive truncate. For a 50-million-row layer that is roughly 800 MB of candidates plus sort scratch, to return ten rows. A bounded top-k keyed on (distance, row index) gives the same output, because the stable sort already orders equal distances by index, and it needs O(count) memory. The distance pass is also single-threaded; AGENTS.md asks for threads "where practical", and the PR body does not say why that is impractical here. The PR body says ranking scratch keeps "its existing bounds", so this is a note for the author rather than a blocker.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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 {
Expand Down Expand Up @@ -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));
}
Expand Down
2 changes: 2 additions & 0 deletions crates/assistant/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ impl ArchiveBatch {
"map.reloadTiles"
| "map.repairTiles"
| "table.statistics"
| "data.similar"
| "topology.validate"
| "edit.previewShapeConversion"
| "raster.imageGrid"
| "layer.sizeBy"
Expand Down
7 changes: 4 additions & 3 deletions crates/data/src/source/duckdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 "dummy". The assertion !args.contains(secret) now matches any argument containing that word, so it is less specific about what it guards. Nothing in this PR touches DuckDB, and the PR body does not mention the change.

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 synthetic-query-token-7f3a, and say in the PR why the value changed. If the change was intentional, state the reason in the PR description.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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 -bail, and independently checks exact stdin contents. It rejects any SQL argument without relying on a token substring, and passes under a private temporary path containing dummy.

Comment thread
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");
}

Expand Down
Loading
Loading