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: 6 additions & 2 deletions apps/rustgis-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,11 @@ impl Strict {
};
if LossKind::from_id(v).is_none() && LossCode::from_id(v).is_none() {
let kinds: Vec<&str> = LossKind::ALL.iter().map(|k| k.id()).collect();
return Err(format!("--allow {v}: not a loss kind ({}) or code (listed in the command line guide)", kinds.join(", ")));
return Err(format!(
"--allow {v}: not a loss kind ({}) or code (listed at {})",
kinds.join(", "),
rustgis_engine::data::loss::GUIDE
));
}
allow.push(v.to_string());
}
Expand Down Expand Up @@ -184,7 +188,7 @@ impl Strict {
let spec = code.spec();
// A counted notice says how many it lost in its text; this counts the notices.
let notices = if n == 1 { "1 notice".to_string() } else { format!("{n} notices") };
said.push_str(&format!("\n {} ({notices}): {}", spec.id, spec.action));
said.push_str(&format!("\n {} ({notices}): {}\n {}", spec.id, spec.action, code.doc_url()));
}
Err(said)
}
Expand Down
1 change: 1 addition & 0 deletions apps/rustgis-cli/tests/integration/strict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ fn a_strict_run_stops_at_a_loss_it_does_not_allow() {
let (code, err, printed, wrote) = run(lossy, &["--strict"]);
assert_eq!((code, printed, wrote), (Some(3), false, false), "{err}");
assert!(err.contains("stopped after layer.addData") && err.contains("dropped.ring (1 notice): Correct the unreadable"), "{err}");
assert!(err.contains("https://rustgis.app/user-guide/loss-codes/#dropped.ring"), "the code's entry in the guide: {err}");
// Allowed by its code or its kind, it runs to the end; another kind doesn't allow it.
for allow in [&["--allow", "dropped.ring"][..], &["--allow", "dropped"], &["--allow=dropped.ring"]] {
let (code, err, _, wrote) = run(lossy, &[&["--strict"][..], allow].concat());
Expand Down
8 changes: 7 additions & 1 deletion apps/rustgis-python/python/rustgis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@
PathLike = Union[str, "os.PathLike[str]"]


# The guide's page of loss codes (rustgis_data::loss::GUIDE), an entry for each code.
_LOSS_GUIDE = "https://rustgis.app/user-guide/loss-codes/"

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.

The guide's address is written out again here, apart from rustgis_data::loss::GUIDE on the Rust side. The two match today, so this is not a defect. But if the Rust constant moves, Python keeps the old page, and the Python test (test_session.py) pins the same literal, so it would not catch the drift. Consider reading the address from the built package or having a test compare the two.

Category: quality

@Mavrick-F Mavrick-F Nov 27, 2026 •

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 two match today. The Python test checks the address it gives against a literal, not against the Rust constant, so a move on the Rust side alone wouldn't fail it. Deriving the address from the Rust constant is left for the release quality pass.



class DataLossWarning(UserWarning):
"""A command lost data: it dropped, changed, approximated or assumed something.

Expand All @@ -53,8 +57,9 @@ class DataLossWarning(UserWarning):

Attributes:
code: The loss code, such as ``"dropped.ring"``: never translated, renamed or reused.
The command line guide lists every code with what to do about it.
The guide has an entry for each code, with what to do about it (``url``).
kind: The code's kind: ``"dropped"``, ``"changed"``, ``"approximated"`` or ``"assumed"``.
url: The code's entry in the guide: what it means and what to do about it.
"""

def __init__(self, message: str, code: str) -> None:
Expand All @@ -67,6 +72,7 @@ def __init__(self, message: str, code: str) -> None:
super().__init__(message)
self.code = code
self.kind = code.split(".", 1)[0]
self.url = _LOSS_GUIDE + "#" + code

def __reduce__(self) -> Tuple[Any, ...]:
"""Pickles with the code and what was added to it (notes), so a warning turned into an
Expand Down
2 changes: 2 additions & 0 deletions apps/rustgis-python/tests/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,8 @@ def test_losses_are_warnings_with_their_code(tmp_path):
with pytest.warns(rustgis.ChangedWarning) as seen:
s.run("edit.calculateField", table="records", field="n", expression="n + 1.5")
assert [w.message.code for w in seen if issubclass(w.category, rustgis.DataLossWarning)] == ["changed.truncated"]
[url] = [w.message.url for w in seen if issubclass(w.category, rustgis.DataLossWarning)]
assert url == "https://rustgis.app/user-guide/loss-codes/#changed.truncated"
s.notices()
with warnings.catch_warnings(record=True) as seen:
warnings.simplefilter("always")
Expand Down
1 change: 1 addition & 0 deletions crates/assistant/src/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ pub const PAGES: &[Page] = pages![
"user-guide/editing.md",
"user-guide/analysis.md",
"user-guide/expressions.md",
"user-guide/loss-codes.md",
"user-guide/layouts.md",
"user-guide/sharing.md",
"user-guide/workspace.md",
Expand Down
27 changes: 25 additions & 2 deletions crates/data/src/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,8 @@ pub struct Record {
pub message: String,
pub details: String,
pub network: Option<Network>,
/// The loss the message reports, if any: the pane links to its entry in the guide.
pub loss: Option<crate::loss::LossCode>,
}

#[derive(Default)]
Expand Down Expand Up @@ -204,13 +206,14 @@ impl History {
message: bounded(message, MAX_MESSAGE_BYTES),
details: bounded(details, MAX_DETAILS_BYTES),
network: None,
loss: None,
});
}

/// [`History::push`] for a message already through [`redact`] (a notice the session redacted
/// for its status bar): it is only bounded, so a notice isn't redacted again for each copy.
/// Only a [`Redacted`], which `redact` alone makes, gets this path.
pub fn push_redacted(&self, severity: Severity, source: &str, message: &Redacted) {
pub fn push_redacted(&self, severity: Severity, source: &str, message: &Redacted, loss: Option<crate::loss::LossCode>) {
self.retain(Record {
id: 0,
timestamp_ms: timestamp_ms(),
Expand All @@ -219,6 +222,7 @@ impl History {
message: truncated(message.as_str(), MAX_MESSAGE_BYTES),
details: String::new(),
network: None,
loss,
});
}

Expand Down Expand Up @@ -261,6 +265,9 @@ impl History {
record.source,
record.message
);
if let Some(code) = record.loss {
let _ = writeln!(report, "Loss: {} ({})", code.spec().id, code.doc_url());
}
if !record.details.is_empty() {
let _ = writeln!(report, "{}", record.details);
}
Expand Down Expand Up @@ -318,6 +325,7 @@ impl Capture {
message,
details: String::new(),
network: None,
loss: None,
},
);
guard.absences_overflow_said = Some(id);
Expand All @@ -335,6 +343,7 @@ impl Capture {
),
details: String::new(),
network: Some(Network { url, method: known_method(method), status: Some(status), duration_ms: None, kind: NetworkKind::Http }),
loss: None,
};
let id = store(&mut guard, record);
guard.absences_said.push((server, id));
Expand Down Expand Up @@ -374,6 +383,7 @@ impl Capture {
message: bounded(message, MAX_MESSAGE_BYTES),
details: bounded(details, MAX_DETAILS_BYTES),
network: Some(network),
loss: None,
};
let mut state = lock(&state);
if once
Expand Down Expand Up @@ -1818,7 +1828,7 @@ mod tests {
fn text_already_redacted_is_only_bounded() {
let history = History::default();
let long = "word ".repeat(1000);
history.push_redacted(Severity::Info, "Application", &Redacted::new(&long));
history.push_redacted(Severity::Info, "Application", &Redacted::new(&long), None);
history.push(Severity::Info, "Application", &long, "");
let records = history.records();
assert_eq!(records[0].message, records[1].message);
Expand All @@ -1827,6 +1837,19 @@ mod tests {
assert_eq!(Redacted::new("Authorization: Bearer hidden").as_str(), "[REDACTED]");
}

#[test]
fn a_loss_keeps_its_code_and_the_report_gives_its_guide_entry() {
let history = History::default();
let code = crate::loss::LossCode::DroppedRing;
history.push_redacted(Severity::Warning, "layer.addData", &Redacted::new("1 ring left out"), Some(code));
history.push_redacted(Severity::Info, "layer.addData", &Redacted::new("added"), None);
let records = history.records();
assert_eq!(records.iter().map(|r| r.loss).collect::<Vec<_>>(), [Some(code), None]);
let report = history.report(Filter::All);
assert!(report.contains("Loss: dropped.ring (https://rustgis.app/user-guide/loss-codes/#dropped.ring)"), "{report}");
assert_eq!(report.matches("Loss: ").count(), 1, "{report}");
}

#[test]
fn absence_notes_name_the_method_and_bound_oversized_addresses() {
let history = History::default();
Expand Down
33 changes: 23 additions & 10 deletions crates/data/src/loss.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Shared classification for data-loss notices, independent of their wording.
//!
//! A code's identifier is public: scripts match on it (`rustgis-cli run --strict --allow`), so it
//! is never translated, renamed or reused. The command line guide lists every code, checked by
//! is never translated, renamed or reused. The guide has an entry for each code ([`GUIDE`]), checked by
//! `the_guide_lists_every_code`.

/// What happened to the data.
Expand Down Expand Up @@ -152,7 +152,16 @@ loss_codes! {
),
}

/// The guide's page of loss codes, which has an entry for each, anchored by its identifier.
pub const GUIDE: &str = "https://rustgis.app/user-guide/loss-codes/";

impl LossCode {
/// The address of this code's entry in the guide: what it means, where it is said and what to
/// do about it.
pub fn doc_url(self) -> String {
format!("{GUIDE}#{}", self.spec().id)
}

/// The code this identifier names.
pub fn from_id(id: &str) -> Option<LossCode> {
Self::ALL.iter().copied().find(|code| code.spec().id == id)
Expand Down Expand Up @@ -437,18 +446,22 @@ mod tests {

#[test]
fn the_guide_lists_every_code() {
let guide = include_str!("../../../docs/cli.md").replace("\r\n", "\n");
let section = guide.split("\n### Loss codes\n").nth(1).unwrap_or_default();
let section = section.split("\n#").next().unwrap_or_default();
let rows: Vec<&str> = section.lines().filter(|l| l.starts_with("| `")).collect();
let guide = include_str!("../../../docs/user-guide/loss-codes.md").replace("\r\n", "\n");
let headings: Vec<&str> = guide.lines().filter(|l| l.starts_with("### `")).collect();
for code in LossCode::ALL {
let spec = code.spec();
let row = format!("| `{}` | {} |", spec.id, spec.action);
assert!(rows.contains(&row.as_str()), "docs/cli.md: the loss codes should list\n{row}");
// The anchor each notice links to ([`LossCode::doc_url`]), and what to do under it.
let heading = format!("### `{0}` {{ #{0} }}", spec.id);
let entry = guide.split(&format!("\n{heading}\n")).nth(1).unwrap_or_default();
let entry = entry.split("\n### ").next().unwrap_or_default().split("\n## ").next().unwrap_or_default();
assert!(!entry.is_empty(), "docs/user-guide/loss-codes.md should have the entry\n{heading}");
let action = format!("**What to do:** {}", spec.action);
assert!(entry.replace('\n', " ").contains(&action), "docs/user-guide/loss-codes.md: `{}` should say\n{action}", spec.id);
assert!(code.doc_url().ends_with(&format!("/user-guide/loss-codes/#{}", spec.id)));
}
for row in rows {
let id = row.trim_start_matches("| `").split('`').next().unwrap_or_default();
assert!(LossCode::from_id(id).is_some(), "docs/cli.md lists `{id}`, which is not a loss code");
for heading in headings {

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.

The per-code check finds each heading by its first match (guide.split(...).nth(1)), so a second ### dropped.ring`` heading would pass silently. Pinning the heading count to the number of codes catches a duplicate. Every heading is already checked to be a code, so equal counts mean one heading per code:

Suggested change
for heading in headings {
assert_eq!(headings.len(), LossCode::ALL.len(), "docs/user-guide/loss-codes.md should have one heading for each code");
for heading in headings {

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.

A duplicate heading would need someone to write one by hand, and the anchor would still resolve to the first; pinning the count is left for the release quality pass.

let id = heading.trim_start_matches("### `").split('`').next().unwrap_or_default();
assert!(LossCode::from_id(id).is_some(), "docs/user-guide/loss-codes.md lists `{id}`, which is not a loss code");
}
}
}
2 changes: 1 addition & 1 deletion crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3599,7 +3599,7 @@ impl Session {
if severity == rustgis_data::diagnostics::Severity::Error && self.rerun_said.iter().any(|said| said == text.as_str()) {
return;
}
self.diagnostics.push_redacted(severity, source.unwrap_or("Application"), &text);
self.diagnostics.push_redacted(severity, source.unwrap_or("Application"), &text, loss);
self.notices.push(Notice {
text: text.into_string(),
error: severity == rustgis_data::diagnostics::Severity::Error,
Expand Down
19 changes: 16 additions & 3 deletions crates/ui-egui/src/diagnosticlog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use rustgis_engine::data::diagnostics::{Filter, NetworkKind, Record, Severity};

use crate::{RustGisApp, theme::Tokens};

/// The Messages pane: its filters, Copy diagnostics and Clear, then the entries, newest first.
pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
// Background requests may finish without another UI action (including HEAD probes).
ui.ctx().request_repaint_after(std::time::Duration::from_millis(500));
Expand Down Expand Up @@ -57,9 +58,10 @@ pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
egui::ScrollArea::vertical().id_salt("diagnostic_log_entries").auto_shrink([false, false]).show(ui, |ui| {
egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| {
let mut shown = false;
for record in records.iter().rev().filter(|r| app.ui.diagnostic_filter.matches(r)) {
let filter = app.ui.diagnostic_filter;
for record in records.iter().rev().filter(|r| filter.matches(r)) {
shown = true;
ui.push_id(record.id, |ui| entry(ui, record, t));
ui.push_id(record.id, |ui| entry(ui, record, t, &mut app.ui.open_url));
ui.separator();
}
if !shown {
Expand All @@ -70,7 +72,9 @@ pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
app.ui.diagnostic_snapshot = Some((generation, records));
}

fn entry(ui: &mut Ui, record: &Record, t: &Tokens) {
/// One entry: its time, severity and source, the message, the loss code with a link to its entry
/// in the guide (set in `open_url` when clicked), and any technical details.
fn entry(ui: &mut Ui, record: &Record, t: &Tokens, open_url: &mut Option<String>) {
// Literal labels, so each is found and translated with the interface's other strings.
let (severity, color) = match record.severity {
Severity::Error => (tl!("Error"), t.red),
Expand All @@ -90,6 +94,15 @@ fn entry(ui: &mut Ui, record: &Record, t: &Tokens) {
ui.label(RichText::new(source).small().color(t.text_dim));
});
ui.add(egui::Label::new(&record.message).wrap().selectable(true));
if let Some(code) = record.loss {
// The code is an identifier, never translated; its guide entry says what to do.
ui.horizontal_wrapped(|ui| {
ui.label(RichText::new(code.spec().id).small().monospace().color(t.text_dim));
if ui.link(RichText::new(tl!("What this means")).small()).on_hover_text(code.doc_url()).clicked() {
*open_url = Some(code.doc_url());
}
});
}
if !record.details.is_empty() || record.network.is_some() {
egui::CollapsingHeader::new(tl!("Technical details")).show(ui, |ui| {
if let Some(network) = &record.network {
Expand Down
27 changes: 2 additions & 25 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,31 +154,8 @@ An `--allow` that names no kind or code is refused with status 2, as is `--allow

### Loss codes

| Code | What to do |
|---|---|
| `dropped.legend` | Use a service with short HTTP or HTTPS addresses for its legend pictures. |
| `dropped.ring` | Correct the unreadable polygon ring in the source, or write to a format that holds holes, such as GeoPackage. |
| `dropped.extra-attributes` | Add fields for the extra attribute values or remove those values from the input. |
| `dropped.time` | Write to a date-time field to keep the time of day. |
| `dropped.value` | Correct the value or use a destination field that can hold it. |
| `dropped.calculation-result` | Correct the expression or check the input rows named in the notice. |
| `dropped.zm` | Keep the source file where heights or measures matter: RustGIS keeps x and y only. |
| `dropped.crs-name` | Keep the source file's coordinate system definition with the export, or export in WGS 84, which every format can name. |
| `dropped.feature` | Correct those features in the source, or read the source in the way the notice suggests. |
| `dropped.geometry` | Correct the geometry in the source, or give the coordinate system its coordinates are in. |
| `dropped.over-limit` | Read less at once, such as by filtering or clipping the source first. |
| `changed.truncated` | Use a decimal field to keep the fractional part. |
| `changed.field-name` | Use field names the format holds: at most 10 bytes and unique ignoring case for a Shapefile, unique ignoring case for a GeoPackage. |
| `changed.cut` | Shorten the text to what the format holds (254 bytes for a Shapefile; nothing past a NUL character), or write to a format without the limit, such as GeoPackage. |
| `changed.body` | Export in the layer's own coordinate system, which keeps its body. |
| `changed.encoding` | Put a .cpg file naming the file's own encoding beside it. |
| `changed.rounded` | Keep the source file where finer values matter, or write to a format that holds them (times finer than the format keeps, numbers past a dBase field's precision, or whole numbers past 2^53 in a decimal field). |
| `changed.position` | Export in a coordinate system that holds the positions, such as WGS 84. |
| `approximated.datum` | Export in the layer's own coordinate system, or give that system with a known transformation to WGS 84. |
| `approximated.curve` | Keep the source file where exact curves matter: RustGIS draws curves as straight segments. |
| `assumed.null-marker` | Write the value another way if the text Null is meant as text, not as an empty value. |
| `assumed.crs` | Give the coordinate system the coordinates are in ("crs" when adding the data, or Define Projection). |
| `assumed.encoding` | Give the file's encoding in a form RustGIS reads: a .cpg beside a Shapefile or dBASE file naming UTF-8 or its Windows code page, or a DXF saved as UTF-8. |
Each code has an entry in [Data loss codes](user-guide/loss-codes.md): what it means, where it is
said and what to do about it. A strict run's message gives the address of each code's entry.

Not every loss has a code yet: losses still reported without one don't stop a strict run.

Expand Down
Loading
Loading