pheon/tests/review.rs
Jan Petykiewicz a04a955e90 feat(review): add deterministic GDS dumps and structural comparisons
Read embedded layer-name labels, retain unsupported records, and report affected hierarchy as ASCII or Mermaid. Preserve duplicate objects, canonicalize polygon rings, and cover the first profile with ten fixture pairs and golden outputs.
2026-11-14 17:25:04 -08:00

668 lines
21 KiB
Rust

mod common;
use common::{library_header, record};
use klamath_rs_ext::{
records::*,
review::{Comparison, Document, LAYER_SENTINEL, hierarchy},
};
use std::{fs, path::PathBuf, process::Command};
fn ascii(bytes: &mut Vec<u8>, tag: u16, value: &str) {
let mut value = value.as_bytes().to_vec();
if value.len() % 2 == 1 {
value.push(0);
}
record(bytes, tag, &value);
}
fn xy(bytes: &mut Vec<u8>, points: &[[i32; 2]]) {
record(
bytes,
RTAG_XY,
&points
.iter()
.flatten()
.flat_map(|v| v.to_be_bytes())
.collect::<Vec<_>>(),
);
}
fn layout(cells: &[(&str, Vec<Vec<u8>>)]) -> Vec<u8> {
let mut bytes = library_header();
for (name, objects) in cells {
record(&mut bytes, RTAG_BGNSTR, &[0; 24]);
ascii(&mut bytes, RTAG_STRNAME, name);
for object in objects {
bytes.extend_from_slice(object);
}
record(&mut bytes, RTAG_ENDSTR, &[]);
}
record(&mut bytes, RTAG_ENDLIB, &[]);
bytes
}
fn polygon(points: &[[i32; 2]]) -> Vec<u8> {
let mut bytes = Vec::new();
record(&mut bytes, RTAG_BOUNDARY, &[]);
record(&mut bytes, RTAG_LAYER, &1_u16.to_be_bytes());
record(&mut bytes, RTAG_DATATYPE, &0_u16.to_be_bytes());
xy(&mut bytes, points);
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn square() -> Vec<u8> {
polygon(&[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]])
}
fn triangle() -> Vec<u8> {
polygon(&[[0, 0], [10, 0], [0, 10], [0, 0]])
}
fn reference(target: &str, x: i32, count: i16) -> Vec<u8> {
let mut bytes = Vec::new();
record(
&mut bytes,
if count == 1 { RTAG_SREF } else { RTAG_AREF },
&[],
);
ascii(&mut bytes, RTAG_SNAME, target);
if count == 1 {
xy(&mut bytes, &[[x, 0]]);
} else {
let counts: Vec<_> = [count, 1].into_iter().flat_map(i16::to_be_bytes).collect();
record(&mut bytes, RTAG_COLROW, &counts);
xy(&mut bytes, &[[x, 0], [x + 100, 0], [x, 0]]);
}
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn label(carrier: (u16, u16), text: &str) -> Vec<u8> {
let mut bytes = Vec::new();
record(&mut bytes, RTAG_TEXT, &[]);
record(&mut bytes, RTAG_LAYER, &carrier.0.to_be_bytes());
record(&mut bytes, RTAG_TEXTTYPE, &carrier.1.to_be_bytes());
xy(&mut bytes, &[[0, 0]]);
ascii(&mut bytes, RTAG_STRING, text);
record(&mut bytes, RTAG_ENDEL, &[]);
bytes
}
fn with_property(mut object: Vec<u8>, value: &str) -> Vec<u8> {
object.truncate(object.len() - 4);
record(&mut object, RTAG_PROPATTR, &17_u16.to_be_bytes());
ascii(&mut object, RTAG_PROPVALUE, value);
record(&mut object, RTAG_ENDEL, &[]);
object
}
fn shared(geometry: Vec<u8>) -> Vec<u8> {
layout(&[
(
"CHIP",
vec![reference("left", 0, 1), reference("right", 20, 1)],
),
("left", vec![reference("leaf", 0, 2)]),
("right", vec![reference("leaf", 0, 3)]),
("leaf", vec![geometry]),
])
}
struct Pair {
name: &'static str,
old: Vec<u8>,
new: Vec<u8>,
changed_cells: usize,
removed: usize,
added: usize,
metadata: usize,
}
// Ten deliberately small fixture pairs specify the first object profile.
fn corpus() -> Vec<Pair> {
let base = layout(&[("CHIP", vec![square(), label((2, 0), "port")])]);
let mut timestamps = base.clone();
timestamps[10] = 1; // BGNLIB payload, ignored by the object profile.
let meta = |name| {
layout(&[(
"CHIP",
vec![
square(),
label((900, 7), LAYER_SENTINEL),
label((900, 7), name),
],
)])
};
vec![
Pair {
name: "record reordering",
old: base.clone(),
new: layout(&[("CHIP", vec![label((2, 0), "port"), square()])]),
changed_cells: 0,
removed: 0,
added: 0,
metadata: 0,
},
Pair {
name: "timestamp edit",
old: base,
new: timestamps,
changed_cells: 0,
removed: 0,
added: 0,
metadata: 0,
},
Pair {
name: "polygon start and winding",
old: layout(&[("CHIP", vec![square()])]),
new: layout(&[(
"CHIP",
vec![polygon(&[[10, 10], [10, 0], [0, 0], [0, 10], [10, 10]])],
)]),
changed_cells: 0,
removed: 0,
added: 0,
metadata: 0,
},
Pair {
name: "duplicate shape",
old: layout(&[("CHIP", vec![square()])]),
new: layout(&[("CHIP", vec![square(), square()])]),
changed_cells: 1,
removed: 0,
added: 1,
metadata: 0,
},
Pair {
name: "same bounds different geometry",
old: layout(&[("CHIP", vec![square()])]),
new: layout(&[("CHIP", vec![triangle()])]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "moved reference",
old: layout(&[
("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![square()]),
]),
new: layout(&[
("CHIP", vec![reference("leaf", 5, 1)]),
("leaf", vec![square()]),
]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "array count",
old: layout(&[
("CHIP", vec![reference("leaf", 0, 2)]),
("leaf", vec![square()]),
]),
new: layout(&[
("CHIP", vec![reference("leaf", 0, 3)]),
("leaf", vec![square()]),
]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "element property",
old: layout(&[("CHIP", vec![with_property(square(), "old")])]),
new: layout(&[("CHIP", vec![with_property(square(), "new")])]),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
Pair {
name: "layer name only",
old: meta("1:0:WG"),
new: meta("1:0:CORE:WG"),
changed_cells: 0,
removed: 0,
added: 0,
metadata: 1,
},
Pair {
name: "shared changed descendant",
old: shared(square()),
new: shared(triangle()),
changed_cells: 1,
removed: 1,
added: 1,
metadata: 0,
},
]
}
#[test]
fn ten_fixture_pairs_have_explicit_expected_changes() {
for pair in corpus() {
let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new);
assert!(diff.issues.is_empty(), "{}: {:?}", pair.name, diff.issues);
assert_eq!(diff.cells.len(), pair.changed_cells, "{}", pair.name);
assert_eq!(
diff.cells.iter().map(|c| c.removed.len()).sum::<usize>(),
pair.removed,
"{}",
pair.name
);
assert_eq!(
diff.cells.iter().map(|c| c.added.len()).sum::<usize>(),
pair.added,
"{}",
pair.name
);
assert_eq!(diff.layer_names.len(), pair.metadata, "{}", pair.name);
let equal = pair.changed_cells + pair.metadata == 0;
assert_eq!(diff.is_equal(), equal, "{}", pair.name);
assert_eq!(
old.canonical_dump() == new.canonical_dump(),
equal,
"{}",
pair.name
);
assert_eq!(diff.exit_code(), if equal { 0 } else { 1 });
}
}
#[test]
fn canonical_polygon_dump_is_readable_and_offsets_are_separate() {
let bytes = layout(&[("CHIP", vec![square()])]);
let doc = Document::parse(&bytes).unwrap();
let dump = doc.canonical_dump();
assert!(
dump.ends_with(
"cell \"CHIP\"\n BOUNDARY layer=1 datatype=0 xy=[0, 0, 0, 10, 10, 10, 10, 0, 0, 0]\n"
),
"{dump}"
);
assert!(!dump.contains("BGNSTR"));
assert!(
doc.record_dump()
.contains("0000000000 0002 HEADER size=6 [600]")
);
assert!(doc.record_dump().contains("BGNSTR"));
}
#[test]
fn canonical_dump_and_hierarchy_match_versioned_goldens() {
let bytes = layout(&[(
"CHIP",
vec![
square(),
label((900, 7), LAYER_SENTINEL),
label((900, 7), "1:0:WG"),
],
)]);
assert_eq!(
Document::parse(&bytes).unwrap().canonical_dump(),
include_str!("golden/review-canonical.txt")
);
let a = shared(square());
let b = shared(triangle());
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(
hierarchy(&a, &b, Some(&diff), false, 8),
include_str!("golden/review-hierarchy.txt")
);
assert_eq!(
hierarchy(&a, &b, Some(&diff), true, 8),
include_str!("golden/review-hierarchy.mmd")
);
}
#[test]
fn misplaced_library_fields_and_nul_names_are_rejected() {
let mut late = layout(&[("CHIP", vec![])]);
late.truncate(late.len() - 4);
ascii(&mut late, RTAG_LIBNAME, "late");
record(&mut late, RTAG_ENDLIB, &[]);
assert!(
Document::parse(&late)
.unwrap_err()
.contains("library field outside")
);
assert!(
Document::parse(&layout(&[("CH\0IP", vec![])]))
.unwrap_err()
.contains("NUL")
);
}
#[test]
fn cell_and_property_order_do_not_affect_comparison() {
let a = with_property(with_property(square(), "a"), "b");
let b = with_property(with_property(square(), "b"), "a");
let a = layout(&[("z", vec![a]), ("a", vec![])]);
let b = layout(&[("a", vec![]), ("z", vec![b])]);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
assert!(Comparison::between(&a, &b).is_equal());
assert_eq!(a.canonical_dump(), b.canonical_dump());
}
#[test]
fn metadata_requires_a_sentinel_in_the_same_cell_and_carrier_pair() {
let bytes = layout(&[
(
"CHIP",
vec![
label((900, 7), LAYER_SENTINEL),
label((900, 7), "1:0:WG"),
label((900, 8), "2:0:ordinary text"),
],
),
("OTHER", vec![label((900, 7), "3:0:ordinary text")]),
]);
let doc = Document::parse(&bytes).unwrap();
assert_eq!(doc.layer_names.len(), 1);
assert_eq!(doc.layer_names.get(&(1, 0)).unwrap(), "WG");
assert!(doc.canonical_dump().contains("2:0:ordinary text"));
assert!(doc.canonical_dump().contains("3:0:ordinary text"));
assert!(!doc.canonical_dump().contains(LAYER_SENTINEL));
let conflicts = layout(&[(
"CHIP",
vec![
label((9, 0), LAYER_SENTINEL),
label((9, 0), "1:0:A"),
label((9, 0), "1:0:B"),
],
)]);
assert!(
Document::parse(&conflicts)
.unwrap_err()
.contains("conflicting names")
);
assert!(
klamath_rs_ext::review::dump_records(&conflicts)
.unwrap()
.contains("1:0:B")
);
let future = layout(&[("CHIP", vec![label((9, 0), "KLAMATH_LAYER_NAMES_V2")])]);
let future = Document::parse(&future).unwrap();
assert_eq!(Comparison::between(&future, &future).exit_code(), 2);
}
#[test]
fn unknown_records_never_produce_a_successful_equality_claim() {
let mut unknown = square();
unknown.truncate(unknown.len() - 4);
record(&mut unknown, 0x7f00, &[]);
record(&mut unknown, RTAG_ENDEL, &[]);
let bytes = layout(&[("CHIP", vec![unknown])]);
let doc = Document::parse(&bytes).unwrap();
let diff = Comparison::between(&doc, &doc);
assert!(!diff.is_equal());
assert_eq!(diff.exit_code(), 2);
assert!(doc.record_dump().contains("7f00"));
assert!(diff.text(0).contains("INCOMPLETE"));
}
#[test]
fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() {
let a = shared(square());
let b = shared(triangle());
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(
hierarchy(&a, &b, Some(&diff), false, 8),
concat!(
"\"CHIP\" x1 [affected]\n",
" \"left\" x1 [affected]\n",
" \"leaf\" x2 [cell changed]\n",
" \"right\" x1 [affected]\n",
" \"leaf\" x3 [cell changed] [shown above]\n",
)
);
let graph = hierarchy(&a, &b, Some(&diff), true, 8);
assert_eq!(graph.matches("leaf [cell changed]").count(), 1);
assert!(graph.contains("x2"));
assert!(graph.contains("x3"));
let limited = hierarchy(&a, &b, Some(&diff), false, 1);
assert!(!limited.contains("\"leaf\""));
assert!(limited.contains("children omitted"));
}
#[test]
fn reference_changes_keep_unchanged_targets_and_old_edges_visible() {
for pair in corpus()
.into_iter()
.filter(|p| p.name == "moved reference" || p.name == "array count")
{
let old = Document::parse(&pair.old).unwrap();
let new = Document::parse(&pair.new).unwrap();
let diff = Comparison::between(&old, &new);
let tree = hierarchy(&old, &new, Some(&diff), false, 8);
assert!(tree.contains("[cell unchanged]"), "{tree}");
assert!(tree.contains("[reference changed]"), "{tree}");
if pair.name == "array count" {
assert!(tree.contains("x2 -> x3"), "{tree}");
}
}
let a = layout(&[
("CHIP", vec![reference("leaf", 0, 1)]),
("leaf", vec![square()]),
]);
let b = layout(&[("CHIP", vec![])]);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let tree = hierarchy(&a, &b, Some(&Comparison::between(&a, &b)), false, 8);
assert!(tree.contains("\"leaf\" x1 -> x0"), "{tree}");
}
#[test]
fn same_bounds_changes_and_truncated_reports_remain_differences() {
let a = layout(&[("CHIP", vec![square()])]);
let b = layout(&[("CHIP", vec![triangle()])]);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(
diff.cells[0].removed[0].bounds,
diff.cells[0].added[0].bounds
);
assert!(diff.text(0).contains("0 of 2 object changes shown"));
assert_eq!(diff.exit_code(), 1);
assert!(diff.cells[0].removed[0].offset > 0);
}
#[test]
fn unit_changes_report_values_without_claiming_geometry_equivalence() {
let a = layout(&[("CHIP", vec![square()])]);
let units = Document::parse(&a)
.unwrap()
.records
.iter()
.find(|r| r.tag == RTAG_UNITS)
.unwrap()
.offset;
let mut b = a.clone();
b[units + 12..units + 20].copy_from_slice(
&klamath_rs_ext::basic::encode_real8(2e-9)
.unwrap()
.to_be_bytes(),
);
let a = Document::parse(&a).unwrap();
let b = Document::parse(&b).unwrap();
let diff = Comparison::between(&a, &b);
assert_eq!(diff.exit_code(), 1);
assert_eq!(diff.library_fields.len(), 1);
assert_eq!(diff.library_fields[0].field, "UNITS");
assert!(diff.text(0).contains("UNITS changed"));
assert!(diff.cells.is_empty());
}
#[test]
fn dangling_references_cycles_and_duplicate_cell_names_are_reported() {
let missing = layout(&[("CHIP", vec![reference("missing", 0, 1)])]);
let missing = Document::parse(&missing).unwrap();
assert!(
missing
.issues
.iter()
.any(|s| s.contains("unresolved reference"))
);
let cycle = layout(&[
("a", vec![reference("b", 0, 1)]),
("b", vec![reference("a", 0, 1)]),
]);
let cycle = Document::parse(&cycle).unwrap();
assert!(cycle.issues.iter().any(|s| s.contains("cyclic")));
assert!(hierarchy(&cycle, &cycle, None, false, 8).len() < 200);
let duplicate = layout(&[("a", vec![]), ("a", vec![])]);
assert!(
Document::parse(&duplicate)
.unwrap_err()
.contains("duplicate cell")
);
}
#[test]
fn absolute_transform_flags_are_not_discarded() {
let a = reference("leaf", 0, 1);
let mut b = Vec::new();
record(&mut b, RTAG_SREF, &[]);
ascii(&mut b, RTAG_SNAME, "leaf");
record(&mut b, RTAG_STRANS, &[0, 2]);
xy(&mut b, &[[0, 0]]);
record(&mut b, RTAG_ENDEL, &[]);
let a = layout(&[("CHIP", vec![a]), ("leaf", vec![])]);
let b = layout(&[("CHIP", vec![b]), ("leaf", vec![])]);
assert_eq!(
Comparison::between(&Document::parse(&a).unwrap(), &Document::parse(&b).unwrap())
.exit_code(),
1
);
}
#[test]
fn polygon_normalization_handles_repeated_minimum_vertices() {
let ring = [[0, 0], [4, 0], [4, 4], [0, 0], [-2, 2], [-2, 4], [0, 0]];
let baseline = layout(&[("CHIP", vec![polygon(&ring)])]);
let baseline = Document::parse(&baseline).unwrap();
let mut open = ring[..ring.len() - 1].to_vec();
for _ in 0..2 {
for start in 0..open.len() {
let mut rotated = open[start..]
.iter()
.chain(&open[..start])
.copied()
.collect::<Vec<_>>();
rotated.push(rotated[0]);
let candidate = layout(&[("CHIP", vec![polygon(&rotated)])]);
let candidate = Document::parse(&candidate).unwrap();
assert!(Comparison::between(&baseline, &candidate).is_equal());
}
open.reverse();
}
}
#[test]
fn malformed_lengths_fields_and_units_return_errors_without_panicking() {
let good = layout(&[("CHIP", vec![square()])]);
for length in 0..good.len() {
assert!(
Document::parse(&good[..length]).is_err(),
"accepted truncated length {length}"
);
}
let mut bad = good.clone();
bad[0..2].copy_from_slice(&3_u16.to_be_bytes());
assert!(Document::parse(&bad).is_err());
let mut bad = good.clone();
let units = Document::parse(&good)
.unwrap()
.records
.iter()
.find(|r| r.tag == RTAG_UNITS)
.unwrap()
.offset;
bad[units + 4..units + 20].fill(0);
assert!(Document::parse(&bad).unwrap_err().contains("UNITS"));
let mut polygon = square();
polygon.truncate(polygon.len() - 4);
record(&mut polygon, RTAG_LAYER, &[0, 1]);
record(&mut polygon, RTAG_ENDEL, &[]);
assert!(
Document::parse(&layout(&[("CHIP", vec![polygon])]))
.unwrap_err()
.contains("duplicate element field")
);
}
#[test]
fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() {
let directory = std::env::temp_dir().join(format!("klamath review {}", std::process::id()));
fs::create_dir_all(&directory).unwrap();
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
let _cleanup = Cleanup(directory.clone());
let old = directory.join("old file.gds");
let new = directory.join("new file.gds");
fs::write(&old, shared(square())).unwrap();
fs::write(&new, shared(triangle())).unwrap();
let command = || Command::new(env!("CARGO_BIN_EXE_klamath"));
let equal = command().arg("diff").arg(&old).arg(&old).output().unwrap();
assert_eq!(equal.status.code(), Some(0));
let diff = command()
.arg("diff")
.arg(&old)
.arg(&new)
.args(["--hierarchy", "mermaid", "--max-changes", "0"])
.output()
.unwrap();
assert_eq!(diff.status.code(), Some(1));
let text = String::from_utf8(diff.stdout).unwrap();
assert!(text.contains("0 of 2 object changes shown"));
assert!(text.contains("```mermaid\nflowchart TD"));
let dump = command()
.arg("dump")
.arg(&old)
.args(["--records"])
.output()
.unwrap();
assert_eq!(dump.status.code(), Some(0));
assert!(String::from_utf8(dump.stdout).unwrap().contains("BGNSTR"));
let graph = command()
.arg("hierarchy")
.arg(&old)
.args(["--format", "mermaid"])
.output()
.unwrap();
assert_eq!(graph.status.code(), Some(0));
assert!(
String::from_utf8(graph.stdout)
.unwrap()
.starts_with("flowchart TD")
);
fs::write(&new, b"invalid").unwrap();
assert_eq!(
command()
.arg("diff")
.arg(&old)
.arg(&new)
.output()
.unwrap()
.status
.code(),
Some(2)
);
}