interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-crumb / tests / parity.rs

477 lines · 17398 bytes Raw Blame History
1//! Parity with the reference `crumb.c` (aien-architecture 29780e5), via the golden files
2//! written by `scripts/crumb-parity.sh`. Each fixture `dot.crumb` stands for `.crumb`.
3//!
4//! The leaf entry must match `sniff` and `validate`; `nearest` and `inherited_invariants`
5//! must match `explain`. Fixtures where the tools deliberately disagree (ADR 0004 sections
6//! 2.2 and 2.3) are listed in [`DIVERGENCES`] and asserted field by field on both sides, so
7//! a change in either tool fails a test instead of being skipped.
8
9use std::collections::BTreeMap;
10use std::fs;
11use std::path::{Path, PathBuf};
12use synapse_crumb::json::JsonError;
13use synapse_crumb::{
14 crumb_path, CrumbContext, CrumbContextEntry, CrumbFile, Dialect, DirectoryCrumb, EntryStatus,
15 InvalidReason, MAX_CRUMB_BYTES, ROOT_DIR,
16};
17
18const TARGETS: [&str; 16] = [
19 ".",
20 "d1",
21 "d1/nested",
22 "d1/nested/deeper",
23 "d2",
24 "d3",
25 "badjson",
26 "gap",
27 "gap/inner",
28 "unknown",
29 "bom",
30 "scalar",
31 "latin1",
32 "nuljunk",
33 "dupkey",
34 "surrogate",
35];
36
37fn manifest() -> PathBuf {
38 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
39}
40
41fn walk(dir: &Path, base: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
42 for e in fs::read_dir(dir).unwrap() {
43 let p = e.unwrap().path();
44 if p.is_dir() {
45 walk(&p, base, out);
46 } else {
47 let rel = p.strip_prefix(base).unwrap().to_str().unwrap().to_string();
48 let rel = match rel.strip_suffix("dot.crumb") {
49 Some(prefix) => format!("{prefix}.crumb"),
50 None => rel,
51 };
52 out.insert(rel, fs::read(&p).unwrap());
53 }
54 }
55}
56
57fn fixture_tree() -> BTreeMap<String, Vec<u8>> {
58 let base = manifest().join("tests/fixtures/tree");
59 let mut map = BTreeMap::new();
60 walk(&base, &base, &mut map);
61 map
62}
63
64fn context(tree: &BTreeMap<String, Vec<u8>>, target: &str) -> CrumbContext {
65 CrumbContext::resolve(target, |p| {
66 Ok(tree
67 .get(p)
68 .map_or(CrumbFile::Missing, |b| CrumbFile::Bytes(b.clone())))
69 })
70 .unwrap()
71}
72
73/// Lines of the golden block `### <kind> <target>`.
74fn golden_block(kind: &str, target: &str) -> Vec<String> {
75 let text = fs::read_to_string(manifest().join(format!("tests/golden/{kind}.txt"))).unwrap();
76 let header = format!("### {kind} {target}");
77 let mut lines = text.lines().skip_while(|l| *l != header);
78 assert_eq!(
79 lines.next(),
80 Some(header.as_str()),
81 "missing golden block {header}"
82 );
83 lines
84 .take_while(|l| !l.starts_with("### "))
85 .map(str::to_string)
86 .collect()
87}
88
89/// The golden `validate` line about one directory's `.crumb`, if crumb.c printed one.
90fn golden_validate_line(dir: &str) -> Option<String> {
91 let text = fs::read_to_string(manifest().join("tests/golden/validate.txt")).unwrap();
92 let f = abs_crumb(dir);
93 text.lines()
94 .find(|l| {
95 (l.starts_with("INVALID ") || l.starts_with("LEGACY "))
96 && (l.contains(&format!(" {f}:")) || l.contains(&format!(" {f} (")))
97 })
98 .map(str::to_string)
99}
100
101fn abs_crumb(dir: &str) -> String {
102 if dir == ROOT_DIR {
103 "<ROOT>/.crumb".to_string()
104 } else {
105 format!("<ROOT>/{dir}/.crumb")
106 }
107}
108
109fn abs_dir(dir: &str) -> String {
110 if dir == ROOT_DIR {
111 "<ROOT>".to_string()
112 } else {
113 format!("<ROOT>/{dir}")
114 }
115}
116
117/// A fixture where Synapse and crumb.c deliberately disagree (ADR 0004 section 2.3).
118/// Every field is asserted, so drift on either side fails a test instead of being skipped.
119struct Divergence {
120 target: &'static str,
121 /// The leaf status Synapse must report.
122 synapse: fn(&EntryStatus) -> bool,
123 /// crumb.c `sniff` lines after the `sniff <dir> as parity` header.
124 sniff: &'static [&'static str],
125 /// crumb.c `validate` line for the file, or `None` when crumb.c finds it valid.
126 validate: Option<&'static str>,
127 /// Directory crumb.c `explain` reports as NEAREST CRUMB.
128 crumb_c_nearest: &'static str,
129 /// Directory Synapse reports as nearest.
130 synapse_nearest: &'static str,
131}
132
133const DIVERGENCES: [Divergence; 6] = [
134 // crumb.c reads any JSON object; Synapse refuses an object of no known dialect.
135 Divergence {
136 target: "unknown",
137 synapse: |s| *s == EntryStatus::Invalid(InvalidReason::UnknownJsonDialect),
138 sniff: &[
139 " .crumb: unknown-object | JSON object with neither schema_version nor version.",
140 " invariant: unknown invariant",
141 ],
142 validate: Some(
143 "INVALID <ROOT>/unknown/.crumb: needs schema_version \"1.0.0\", name, purpose",
144 ),
145 crumb_c_nearest: "unknown",
146 synapse_nearest: ROOT_DIR,
147 },
148 // crumb.c sniff prints any parsed JSON value, even a top-level string.
149 Divergence {
150 target: "scalar",
151 synapse: |s| *s == EntryStatus::Invalid(InvalidReason::UnrecognizedFormat),
152 sniff: &[" .crumb: ? | (legacy format)"],
153 validate: Some("INVALID <ROOT>/scalar/.crumb: not a JSON object"),
154 crumb_c_nearest: ROOT_DIR,
155 synapse_nearest: ROOT_DIR,
156 },
157 // crumb.c copies string bytes without checking UTF-8; Synapse refuses non-UTF-8.
158 Divergence {
159 target: "latin1",
160 synapse: |s| *s == EntryStatus::Invalid(InvalidReason::NotUtf8),
161 sniff: &[
162 " .crumb: latin1 | RFC-0001 document with one Latin-1 byte in an unprinted field.",
163 ],
164 validate: None,
165 crumb_c_nearest: "latin1",
166 synapse_nearest: ROOT_DIR,
167 },
168 // crumb.c parses a C string, so a NUL ends the document; Synapse refuses the trailing bytes.
169 Divergence {
170 target: "nuljunk",
171 synapse: |s| {
172 matches!(
173 s,
174 EntryStatus::Invalid(InvalidReason::Json(JsonError::Syntax { .. }))
175 )
176 },
177 sniff: &[" .crumb: nuljunk | RFC-0001 document followed by a NUL byte and junk."],
178 validate: None,
179 crumb_c_nearest: "nuljunk",
180 synapse_nearest: ROOT_DIR,
181 },
182 // crumb.c keeps the last value of a duplicated key; Synapse refuses duplicates.
183 Divergence {
184 target: "dupkey",
185 synapse: |s| {
186 matches!(
187 s,
188 EntryStatus::Invalid(InvalidReason::Json(JsonError::DuplicateKey { .. }))
189 )
190 },
191 sniff: &[" .crumb: dupkey | second purpose"],
192 validate: None,
193 crumb_c_nearest: "dupkey",
194 synapse_nearest: ROOT_DIR,
195 },
196 // crumb.c turns a lone UTF-16 surrogate escape into U+FFFD; Synapse refuses it.
197 Divergence {
198 target: "surrogate",
199 synapse: |s| {
200 matches!(
201 s,
202 EntryStatus::Invalid(InvalidReason::Json(JsonError::Syntax { .. }))
203 )
204 },
205 sniff: &[" .crumb: surrogate | lone surrogate [\u{FFFD}] here"],
206 validate: None,
207 crumb_c_nearest: "surrogate",
208 synapse_nearest: ROOT_DIR,
209 },
210];
211
212fn divergence(target: &str) -> Option<&'static Divergence> {
213 DIVERGENCES.iter().find(|d| d.target == target)
214}
215
216/// What crumb.c `sniff` prints for the directory's own `.crumb`, derived from the typed leaf,
217/// or `None` when the Synapse status has no single crumb.c rendering (only allowed for
218/// [`DIVERGENCES`]). crumb.c reads only JSON and only top-level string `name`/`purpose`:
219/// D2 has neither (its `purpose` is an object), and D3 is not JSON.
220fn sniff_lines(target: &str, leaf: &CrumbContextEntry) -> Option<Vec<String>> {
221 let mut out = vec![format!("sniff {} as parity", abs_dir(target))];
222 match &leaf.status {
223 EntryStatus::Present(DirectoryCrumb::Rfc0001(c)) => {
224 out.push(format!(" .crumb: {} | {}", c.name, c.purpose));
225 out.extend(c.invariants.iter().map(|i| format!(" invariant: {i}")));
226 }
227 EntryStatus::Present(DirectoryCrumb::Atlas(_)) => {
228 out.push(" .crumb: ? | (legacy format)".to_string())
229 }
230 EntryStatus::Present(DirectoryCrumb::YamlV1(_))
231 | EntryStatus::Missing
232 | EntryStatus::Invalid(InvalidReason::UnrecognizedFormat)
233 | EntryStatus::Invalid(InvalidReason::Json(JsonError::Syntax { .. })) => {
234 out.push(" no .crumb here".to_string())
235 }
236 _ => return None,
237 }
238 Some(out)
239}
240
241/// What crumb.c `validate` prints for one `.crumb`: `Some(None)` for nothing, `None` when
242/// the Synapse status has no single crumb.c rendering (only allowed for [`DIVERGENCES`]).
243fn validate_line(e: &CrumbContextEntry) -> Option<Option<String>> {
244 let f = abs_crumb(&e.dir);
245 Some(match &e.status {
246 EntryStatus::Missing | EntryStatus::Present(DirectoryCrumb::Rfc0001(_)) => None,
247 EntryStatus::Present(DirectoryCrumb::Atlas(_)) => {
248 Some(format!("LEGACY {f} (pre-RFC format, not validated)"))
249 }
250 EntryStatus::Present(DirectoryCrumb::YamlV1(_))
251 | EntryStatus::Invalid(
252 InvalidReason::UnrecognizedFormat
253 | InvalidReason::Json(JsonError::Syntax { .. })
254 | InvalidReason::NotJsonObject,
255 ) => Some(format!("INVALID {f}: not a JSON object")),
256 EntryStatus::Invalid(
257 InvalidReason::UnknownJsonDialect
258 | InvalidReason::UnsupportedSchemaVersion
259 | InvalidReason::MissingField {
260 dialect: Dialect::Rfc0001Json,
261 ..
262 },
263 ) => Some(format!(
264 "INVALID {f}: needs schema_version \"1.0.0\", name, purpose"
265 )),
266 _ => return None,
267 })
268}
269
270/// crumb.c `explain` NEAREST CRUMB and INHERITED INVARIANTS, from the typed context, or
271/// `None` when the nearest crumb has no crumb.c rendering (D3, asserted separately).
272/// `export:` and `related:` lines are not modelled by Synapse and are dropped from both sides.
273fn explain_lines(ctx: &CrumbContext) -> Option<Vec<String>> {
274 let mut out = vec!["== NEAREST CRUMB ==".to_string()];
275 match ctx.nearest() {
276 None => out.push(" (no .crumb found at or above this path)".to_string()),
277 Some(e) => {
278 out.push(format!(" file: {}", abs_crumb(&e.dir)));
279 let (name, layer, purpose, inv): (&str, &str, &str, &[String]) = match e.crumb() {
280 Some(DirectoryCrumb::Rfc0001(c)) => (
281 &c.name,
282 c.layer.as_deref().unwrap_or(""),
283 &c.purpose,
284 &c.invariants,
285 ),
286 Some(DirectoryCrumb::Atlas(_)) => ("", "", "", &[]),
287 _ => return None,
288 };
289 out.push(format!(" name: {name}"));
290 out.push(format!(" layer: {layer}"));
291 out.push(format!(" purpose: {purpose}"));
292 if inv.is_empty() {
293 out.push(" invariant: (none)".to_string());
294 }
295 out.extend(inv.iter().map(|i| format!(" invariant: {i}")));
296 }
297 }
298 out.push("== INHERITED INVARIANTS ==".to_string());
299 let inherited = ctx.inherited_invariants();
300 if inherited.is_empty() {
301 out.push(" (none)".to_string());
302 }
303 out.extend(
304 inherited
305 .iter()
306 .map(|(d, i)| format!(" from {}: {i}", abs_crumb(d))),
307 );
308 Some(out)
309}
310
311fn without_unmodelled(lines: Vec<String>) -> Vec<String> {
312 lines
313 .into_iter()
314 .filter(|l| !l.starts_with(" export: ") && !l.starts_with(" related: "))
315 .collect()
316}
317
318#[test]
319fn pinned_source_matches_script() {
320 let pin = fs::read_to_string(manifest().join("tests/golden/PIN")).unwrap();
321 assert!(pin.contains("commit 29780e56c9e6b9111d884e0d4b146737228c19f6"));
322 assert!(pin.contains(
323 "crumb.c sha256 ef0f6566fb838917a750eb898f66596b76aa15a53d7d61bedac03c4c963ee147"
324 ));
325}
326
327#[test]
328fn script_targets_match_test_targets() {
329 let script = fs::read_to_string(manifest().join("../../scripts/crumb-parity.sh")).unwrap();
330 let start = script.find("TARGETS=(").unwrap() + "TARGETS=(".len();
331 let end = start + script[start..].find(')').unwrap();
332 let listed: Vec<&str> = script[start..end].split_whitespace().collect();
333 assert_eq!(listed, TARGETS);
334}
335
336#[test]
337fn fixtures_stay_below_the_size_cap() {
338 for (path, bytes) in fixture_tree() {
339 assert!((bytes.len() as u64) < MAX_CRUMB_BYTES, "{path}");
340 }
341}
342
343#[test]
344fn leaf_dialects_are_as_designed() {
345 let tree = fixture_tree();
346 let leaf = |t: &str| context(&tree, t).leaf().clone();
347 assert_eq!(leaf("d1").dialect(), Some(Dialect::Rfc0001Json));
348 assert_eq!(leaf("d2").dialect(), Some(Dialect::AtlasJson));
349 assert_eq!(leaf("d3").dialect(), Some(Dialect::YamlV1));
350 assert_eq!(leaf("gap").status, EntryStatus::Missing);
351 assert!(matches!(
352 leaf("badjson").status,
353 EntryStatus::Invalid(InvalidReason::Json(_))
354 ));
355 // A UTF-8 byte order mark is not JSON whitespace: refused by both tools.
356 assert_eq!(
357 leaf("bom").status,
358 EntryStatus::Invalid(InvalidReason::UnrecognizedFormat)
359 );
360 for d in &DIVERGENCES {
361 assert!((d.synapse)(&leaf(d.target).status), "{}", d.target);
362 }
363 match leaf("d2").crumb() {
364 Some(DirectoryCrumb::Atlas(a)) => assert_eq!(
365 a.purpose_statement.as_deref(),
366 Some("Pre-RFC Atlas spark-crumbs directory.")
367 ),
368 other => panic!("{other:?}"),
369 }
370}
371
372#[test]
373fn sniff_matches_crumb_c() {
374 let tree = fixture_tree();
375 for t in TARGETS {
376 let ctx = context(&tree, t);
377 let golden = golden_block("sniff", t);
378 let mapped = sniff_lines(t, ctx.leaf());
379 match divergence(t) {
380 Some(d) => {
381 assert_eq!(golden[1..], *d.sniff, "crumb.c sniff {t} drifted");
382 assert!((d.synapse)(&ctx.leaf().status), "Synapse sniff {t} drifted");
383 assert_ne!(mapped.as_ref(), Some(&golden), "{t} no longer diverges");
384 }
385 None => assert_eq!(
386 mapped.unwrap_or_else(|| panic!("{t}: unmapped status outside DIVERGENCES")),
387 golden,
388 "sniff {t}"
389 ),
390 }
391 }
392}
393
394#[test]
395fn validate_matches_crumb_c() {
396 let tree = fixture_tree();
397 for t in TARGETS {
398 let leaf = context(&tree, t).leaf().clone();
399 let golden = golden_validate_line(t);
400 let mapped = validate_line(&leaf);
401 match divergence(t) {
402 Some(d) => {
403 assert_eq!(
404 golden.as_deref(),
405 d.validate,
406 "crumb.c validate {t} drifted"
407 );
408 assert!((d.synapse)(&leaf.status), "Synapse validate {t} drifted");
409 // Synapse refuses every divergent fixture, so its own verdict is "invalid".
410 assert!(leaf.crumb().is_none(), "{t}");
411 }
412 None => assert_eq!(
413 mapped.unwrap_or_else(|| panic!("{t}: unmapped status outside DIVERGENCES")),
414 golden,
415 "validate {t}"
416 ),
417 }
418 }
419
420 let golden = fs::read_to_string(manifest().join("tests/golden/validate.txt")).unwrap();
421 let present = TARGETS
422 .iter()
423 .filter(|t| tree.contains_key(&crumb_path(t)))
424 .count();
425 assert!(golden.contains(&format!(
426 "{present} .crumb file(s), 0 directory(ies) with live local crumbs, INVALID found"
427 )));
428 assert!(golden.ends_with("exit 1\n"));
429}
430
431#[test]
432fn explain_matches_crumb_c() {
433 let tree = fixture_tree();
434 for t in TARGETS {
435 let ctx = context(&tree, t);
436 let golden = without_unmodelled(golden_block("explain", t));
437 if let Some(d) = divergence(t) {
438 assert_eq!(
439 golden[1],
440 format!(" file: {}", abs_crumb(d.crumb_c_nearest)),
441 "crumb.c explain {t} drifted"
442 );
443 assert_eq!(ctx.nearest().unwrap().dir, d.synapse_nearest, "{t}");
444 if d.crumb_c_nearest == d.synapse_nearest {
445 assert_eq!(explain_lines(&ctx).unwrap(), golden, "explain {t}");
446 }
447 continue;
448 }
449 match t {
450 // Divergence: crumb.c cannot parse D3, so it falls back to the root crumb;
451 // Synapse reports the typed D3 crumb as nearest.
452 "d3" => {
453 assert_eq!(golden[1], " file: <ROOT>/.crumb");
454 let n = ctx.nearest().unwrap();
455 assert_eq!((n.dir.as_str(), n.dialect()), ("d3", Some(Dialect::YamlV1)));
456 assert_eq!(explain_lines(&ctx), None);
457 assert!(ctx.inherited_invariants().len() == 2);
458 }
459 _ => assert_eq!(explain_lines(&ctx).unwrap(), golden, "explain {t}"),
460 }
461 }
462}
463
464#[test]
465fn chains_include_missing_intermediate_entries() {
466 let tree = fixture_tree();
467 let ctx = context(&tree, "gap/inner");
468 let s: Vec<(&str, bool)> = ctx
469 .entries()
470 .iter()
471 .map(|e| (e.dir.as_str(), e.status == EntryStatus::Missing))
472 .collect();
473 assert_eq!(s, [(".", false), ("gap", true), ("gap/inner", false)]);
474 let deeper = context(&tree, "d1/nested/deeper");
475 assert_eq!(deeper.entries().len(), 4);
476 assert_eq!(deeper.nearest().unwrap().dir, "d1/nested");
477}