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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ serde = { version = "1", features = ["derive", "rc"] }
# float_roundtrip: projects must read back the exact coordinates they wrote, or source-edit
# baselines (row hashes) see every reopened row as changed.
serde_json = { version = "1", features = ["raw_value", "float_roundtrip"] }
serde_ignored = "0.1"
sha2 = "0.11"
# JSON Schema of the project file, generated from the saved types (`cargo xtask schema`); only
# behind the `schema` features, so the app, the browser build and the packages never compile it.
Expand Down
42 changes: 36 additions & 6 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,20 +213,42 @@ impl Strict {
}
}

/// Why [`run_strict`] stops the run: the message, and the result of the command when it ran but
/// [`Strict::check`] stopped the run after it (its effect happened, so a `--cmd` prints it).
struct Stop {
/// The result of a command that succeeded before the run was stopped.
kept: Option<Value>,
message: String,
}

impl From<String> for Stop {
/// A failure with no result kept.
fn from(message: String) -> Self {
Stop { kept: None, message }
}
}

impl From<Stop> for String {
/// The message alone, where the result isn't printed (a load, `--save`).
fn from(stop: Stop) -> Self {
stop.message
}
}

/// [`run`], then [`Strict::check`] when the run is strict: after a failure too, as a failed
/// command still reports the losses that outlive its rollback (a counted omission).
fn run_strict(s: &mut Session, strict: Option<&Strict>, id: &str, p: Value) -> Result<Value, String> {
fn run_strict(s: &mut Session, strict: Option<&Strict>, id: &str, p: Value) -> Result<Value, Stop> {
let before = strict.map(|_| s.losses_given().to_vec());
let out = run(s, id, p);
if let (Some(strict), Some(before)) = (strict, before)
&& let Err(said) = strict.check(s, &before, id)
{
return Err(match out {
Err(e) => format!("{e}\n{said}"),
Ok(_) => said,
Err(e) => Stop::from(format!("{e}\n{said}")),
Ok(kept) => Stop { kept: Some(kept), message: said },
});
}
out
Ok(out?)
}

fn is_project(path: &str) -> bool {
Expand Down Expand Up @@ -1293,10 +1315,18 @@ fn cli() -> ExitCode {
Some((id, json)) => (id, serde_json::from_str(json).map_err(|e| format!("{id}: bad JSON: {e}"))?),
None => (c.as_str(), Value::Null),
};
let out = run_strict(&mut s, strict, id, p)?;
if !out.is_null() {
// A command that ran before a strict stop has its result printed too: its
// effect (a file written) happened.
let (out, stop) = match run_strict(&mut s, strict, id, p) {
Ok(out) => (Some(out), None),
Err(stop) => (stop.kept, Some(stop.message)),
};
if let Some(out) = out.filter(|out| !out.is_null()) {
print(&out);
}
if let Some(stop) = stop {
return Err(stop);
}
}
}
if let Some(p) = opt(&args, "--save") {
Expand Down
2 changes: 2 additions & 0 deletions apps/rustgis-cli/tests/integration/strict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ fn a_strict_run_stops_at_a_command_that_loses_data() {
assert!(err.contains("stopped after edit.calculateField") && err.contains("changed.truncated (1 notice)"), "{err}");
let printed = String::from_utf8_lossy(&out.stdout);
assert!(!printed.contains("\"cores\""), "the command after it didn't run: {printed}");
// The command the run stopped after did run: its result is printed before the stop.
assert!(printed.trim_end().ends_with("\"rows\": 2\n}"), "the stopping command's result: {printed}");
}

/// A failed command still reports the losses its rollback can't take back (a counted omission):
Expand Down
72 changes: 65 additions & 7 deletions crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -977,9 +977,10 @@ pub struct Similarity {

/// 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. 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.
/// Cancel between rows and within wide vectors. Only the `n` nearest so far are kept (a heap of
/// `n` entries however many rows the layer has; `data.similar` takes `n` up to 1,000); sorting
/// those at the end 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)));
Expand Down Expand Up @@ -1036,7 +1037,8 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result<S
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();
// The `n` nearest so far, the farthest of them on top: by distance (`total_cmp`), then row.
let mut nearest = std::collections::BinaryHeap::<Ranked>::with_capacity(n.min(ds.features.len()).saturating_add(1));
let mut skipped = 0;
for r in 0..ds.features.len() {
control::check()?;
Expand All @@ -1057,17 +1059,51 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result<S
})
.sum::<Result<f64, control::Cancelled>>()?
.sqrt();
out.push((r, distance));
let ranked = Ranked { distance, row: r };
if nearest.len() < n {
nearest.push(ranked);
} else if let Some(mut top) = nearest.peek_mut()
&& ranked < *top
{
*top = ranked;
}
}
}
control::check()?;
out.sort_by(|a, b| a.1.total_cmp(&b.1));
let out: Vec<(usize, f64)> = nearest.into_sorted_vec().into_iter().map(|r| (r.row, r.distance)).collect();
control::check()?;
out.truncate(n);
control::finish();
Ok(Similarity { matches: out, skipped })
}

/// A candidate of [`similar`], ordered by distance (`total_cmp`), then by row, as a stable sort by
/// distance of rows taken in order leaves them.
#[derive(Clone, Copy, Debug)]
struct Ranked {
distance: f64,
row: usize,
}

impl Ord for Ranked {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.distance.total_cmp(&other.distance).then(self.row.cmp(&other.row))
}
}

impl PartialOrd for Ranked {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}

impl PartialEq for Ranked {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == std::cmp::Ordering::Equal
}
}

impl Eq for Ranked {}

fn radius_scale(at: Coord) -> f64 {
1.0 / at.y.to_radians().cos().max(0.01)
}
Expand Down Expand Up @@ -1770,6 +1806,28 @@ mod tests {
assert!(control.looked() > 0);
}

/// The bounded ranking keeps exactly what a full stable sort by distance, cut to `n`, keeps:
/// the same rows, in the same order (ties by row), with the same distance bits.
#[test]
fn similar_keeps_the_n_nearest_as_a_full_sort_would() {
let mut ds = Dataset::new("v", GeometryType::Point, vec![Field::new("n", FieldType::Integer)]);
// Values 0..5 repeated: many candidates at each distance from row 0.
for i in 0..40 {
ds.push(Some(Geometry::Point(Coord::new(i as f64, 0.0))), vec![Value::Int(i % 5)]);
}
let all = similar(&ds, 0, &[0], usize::MAX).unwrap_or_else(|e| panic!("{e}")).matches;
assert_eq!(all.len(), 39);
let mut reference = all.clone();
reference.sort_by_key(|(row, _)| *row);
reference.sort_by(|a, b| a.1.total_cmp(&b.1));
let bits = |v: &[(usize, f64)]| v.iter().map(|(r, d)| (*r, d.to_bits())).collect::<Vec<_>>();
assert_eq!(bits(&all), bits(&reference));
for n in [0, 1, 5, 8, 12, 39, 100] {
let got = similar(&ds, 0, &[0], n).unwrap_or_else(|e| panic!("{e}")).matches;
assert_eq!(bits(&got), bits(&reference[..n.min(reference.len())]), "n = {n}");
}
}

#[test]
fn routes_points_profiles_and_similarity() {
// A square of roads with a slow diagonal.
Expand Down
23 changes: 21 additions & 2 deletions crates/data/src/ogc/dataset.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ impl DatasetDiscovery {

/// A snapshot of counted omissions, including partial listings and failed traversals.
pub fn notes(&self) -> Vec<String> {
self.omissions.iter().map(|(reason, count)| format!("{count} {reason}")).collect()
self.omissions.iter().map(|(reason, count)| counted(*count, reason)).collect()
}

/// Adds counts for known work abandoned by a terminal discovery error or budget. A document
Expand All @@ -141,7 +141,7 @@ impl DatasetDiscovery {
};
*left.entry(kind).or_default() += count;
}
notes.extend(left.into_iter().map(|(kind, count)| format!("{count} {kind} were left out: dataset discovery stopped")));
notes.extend(left.into_iter().map(|(kind, count)| counted(count, &format!("{kind} were left out: dataset discovery stopped"))));
notes
}

Expand Down Expand Up @@ -605,3 +605,22 @@ impl DatasetDiscovery {
service.layers.push(candidate.layer);
}
}

/// `count` and `reason` ("tileset documents were left out: …"), in the singular for one: the first
/// "s were " of every reason, a regular plural, becomes " was " ("1 tileset document was left out").
fn counted(count: usize, reason: &str) -> String {

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.

counted builds the singular by splitting the human-readable reason at its first "s were ". That is correct for every string in this PR, but it depends on each reason's noun ending in "s" and on no earlier text containing "s were ". The reason strings are free to change wording, as this PR shows when it edits "tileset documents" and similar text. Passing the singular and plural nouns from each call site (the omissions keys and the kind loop in notes / left_over) would make the rule explicit, and a wording change would then fail at compile time instead of quietly producing "1 … were left out".

Confidence: medium that this is latent, not wrong today.

Category: quality

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.

This is left for the release quality pass: every reason string is a regular plural today, and the unit test pins the singular form.

match reason.split_once("s were ") {
Some((what, why)) if count == 1 => format!("1 {what} was {why}"),
_ => format!("{count} {reason}"),
}
}

#[cfg(test)]
mod tests {
#[test]
fn one_omission_is_said_in_the_singular_and_two_in_the_plural() {
let reason = "tileset documents were left out: no usable JSON link";
assert_eq!(super::counted(1, reason), "1 tileset document was left out: no usable JSON link");
assert_eq!(super::counted(2, reason), "2 tileset documents were left out: no usable JSON link");
}
}
15 changes: 4 additions & 11 deletions crates/data/src/raster/cog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -408,17 +408,10 @@ fn read_layout(r: Sparse) -> Result<Parse> {
lost.push(crate::loss::Note::loss(crate::loss::LossCode::AssumedCrs, super::geotiff::NO_EPSG_GEOGRAPHIC));
}
// Its bytes asked for when not read yet, as the other tags' are.
let copyright = match tag(&mut dec, Tag::Copyright)? {
Ok(None) => None,
Ok(Some(v)) => match v.into_string() {
Ok(c) => Some(c.trim().to_string()),
Err(e) => {
lost.push(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out"));
None
}
},
Err(e) => {
lost.push(format!("its Copyright tag: it can't be read ({e}), so it is left out"));
let copyright = match super::geotiff::copyright_of(tag(&mut dec, Tag::Copyright)?) {
Ok(c) => c,
Err(said) => {
lost.push(said);
None
}
};
Expand Down
10 changes: 9 additions & 1 deletion crates/data/src/raster/geotiff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,15 @@ pub(crate) const NO_EPSG_GEOGRAPHIC: &str =

/// The file's Copyright tag, trimmed, or why it is left out (`Err`); `Ok(None)` without one.
pub(crate) fn copyright_tag<R: Read + Seek>(dec: &mut Decoder<R>) -> std::result::Result<Option<String>, String> {
match dec.find_tag(Tag::Copyright).map(|v| v.map(|v| v.into_string())) {
copyright_of(dec.find_tag(Tag::Copyright))
}

/// The Copyright tag as `found` (however it was read): trimmed, or why it is left out (`Err`);
/// `Ok(None)` without one. Shared by a whole read and the in-place layout's (`cog::read_layout`).
pub(crate) fn copyright_of(
found: std::result::Result<Option<tiff::decoder::ifd::Value>, impl std::fmt::Display>,
) -> std::result::Result<Option<String>, String> {
match found.map(|v| v.map(|v| v.into_string())) {
Ok(None) => Ok(None),
Ok(Some(Ok(c))) => Ok(Some(c.trim().to_string())),
Ok(Some(Err(e))) => Err(format!("its Copyright tag: it isn't ASCII text ({e}), so it is left out")),
Expand Down
1 change: 0 additions & 1 deletion crates/data/tests/integration/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Consolidated integration tests (one binary per crate to cut link time in CI).

mod date_properties;
mod datum_grids;
#[cfg(not(target_arch = "wasm32"))]
mod extent_query_properties;
#[cfg(not(target_arch = "wasm32"))]
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ tiny-skia = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
# The keys a project file has that this version doesn't read, to say what opening it left out.
serde_ignored = "0.1"
serde_ignored = { workspace = true }
log = { workspace = true }
web-time = { workspace = true }
base64 = { workspace = true }
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/cmd/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub fn commands() -> Vec<C> {
),
C::new("connection.forgetPassword", "Forget Saved Password", "Home › Add › Data Sources", forget_password).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)).view().params(r#"{"id": "a database connection's id or name"}"#),
C::new("connection.test", "Test Connection", "Home › Add › Data Sources", test).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)).view().params(
r#"{"id"?: "a connection's id or name", "kind"?: "postgres"|"mysql"|"sqlserver"|"service"|"wms"|"wmts"|"wfs"|"wcs"|"ogcapi"|"arcgis"|"csw"|"stac"|"s3", "name"?: text, "group"?: text, "address"?: text, "options"?: "an unsaved connection, as connection.new (when no id)", "auth"?: text, "user"?: text, "keyName"?: "as connection.new (when no id)", "password"?: "for a named database, authentication refusal restores prior session credentials; a later listing failure keeps the new password; never persisted. A saved web service's: as connection.login (logs in first)", "apiKey"?: "a saved web service's, as connection.login (logs in first)", "allowInsecure"?: "as connection.login", "accessKeyId"?: text, "secretAccessKey"?: text, "sessionToken"?: "as connection.login (logs in first)", "probe"?: "true: only the address the test reads, {fetch} (null for databases, which their driver tests), with tile: {zoom, vector} for an XYZ sample", "answer"?: "non-database kinds only, not XYZ tiles: fetched text (including S3 bucket or object listing XML) that address returned, parsed without a request (no network request then); databases ignore answer and test through their driver"} (a direct XYZ test returns result: {kind: "xyz", tile: [z,x,y], status: "received" or "missing"}; missing is not a pass) → a database's result has {count, layers}, and for an Esri enterprise geodatabase on SQL Server geodatabase: {owner, release, note? (when its catalog or its list of spatial columns was cut short)}, or geodatabaseProblem: why its catalog couldn't be read"#,
r#"{"id"?: "a connection's id or name", "kind"?: "postgres"|"mysql"|"sqlserver"|"service"|"wms"|"wmts"|"wfs"|"wcs"|"ogcapi"|"arcgis"|"csw"|"stac"|"s3", "name"?: text, "group"?: text, "address"?: text, "options"?: "an unsaved connection, as connection.new (when no id)", "auth"?: text, "user"?: text, "keyName"?: "as connection.new (when no id)", "password"?: "for a named database, authentication refusal restores prior session credentials; a later listing failure keeps the new password; never persisted. A saved web service's: as connection.login (logs in first)", "apiKey"?: "a saved web service's, as connection.login (logs in first)", "allowInsecure"?: "as connection.login", "accessKeyId"?: text, "secretAccessKey"?: text, "sessionToken"?: "as connection.login (logs in first)", "probe"?: "true: only the address the test reads, {fetch} (null for databases, which their driver tests), with tile: {zoom, vector} for an XYZ sample", "answer"?: "non-database kinds only, not XYZ tiles: fetched text (including S3 bucket or object listing XML) that address returned, parsed without a request (no network request then); databases ignore answer and test through their driver"} (a direct XYZ test returns result: {kind: "xyz", tile: [z,x,y], status: "received" or "missing"}; missing is not a pass; desktop only: in the browser a direct XYZ test is refused, so pass probe and fetch the tile in the app) → a database's result has {count, layers}, and for an Esri enterprise geodatabase on SQL Server geodatabase: {owner, release, note? (when its catalog or its list of spatial columns was cut short)}, or geodatabaseProblem: why its catalog couldn't be read"#,
),
C::new("connection.browse", "Browse Connection", "Home › Add › Data Sources", browse::browse).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files)).view().params(
r#"{"id": "a connection's id or name", "node"?: "a child's node, as a listing gives it (the connection's top level when absent)", "probe"?: "true: only the address this level reads, {fetch} (null: read without a fetch, or by the database driver); an S3 connection logs in first, as connection.test does", "answer"?: "what that address returned, when the app fetched it", "documents"?: [{"url": "a further document a listing asked for (next)", "text": "its answer"}]} → {connection, node, children: [{key, name, what, detail?, node? (browse it), children? (listed already), add? {command, params}: the command that adds it}], truncated?, matched?, notes?, service? {url, type}, next? (fetch it, then ask again with answer and documents)}. Database roots list schemas; open a schema node to list its tables. A geodatabase's root lists feature datasets, feature classes, tables and other spatial tables (open a feature dataset node to list its classes); if its catalog couldn't be read, the database browses as plain SQL Server, with a note."#,
Expand Down Expand Up @@ -1374,7 +1374,7 @@ fn test_xyz(s: &mut Session, p: &Value, c: &Connection, mut out: Value, sample:
return Err(tile_test::TEXT_ANSWER.into());
}
#[cfg(target_arch = "wasm32")]
return Err("An XYZ sample tile must be fetched by the app.".into());
return Err("In the browser, an XYZ sample tile must be fetched by the app: test with probe: true".into());
#[cfg(not(target_arch = "wasm32"))]
{
use crate::render::rustgis_tiles::cache;
Expand Down
Loading
Loading