feat(domain): R2.2 report migration, rebase, sheet snapshot and layered archive reading in Rust; draft restore and archive import operations
migrateReportV2ToV3 / readReportDocument (version read on the raw value, JS truthiness kept, a malformed mapped path still fails the read), rebaseReportOnSheet (??= labels, archived names first-match), buildSheetSnapshot / assertSnapshot (raw depth, shape, caps in UTF-16 and UTF-8, integrity), readArchiveDocument (layered: report first, wrapper, snapshot gate, sheet invariant, unsupported_envelope origin quirk). Checked against 84 cases frozen from the TypeScript and 765 Zod verdicts (one declared difference: L1, a lone surrogate reads as U+FFFD), the ported report and archive suites and the 612 legacy leaves. Facade: draft.restore (content kinds invalid / unsupported_version, rebase_failed never a content kind), archive.import (incompatible_version with found, no_attachment), archive.snapshot.
This commit is contained in:
1 parent
6c0533c1da
commit
21906c4358
28 files changed
+5239
-213
No files matched your search
@@ -0,0 +1,238 @@
|
||||
//! The Rust report and archive functions against what the TypeScript domain did on the same
|
||||
//! inputs (`crates/core/tests/oracles/characterisation.json`, written by
|
||||
//! `packages/domain/tests/r2-characterisation.test.ts`), and the Rust contracts against the
|
||||
//! accept / refuse verdicts of the Zod schemas (`verdicts.json`).
|
||||
#![allow(clippy::disallowed_methods, clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
mod common;
|
||||
|
||||
use faunosteo_core::domain::archive::{
|
||||
Branding, PdfLabelSet, ReportArchiveEnvelope, SheetSnapshot, assert_snapshot,
|
||||
build_sheet_snapshot, read_archive_document,
|
||||
};
|
||||
use faunosteo_core::domain::js::parse_json;
|
||||
use faunosteo_core::domain::report::v2::ReportV2;
|
||||
use faunosteo_core::domain::report::{
|
||||
ReadFailure, Report, ReportMigrationMap, read_report_document, rebase_report_on_sheet,
|
||||
};
|
||||
use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet, Reference};
|
||||
use faunosteo_core::json::to_js_pretty;
|
||||
use serde::Serialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
fn oracle(name: &str) -> (String, Value) {
|
||||
let text = common::repo_file(&format!("crates/core/tests/oracles/{name}"));
|
||||
let value = parse_json(&text).unwrap();
|
||||
(text, value)
|
||||
}
|
||||
|
||||
/// Object keys sorted at every level: equality whatever the declared field order.
|
||||
fn sorted(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut keys: Vec<&String> = map.keys().collect();
|
||||
keys.sort();
|
||||
let mut out = Map::new();
|
||||
for key in keys {
|
||||
out.insert(key.clone(), sorted(&map[key]));
|
||||
}
|
||||
Value::Object(out)
|
||||
}
|
||||
Value::Array(items) => Value::Array(items.iter().map(sorted).collect()),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pretty<T: Serialize>(value: &T) -> String {
|
||||
to_js_pretty(value).unwrap()
|
||||
}
|
||||
|
||||
struct Context {
|
||||
maps: Map<String, Value>,
|
||||
sheets: Map<String, Value>,
|
||||
}
|
||||
|
||||
impl Context {
|
||||
fn map(&self, case: &Value) -> ReportMigrationMap {
|
||||
let name = case["map"].as_str().unwrap_or("test");
|
||||
let text = self.maps[name].as_str().unwrap();
|
||||
serde_json::from_value(parse_json(text).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
fn sheet(&self, case: &Value) -> LoadedSheet {
|
||||
let bundle = self.sheets[case["sheet"].as_str().unwrap()].clone();
|
||||
let data: BundledSheetData = serde_json::from_value(bundle).unwrap();
|
||||
LoadedSheet::from_bundle(data).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn read_error(failure: &ReadFailure) -> Value {
|
||||
match failure {
|
||||
ReadFailure::UnsupportedVersion(found) => {
|
||||
json!({ "kind": "unsupported_version", "found": found })
|
||||
}
|
||||
ReadFailure::Invalid(_) => json!({ "kind": "invalid" }),
|
||||
}
|
||||
}
|
||||
|
||||
/// What Rust returns for a case: `Ok(output)` or `Err(error)` in the oracle's shapes.
|
||||
fn run(context: &Context, case: &Value) -> Result<Value, Value> {
|
||||
let input = parse_json(case["input"].as_str().unwrap()).unwrap();
|
||||
match case["fn"].as_str().unwrap() {
|
||||
"readReport" => read_report_document(&input, &context.map(case))
|
||||
.map(|o| serde_json::to_value(o).unwrap())
|
||||
.map_err(|f| read_error(&f)),
|
||||
"readArchive" => read_archive_document(&input, &context.map(case))
|
||||
.map(|o| serde_json::to_value(o).unwrap())
|
||||
.map_err(|f| read_error(&f)),
|
||||
"rebase" => {
|
||||
let archived = case["archived"]
|
||||
.as_str()
|
||||
.map(|t| assert_snapshot(&parse_json(t).unwrap()).unwrap());
|
||||
let report: Report = serde_json::from_value(input).unwrap();
|
||||
rebase_report_on_sheet(&report, &context.sheet(case), archived.as_ref())
|
||||
.map(|o| serde_json::to_value(o).unwrap())
|
||||
.map_err(|f| read_error(&f))
|
||||
}
|
||||
"buildSnapshot" => {
|
||||
let report: Report = serde_json::from_value(input).unwrap();
|
||||
Ok(serde_json::to_value(build_sheet_snapshot(&context.sheet(case), &report)).unwrap())
|
||||
}
|
||||
"assertSnapshot" => assert_snapshot(&input)
|
||||
.map(|s| serde_json::to_value(s).unwrap())
|
||||
.map_err(|r| json!({ "kind": r })),
|
||||
other => panic!("unknown fn {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The comparison of one case; `None` when Rust matches the TypeScript.
|
||||
fn mismatch(context: &Context, case: &Value) -> Option<String> {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let actual = run(context, case);
|
||||
match (&actual, case.get("output"), case.get("error")) {
|
||||
(Ok(out), Some(expected), None) => {
|
||||
// The archive's PDF labels follow the engine's dictionary order in Rust and the
|
||||
// Zod key order in TypeScript (D-R11): compared without the order there.
|
||||
let exact = !name.starts_with("readArchive");
|
||||
let same = if exact {
|
||||
pretty(out) == pretty(expected)
|
||||
} else {
|
||||
pretty(&sorted(out)) == pretty(&sorted(expected))
|
||||
&& pretty(&out["report"]) == pretty(&expected["report"])
|
||||
};
|
||||
(!same).then(|| format!("{name}: output differs\n rust: {}", pretty(out)))
|
||||
}
|
||||
(Err(error), None, Some(expected)) => {
|
||||
// Through the JavaScript printer: a found version 4 reads 4 on both sides.
|
||||
(pretty(error) != pretty(expected))
|
||||
.then(|| format!("{name}: error {error} != {expected}"))
|
||||
}
|
||||
_ => Some(format!(
|
||||
"{name}: rust {actual:?} vs ts output/error mismatch"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn cases(with_rules: bool) -> (Context, Vec<Value>) {
|
||||
let (_, value) = oracle("characterisation.json");
|
||||
let context = Context {
|
||||
maps: value["maps"].as_object().unwrap().clone(),
|
||||
sheets: value["sheets"].as_object().unwrap().clone(),
|
||||
};
|
||||
let list = value["cases"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c.get("needsRules").is_some() == with_rules)
|
||||
.cloned()
|
||||
.collect();
|
||||
(context, list)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rust_does_what_the_typescript_did() {
|
||||
let (context, list) = cases(false);
|
||||
assert!(list.len() > 80, "{} cases", list.len());
|
||||
let failures: Vec<String> = list.iter().filter_map(|c| mismatch(&context, c)).collect();
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// The cases whose outcome is a sheet integrity rule: they need the real rules of
|
||||
/// `sheet/validate.rs` (fork A) instead of the stub this branch carried.
|
||||
#[test]
|
||||
fn rust_does_what_the_typescript_did_with_the_integrity_rules() {
|
||||
let (context, list) = cases(true);
|
||||
assert!(!list.is_empty());
|
||||
let failures: Vec<String> = list.iter().filter_map(|c| mismatch(&context, c)).collect();
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
}
|
||||
|
||||
/// Decision L1: where `JSON.parse` keeps a lone surrogate (the TypeScript output still
|
||||
/// carries the `\ud800` escape), Rust reads U+FFFD; nothing else differs.
|
||||
#[test]
|
||||
fn lone_surrogates_are_the_one_declared_difference() {
|
||||
let (raw, value) = oracle("characterisation.json");
|
||||
let backslash = char::from(92);
|
||||
let lone_escape = format!("{backslash}ud800");
|
||||
let flagged: Vec<&Value> = value["cases"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|c| c.get("l1").is_some())
|
||||
.collect();
|
||||
assert_eq!(flagged.len(), 2);
|
||||
for case in flagged {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let line = raw.lines().find(|l| l.contains(name)).unwrap();
|
||||
let output = &line[line.find("\"output\"").unwrap()..];
|
||||
assert!(
|
||||
output.contains(&lone_escape),
|
||||
"{name}: TS output keeps the lone surrogate"
|
||||
);
|
||||
let context = cases(false).0;
|
||||
let rust = pretty(&run(&context, case).unwrap());
|
||||
assert!(rust.contains('\u{FFFD}'), "{name}: Rust reads U+FFFD");
|
||||
}
|
||||
}
|
||||
|
||||
fn verdict(schema: &str, input: &Value) -> bool {
|
||||
let input = input.clone();
|
||||
match schema {
|
||||
"Report" => serde_json::from_value::<Report>(input).is_ok(),
|
||||
"ReportV2" => serde_json::from_value::<ReportV2>(input).is_ok(),
|
||||
"MigrationMap" => serde_json::from_value::<ReportMigrationMap>(input).is_ok(),
|
||||
"Branding" => serde_json::from_value::<Branding>(input).is_ok(),
|
||||
"PdfLabelSet" => serde_json::from_value::<PdfLabelSet>(input).is_ok(),
|
||||
"SheetSnapshot" => serde_json::from_value::<SheetSnapshot>(input).is_ok(),
|
||||
"Envelope" => serde_json::from_value::<ReportArchiveEnvelope>(input).is_ok(),
|
||||
"Reference" => serde_json::from_value::<Reference>(input).is_ok(),
|
||||
other => panic!("unknown schema {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_contracts_accept_and_refuse_what_zod_does() {
|
||||
let (_, list) = oracle("verdicts.json");
|
||||
let list = list.as_array().unwrap();
|
||||
assert!(list.len() > 500, "{} verdicts", list.len());
|
||||
let failures: Vec<String> = list
|
||||
.iter()
|
||||
.filter_map(|v| {
|
||||
let schema = v["schema"].as_str().unwrap();
|
||||
let input = parse_json(v["input"].as_str().unwrap()).unwrap();
|
||||
let expected = v["accepted"].as_bool().unwrap();
|
||||
(verdict(schema, &input) != expected).then(|| {
|
||||
format!(
|
||||
"{schema} / {}: zod accepted={expected}",
|
||||
v["name"].as_str().unwrap()
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"{} mismatches:\n{}",
|
||||
failures.len(),
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user