Files
faunosteo/crates/core/tests/sheet_verdict.rs
T
bchanot e823655f09 fix(anatomy): V1-2.2 owner arbitrations on SVG references and bytes
Refuse local references to ids a drawing does not define, scope canvas
ids per view, upload every drawing in one stored form checked by the
verdict and the preview, keep strict numeric rgb() colours, and commit
real Inkscape 1.4.3 exports with their generator.
2026-10-29 16:24:07 +01:00

625 lines
23 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! V1-2.2: the server verdict (contract §6.4, §6.5, §6.7). A clean sheet and the equine draft
//! pass; each submission rule fails alone with its closed code; the caps hold at cap − 1 and
//! cap and fail at cap + 1 (labels in astral characters included); the shape is the one the
//! M5 SQL reads; the same input gives the same verdict; a synthetic document at the caps is
//! verified in time.
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
mod common;
use faunosteo_core::domain::sheet::fingerprint::sheet_fingerprint;
use faunosteo_core::domain::sheet::verdict::{
DrawingResult, Verdict, VerdictBinding, VerdictDrawing, VerdictInput, VerdictOutcome, codes,
compute_verdict, sha256_hex,
};
use serde_json::{Value, json};
const ASSET: &str = "11111111-2222-4333-8444-555555555555";
/// A drawing in its stored form (`serialize::stored_form`), as the page's cleaning uploads it.
const DRAWING: &str = concat!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n",
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><path d="M0 0L5 5"/></svg>"#
);
const SEED: &str = "supabase/seed/anatomical-sheets/equine/draft";
const HORSE_ID: &str = "7f767f74-3b36-51a7-8465-52dd7e2ead4a";
fn binding() -> VerdictBinding {
VerdictBinding {
sheet_id: "aaaaaaaa-0000-4000-8000-000000000001".to_owned(),
version_id: "aaaaaaaa-0000-4000-8000-000000000002".to_owned(),
revision: 3,
review_id: "aaaaaaaa-0000-4000-8000-000000000003".to_owned(),
}
}
fn name(text: &str) -> Value {
json!({ "fr": text, "en": text })
}
/// A small valid document drawn on `ASSET`: one view, one point, one zone with a category
/// and a node, everything `to_confirm` (submittable, not yet approvable).
fn document() -> Value {
json!({
"schema_version": 2, "species_id": "canine", "name": name("Chien"),
"description": {}, "scope_disclaimer": { "fr": "Outil", "en": "Tool" },
"attribution": { "authors": ["A"], "license": null, "notes": null },
"vertebral_config": { "regions": [] }, "references": [],
"categories": [{ "id": "c", "name": name("C"), "color": null }],
"views": [{ "id": "main", "kind": "main", "name": name("Vue"), "svg_asset_id": ASSET, "view_box": null }],
"annotations": [{ "id": "a1", "kind": "point", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 1, "cy": 1, "r": 1 },
"review_status": "to_confirm", "name": name("P"), "finding_zone_id": "z1", "vertebral_region_code": null }],
"finding_zones": [{ "id": "z1", "name": name("Z"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("D"), "review_status": "to_confirm",
"children": [{ "id": "n1", "name": name("N"), "review_status": "to_confirm" }] }] }]
})
}
fn row(bytes: &[u8]) -> VerdictDrawing<'_> {
VerdictDrawing {
asset_id: ASSET,
sha256: Box::leak(sha256_hex(bytes).into_boxed_str()),
byte_size: bytes.len() as u64,
bytes: Some(bytes),
}
}
fn verdict_of(document: &Value, drawings: Vec<VerdictDrawing<'_>>) -> Verdict {
let text = document.to_string();
compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: None,
drawings,
})
}
fn verdict(document: &Value) -> Verdict {
verdict_of(document, vec![row(DRAWING.as_bytes())])
}
#[test]
fn a_clean_sheet_passes_bound_to_its_round() {
let doc = document();
let verdict = verdict(&doc);
assert_eq!(
verdict.outcome,
VerdictOutcome::Passed,
"{:?}",
verdict.failures
);
assert_eq!(
(verdict.failure_code.as_deref(), verdict.failures.len()),
(None, 0)
);
assert_eq!(
verdict.fingerprint,
Some(sheet_fingerprint(&doc.to_string()).unwrap())
);
let b = binding();
assert_eq!(
(
&verdict.sheet_id,
&verdict.version_id,
verdict.revision,
&verdict.review_id
),
(&b.sheet_id, &b.version_id, b.revision, &b.review_id)
);
assert_eq!(verdict.format, 1);
assert!(verdict.verified_with.starts_with("faunosteo-core "));
assert_eq!(verdict.drawings.len(), 1);
assert_eq!(verdict.drawings[0].result, DrawingResult::Ok);
let keys: Vec<&str> = verdict.groups.iter().map(|g| g.key.as_str()).collect();
assert_eq!(keys, ["general", "view:main", "zone:z1"]);
assert!(
verdict.groups[1..].iter().all(|g| !g.coverable),
"to_confirm left"
);
assert!(verdict.changes.is_none());
let completeness = verdict.completeness.unwrap();
assert_eq!(completeness.statuses.to_confirm, 3);
assert_eq!(completeness.uncited, 2);
}
#[test]
fn the_shape_is_what_the_sql_reads() {
let value = serde_json::to_value(verdict(&document())).unwrap();
assert!(value["fingerprint"].as_str().unwrap().len() == 64);
for group in value["groups"].as_array().unwrap() {
assert!(group["key"].is_string() && group["digest"].is_string());
assert!(group["coverable"].is_boolean());
}
let drawing = &value["drawings"][0];
assert_eq!(drawing["asset_id"], json!(ASSET));
assert_eq!(drawing["sha256"], json!(sha256_hex(DRAWING.as_bytes())));
assert_eq!(value["outcome"], json!("passed"));
assert_eq!(
value["verified_with"].as_str().map(|s| s.len() <= 100),
Some(true)
);
}
#[test]
fn the_equine_draft_passes_with_its_fingerprint_and_thirty_groups() {
let text = common::repo_file(&format!("{SEED}/document.json"));
let horse = std::fs::read(common::repo_path(&format!("{SEED}/assets/horse.svg"))).unwrap();
let verdict = compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: None,
drawings: vec![VerdictDrawing {
asset_id: HORSE_ID,
sha256: "0ea5202fa3b95bac167b87c12ee969ab0272e085b60c2d34dbca6202c5f08541",
byte_size: 132_997,
bytes: Some(&horse),
}],
});
assert_eq!(
verdict.outcome,
VerdictOutcome::Passed,
"{:?}",
verdict.failures
);
assert_eq!(
verdict.fingerprint.as_deref(),
Some("12d788727c1e532641bd5b3a7ecf39dbdd25e70350f8a76be5ca917b262874e2")
);
assert_eq!(verdict.groups.len(), 30);
assert_eq!(verdict.document_bytes, 184_105);
assert!(
verdict
.issues
.iter()
.all(|i| i.severity != faunosteo_core::domain::sheet::SheetIssueSeverity::Error)
);
}
fn failures(verdict: &Verdict) -> Vec<&str> {
verdict.failures.iter().map(String::as_str).collect()
}
#[test]
fn an_unreadable_document_or_base_fails_as_integrity() {
for text in ["{", "[]", r#"{"schema_version":2}"#] {
let verdict = compute_verdict(&VerdictInput {
binding: binding(),
document: text,
base_document: None,
drawings: vec![],
});
assert_eq!(failures(&verdict), [codes::DOCUMENT], "{text}");
assert!(verdict.fingerprint.is_none() && verdict.groups.is_empty());
}
let mut unknown = document();
unknown["extra"] = json!(1);
assert_eq!(
failures(&verdict(&unknown)),
[codes::DOCUMENT],
"strict shape"
);
let text = document().to_string();
let verdict = compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: Some("{\"broken\""),
drawings: vec![row(DRAWING.as_bytes())],
});
assert_eq!(failures(&verdict), [codes::BASE]);
}
#[test]
fn each_submission_rule_fails_alone() {
let mut duplicate = document();
let copy = duplicate["annotations"][0].clone();
duplicate["annotations"].as_array_mut().unwrap().push(copy);
let v = verdict(&duplicate);
assert_eq!(failures(&v), [codes::RULES]);
assert!(
v.fingerprint.is_none(),
"no fingerprint with an integrity error"
);
assert!(v.issues.iter().any(|i| i.code == "annotation.id.duplicate"));
let mut undrawn = document();
undrawn["annotations"][0]["geometry"] = Value::Null;
let v = verdict(&undrawn);
assert_eq!(failures(&v), [codes::NO_GEOMETRY]);
assert!(
v.fingerprint.is_some(),
"a missing geometry is no integrity error"
);
assert!(v.issues.iter().any(|i| i.code == "annotation.geometry.missing" && i.path == "annotations[0].geometry"));
}
#[test]
fn each_drawing_fault_fails_with_its_code() {
let doc = document();
let bytes = DRAWING.as_bytes();
let base = row(bytes);
let cases: Vec<(Vec<VerdictDrawing<'_>>, &str, DrawingResult)> = vec![
(vec![], codes::DRAWING_MISSING, DrawingResult::Missing),
(
vec![VerdictDrawing {
bytes: None,
..base
}],
codes::DRAWING_MISSING,
DrawingResult::Missing,
),
(
vec![VerdictDrawing {
byte_size: 1,
..base
}],
codes::SIZE_MISMATCH,
DrawingResult::SizeMismatch,
),
(
vec![VerdictDrawing {
sha256: "ab",
..base
}],
codes::OBJECT_CONFLICT,
DrawingResult::HashMismatch,
),
];
for (drawings, code, result) in cases {
let v = verdict_of(&doc, drawings);
assert_eq!(failures(&v), [code]);
assert_eq!(v.drawings[0].result, result);
assert!(v.fingerprint.is_some());
}
let invalid: &[u8] = b"<svg xmlns=\"http://www.w3.org/2000/svg\">\xff</svg>";
let doctype = b"<!DOCTYPE svg><svg xmlns=\"http://www.w3.org/2000/svg\"/>";
let styled = br#"<svg xmlns="http://www.w3.org/2000/svg"><style>.a{fill:red}</style><path class="a" d="M0 0"/></svg>"#;
for (bytes, code, detail) in [
(invalid, codes::SVG_REJECTED, "malformed"),
(&doctype[..], codes::SVG_REJECTED, "doctype"),
(&styled[..], codes::SVG_REMOVAL, "style"),
] {
let v = verdict_of(&doc, vec![row(bytes)]);
assert_eq!(failures(&v), [code]);
assert_eq!(v.drawings[0].detail.as_deref(), Some(detail));
}
}
/// Owner decision 2026-10-29: a stored drawing must be in the stored form the page's cleaning
/// writes; bytes read with no removal but written otherwise (original export bytes, another
/// declared encoding, an HTML-only comment form, another quoting) fail, never repaired.
#[test]
fn a_drawing_outside_the_stored_form_fails() {
let doc = document();
let body = DRAWING.split_once('\n').unwrap().1;
let export = std::fs::read(common::repo_path(
"crates/core/tests/fixtures/svg/exports/imagemagick-7.1.2-18-draw.svg",
))
.unwrap();
let mut doc_on_export = doc.clone();
doc_on_export["views"][0]["view_box"] = Value::Null;
for bytes in [
body.as_bytes().to_vec(),
format!("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n{body}").into_bytes(),
DRAWING.replace("<path", "<!-->--><path").into_bytes(),
DRAWING
.replace("viewBox=\"0 0 10 10\"", "viewBox='0 0 10 10'")
.into_bytes(),
format!("{DRAWING}\n").into_bytes(),
export,
] {
let v = verdict_of(&doc, vec![row(&bytes)]);
assert_eq!(
failures(&v),
[codes::SVG_NOT_CANONICAL],
"{}",
String::from_utf8_lossy(&bytes)
);
assert_eq!(v.drawings[0].result, DrawingResult::SvgNotCanonical);
assert!(v.fingerprint.is_some());
}
let v = verdict_of(&doc, vec![row(DRAWING.as_bytes())]);
assert_eq!(v.drawings[0].result, DrawingResult::Ok);
}
/// `count` annotations drawn in the main view, all in zone `z1`.
fn with_annotations(count: usize) -> Value {
let mut doc = document();
let template = doc["annotations"][0].clone();
doc["annotations"] = (0..count)
.map(|i| {
let mut a = template.clone();
a["id"] = json!(format!("a{i}"));
a
})
.collect();
doc
}
fn caps_failed(doc: &Value) -> bool {
let v = verdict(doc);
assert!(
v.failures.iter().all(|c| c == codes::CAPS),
"{:?}",
v.failures
);
v.failures.iter().any(|c| c == codes::CAPS)
}
#[test]
fn the_caps_hold_at_the_cap_and_fail_one_over() {
assert!(!caps_failed(&with_annotations(1023)) && !caps_failed(&with_annotations(1024)));
assert!(caps_failed(&with_annotations(1025)));
// Labels in UTF-16 units: 𝄞 counts two.
for (label, over) in [
("𝄞".repeat(255) + "a", false),
("𝄞".repeat(256), false),
("𝄞".repeat(256) + "a", true),
] {
let mut doc = document();
doc["finding_zones"][0]["name"] = json!({ "fr": label, "en": "Z" });
assert_eq!(caps_failed(&doc), over);
}
for (depth, over) in [(7, false), (8, false), (9, true)] {
let mut doc = document();
doc["finding_zones"][0]["categories"][0]["children"] = chain(depth - 1);
assert_eq!(caps_failed(&doc), over, "depth {depth}");
}
for (nodes, over) in [(8191, false), (8192, false), (8193, true)] {
let mut doc = document();
let flat: Vec<Value> = (0..nodes - 1)
.map(|i| json!({ "id": format!("n{i}"), "name": name("N"), "review_status": "to_confirm" }))
.collect();
doc["finding_zones"][0]["categories"][0]["children"] = Value::Array(flat);
assert_eq!(caps_failed(&doc), over, "{nodes} nodes");
}
}
/// `levels` nested nodes below the category.
fn chain(levels: usize) -> Value {
let mut children = json!([]);
for i in (0..levels).rev() {
children = json!([{ "id": format!("d{i}"), "name": name("N"), "review_status": "to_confirm", "children": children }]);
}
children
}
#[test]
fn the_document_cap_is_the_server_measure() {
let measure = |doc: &Value| verdict(doc).document_bytes;
let mut doc = document();
doc["description"] = json!({ "fr": "" });
let empty = measure(&doc);
for (bytes, over) in [
(2_097_151_u64, false),
(2_097_152, false),
(2_097_153, true),
] {
let mut sized = doc.clone();
sized["description"]["fr"] = json!(
"é".repeat(((bytes - empty) / 2) as usize)
+ &"x".repeat(((bytes - empty) % 2) as usize)
);
assert_eq!(measure(&sized), bytes);
assert_eq!(caps_failed(&sized), over, "{bytes}");
}
}
#[test]
fn drawings_count_toward_the_caps() {
let mut doc = document();
let ids = [
ASSET,
"11111111-2222-4333-8444-000000000002",
"11111111-2222-4333-8444-000000000003",
"11111111-2222-4333-8444-000000000004",
"11111111-2222-4333-8444-000000000005",
];
let views: Vec<Value> = ids
.iter()
.enumerate()
.map(|(i, id)| match i {
0 => json!({ "id": "main", "kind": "main", "name": name("V"), "svg_asset_id": id, "view_box": null }),
_ => json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"), "svg_asset_id": id,
"view_box": null, "parent_view_id": "main" }),
})
.collect();
let triggers: Vec<Value> = (1..ids.len())
.map(|i| json!({ "id": format!("t{i}"), "kind": "detail_trigger", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "circle", "cx": 2, "cy": 2, "r": 1 },
"review_status": "to_confirm", "name": null, "opens_view_id": format!("d{i}") }))
.collect();
doc["views"] = Value::Array(views);
doc["annotations"].as_array_mut().unwrap().extend(triggers);
let bytes = DRAWING.as_bytes();
let rows = |n: usize| -> Vec<VerdictDrawing<'_>> {
ids.iter()
.take(n)
.map(|id| VerdictDrawing {
asset_id: id,
..row(bytes)
})
.collect()
};
let mut four = doc.clone();
four["views"].as_array_mut().unwrap().pop();
four["annotations"].as_array_mut().unwrap().pop();
assert_eq!(failures(&verdict_of(&four, rows(4))), Vec::<&str>::new());
let v = verdict_of(&doc, rows(5));
assert_eq!(failures(&v), [codes::CAPS]);
assert!(
v.caps
.unwrap()
.exceeded
.iter()
.any(|c| c.as_str() == "drawings")
);
}
#[test]
fn the_first_failure_names_the_round_in_code_order() {
let mut doc = with_annotations(1025);
doc["annotations"][0]["geometry"] = Value::Null;
let copy = doc["annotations"][1].clone();
doc["annotations"].as_array_mut().unwrap().push(copy);
let v = verdict_of(&doc, vec![]);
assert_eq!(
failures(&v),
[
codes::RULES,
codes::NO_GEOMETRY,
codes::CAPS,
codes::DRAWING_MISSING
]
);
assert_eq!(v.failure_code.as_deref(), Some(codes::RULES));
assert_eq!(v.outcome, VerdictOutcome::Failed);
}
#[test]
fn the_same_input_gives_the_same_verdict() {
let doc = document();
let first = serde_json::to_string(&verdict(&doc)).unwrap();
assert_eq!(first, serde_json::to_string(&verdict(&doc)).unwrap());
}
#[test]
fn a_base_gives_removal_groups_and_the_change_list() {
let mut base = document();
base["finding_zones"]
.as_array_mut()
.unwrap()
.push(json!({ "id": "z2", "name": name("Z2"), "categories": [] }));
let text = document().to_string();
let base_text = base.to_string();
let v = compute_verdict(&VerdictInput {
binding: binding(),
document: &text,
base_document: Some(&base_text),
drawings: vec![row(DRAWING.as_bytes())],
});
assert_eq!(v.outcome, VerdictOutcome::Passed);
let last = v.groups.last().unwrap();
assert_eq!(
(last.key.as_str(), last.removed, last.coverable),
("zone:z2", true, true)
);
let changes = v.changes.unwrap();
assert_eq!(changes.len(), 1);
assert_eq!(changes[0].group, "zone:z2");
}
/// A document at every cap: 64 views, 1 024 annotations, 8 192 finding nodes, depth 8.
fn at_caps() -> Value {
let mut doc = document();
let mut views = vec![
json!({ "id": "main", "kind": "main", "name": name("V"), "svg_asset_id": ASSET, "view_box": null }),
];
let mut annotations = Vec::new();
for i in 1..64 {
views.push(json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"), "svg_asset_id": null,
"view_box": { "min_x": 0, "min_y": 0, "width": 5, "height": 5 }, "parent_view_id": "main" }));
annotations.push(json!({ "id": format!("t{i}"), "kind": "detail_trigger", "view_id": "main", "category_id": "c",
"laterality": "unpaired", "geometry": { "type": "polygon", "points": [[0, 0], [1, 0], [1, 1]] },
"review_status": "reviewed", "name": null, "opens_view_id": format!("d{i}") }));
}
let zones: Vec<Value> = (0..64)
.map(|z| {
let mut children = vec![chain_reviewed(7)];
children.extend((0..120).map(|n| json!({ "id": format!("l{n}"), "name": name("Nœud de lésion"), "review_status": "reviewed" })));
json!({ "id": format!("z{z}"), "name": name("Zone"), "categories": [{ "id": "cat", "kind": "dysfunction",
"name": name("Catégorie"), "review_status": "reviewed", "children": children }] })
})
.collect();
for i in 0..(1024 - 63) {
annotations.push(json!({ "id": format!("p{i}"), "kind": "point", "view_id": format!("d{}", 1 + i % 63),
"category_id": "c", "laterality": "left", "geometry": { "type": "circle", "cx": 1.25, "cy": 2.5, "r": 0.5 },
"review_status": "reviewed", "name": name("Point"), "finding_zone_id": format!("z{}", i % 64),
"vertebral_region_code": null }));
}
doc["views"] = Value::Array(views);
doc["annotations"] = Value::Array(annotations);
doc["finding_zones"] = Value::Array(zones);
doc
}
fn chain_reviewed(levels: usize) -> Value {
let mut node =
json!({ "id": format!("c{levels}"), "name": name("N"), "review_status": "reviewed" });
for level in (1..levels).rev() {
node = json!({ "id": format!("c{level}"), "name": name("N"), "review_status": "reviewed", "children": [node] });
}
node
}
#[test]
fn a_document_at_every_cap_is_verified_in_time() {
let doc = at_caps();
let started = std::time::Instant::now();
let v = verdict(&doc);
let elapsed = started.elapsed();
assert_eq!(v.outcome, VerdictOutcome::Passed, "{:?}", v.failures);
let caps = v.caps.unwrap();
assert_eq!(
(
caps.views,
caps.annotations,
caps.finding_nodes,
caps.finding_depth
),
(64, 1024, 8192, 8)
);
assert_eq!(v.groups.len(), 1 + 64 + 64);
assert!(v.groups.iter().all(|g| g.coverable));
println!(
"verdict at the caps: {} ms, document {} bytes",
elapsed.as_millis(),
v.document_bytes
);
assert!(
elapsed.as_secs() < 20,
"the core's share of the 120 s budget"
);
}
#[test]
fn every_cap_holds_at_cap_minus_one_and_cap_and_fails_one_over() {
use faunosteo_core::domain::sheet::AnatomicalSheetDocument;
use faunosteo_core::domain::sheet::caps::caps_report;
const MIB: u64 = 1024 * 1024;
let typed =
|doc: &Value| -> AnatomicalSheetDocument { serde_json::from_value(doc.clone()).unwrap() };
let names = |doc: &AnatomicalSheetDocument, sizes: &[u64]| -> Vec<&'static str> {
caps_report(doc, 0, sizes)
.exceeded
.iter()
.map(|c| c.as_str())
.collect()
};
let base = typed(&document());
for (sizes, expected) in [
(vec![1; 3], vec![]),
(vec![1; 4], vec![]),
(vec![1; 5], vec!["drawings"]),
(vec![2 * MIB - 1], vec![]),
(vec![2 * MIB], vec![]),
(vec![2 * MIB + 1], vec!["drawing_bytes"]),
(vec![2 * MIB, 2 * MIB, 2 * MIB - 1], vec![]),
(vec![2 * MIB, 2 * MIB, 2 * MIB], vec![]),
(
vec![2 * MIB, 2 * MIB, 2 * MIB, 1],
vec!["drawings_total_bytes"],
),
] {
assert_eq!(names(&base, &sizes), expected, "{sizes:?}");
}
for (count, expected) in [(63, vec![]), (64, vec![]), (65, vec!["views"])] {
let mut doc = document();
let extra = (1..count).map(|i| {
json!({ "id": format!("d{i}"), "kind": "detail", "name": name("D"), "svg_asset_id": null,
"view_box": { "min_x": 0, "min_y": 0, "width": 1, "height": 1 }, "parent_view_id": "main" })
});
doc["views"].as_array_mut().unwrap().extend(extra);
assert_eq!(names(&typed(&doc), &[1]), expected, "{count} views");
}
}