cadmpeg-ir 0.6.1

CAD data model, validation, diffing, and codec API for cadmpeg.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
// SPDX-License-Identifier: Apache-2.0
//! Structural comparison of IR documents.
//!
//! Numbers compare through [`crate::compare`], so a coordinate that
//! differs only in the last place — what the same file decoded under two
//! platforms' libm produces — is not reported as a change, while an integer
//! count, index, or degree that moved by one always is. That module states the
//! tolerance and its caveats, including that the relation is not transitive:
//! every verdict here concerns exactly the two documents passed in.
//!
//! The comparison covers tolerances, every model and native arena, and
//! [`crate::document::SourceMeta`] — the source format id, all dialect layers,
//! and its attributes, where a codec records the program version, the object
//! count, and the rest of what it read out of the container.
//!
//! One class of attribute is carved out. A machine-local digest, named by the
//! [`crate::compare::LOCAL_DIGEST_SUFFIX`] convention, is a bitwise
//! fingerprint of the very values this module compares tolerantly: two decodes
//! that agree to fourteen significant digits hash differently, and no tolerance
//! can reconcile them. Reporting such a difference as a difference would make
//! every cross-platform comparison of one file report that file as changed.
//! [`SourceDiff::local_digests`] therefore reports them for information, outside
//! [`IrDiff::is_empty`] and outside the exit code derived from it, while every
//! other source attribute counts.
//!
//! A document with no `source` compares with an absent format, dialect set, and
//! attribute map. Two documents that both lack source metadata therefore agree,
//! and a document that gained populated source metadata differs.

use std::collections::BTreeMap;
use std::fmt;
use std::ops::Deref;

use crate::compare::{floats_agree, is_local_digest_attribute, values_agree};
use crate::document::ArenaName;
use cadmpeg_core::dialect::DialectLayers;
use cadmpeg_core::text::NonBlankString;

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::ser::SerializeTuple;
use serde::{Serialize, Serializer};
use serde_json::Value;

use crate::CadIr;

/// One differing source attribute.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct AttributeChange {
    /// Attribute key.
    pub key: NonBlankString,
    /// Value in the left-hand document, absent when only the right-hand document
    /// carries the key.
    pub left: Option<String>,
    /// Value in the right-hand document, absent when only the left-hand document
    /// carries the key.
    pub right: Option<String>,
}

/// Changes in the two documents' source metadata.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct SourceDiff {
    /// `(left, right)` source format ids, present only when they differ.
    #[cfg_attr(feature = "schema", schemars(with = "Option<(String, String)>"))]
    pub format_change: Option<FormatChange>,
    /// `(left, right)` complete dialect-layer sets, present when they differ.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(
        feature = "schema",
        schemars(with = "Option<(Option<DialectLayers>, Option<DialectLayers>)>")
    )]
    pub dialects_change: Option<DialectsChange>,
    /// Differing attributes, each a difference.
    pub attributes: Vec<AttributeChange>,
    /// Differing machine-local digest attributes, reported for information and
    /// never counted as a difference.
    ///
    /// See the module documentation: such a digest cannot agree across platforms,
    /// so a verdict that turned on one would call the same file changed.
    pub local_digests: Vec<AttributeChange>,
}

/// A change between two source formats, with absence represented explicitly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormatChange {
    before: Option<String>,
    after: Option<String>,
}

impl FormatChange {
    fn between(before: Option<&str>, after: Option<&str>) -> Option<Self> {
        (before != after).then(|| Self {
            before: before.map(str::to_owned),
            after: after.map(str::to_owned),
        })
    }

    /// Returns the left-hand source format, or `None` when it was absent.
    #[must_use]
    pub fn before(&self) -> Option<&str> {
        self.before.as_deref()
    }

    /// Returns the right-hand source format, or `None` when it is absent.
    #[must_use]
    pub fn after(&self) -> Option<&str> {
        self.after.as_deref()
    }
}

impl Serialize for FormatChange {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut tuple = serializer.serialize_tuple(2)?;
        tuple.serialize_element(self.before().unwrap_or(""))?;
        tuple.serialize_element(self.after().unwrap_or(""))?;
        tuple.end()
    }
}

/// A change between two complete dialect-layer sets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DialectsChange {
    before: Option<DialectLayers>,
    after: Option<DialectLayers>,
}

impl DialectsChange {
    fn between(before: Option<&DialectLayers>, after: Option<&DialectLayers>) -> Option<Self> {
        (before != after).then(|| Self {
            before: before.cloned(),
            after: after.cloned(),
        })
    }

    /// Returns the left-hand dialect layers, or `None` when they were absent.
    #[must_use]
    pub fn before(&self) -> Option<&DialectLayers> {
        self.before.as_ref()
    }

    /// Returns the right-hand dialect layers, or `None` when they are absent.
    #[must_use]
    pub fn after(&self) -> Option<&DialectLayers> {
        self.after.as_ref()
    }
}

impl Serialize for DialectsChange {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut tuple = serializer.serialize_tuple(2)?;
        tuple.serialize_element(&self.before)?;
        tuple.serialize_element(&self.after)?;
        tuple.end()
    }
}

impl SourceDiff {
    /// Returns `true` when nothing that counts as a difference changed.
    ///
    /// [`Self::local_digests`] is not consulted.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.format_change.is_none() && self.dialects_change.is_none() && self.attributes.is_empty()
    }
}

/// A non-empty list of top-level entity field names that differ.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(transparent)]
pub struct NonEmptyFields(Vec<String>);

impl NonEmptyFields {
    /// Construct a field list, rejecting the empty list.
    #[must_use]
    pub fn new(fields: Vec<String>) -> Option<Self> {
        (!fields.is_empty()).then_some(Self(fields))
    }
}

impl Deref for NonEmptyFields {
    type Target = [String];

    fn deref(&self) -> &[String] {
        &self.0
    }
}

impl<U> PartialEq<[U]> for NonEmptyFields
where
    String: PartialEq<U>,
{
    fn eq(&self, other: &[U]) -> bool {
        self.0.as_slice() == other
    }
}

impl<U, const N: usize> PartialEq<[U; N]> for NonEmptyFields
where
    String: PartialEq<U>,
{
    fn eq(&self, other: &[U; N]) -> bool {
        self.0.as_slice() == other.as_slice()
    }
}

/// A modified entity and its differing top-level fields.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct ModifiedEntity {
    /// Diff key of the entity, as produced by the arena's key function.
    pub id: String,
    /// Names of the top-level entity fields whose JSON-serialized values differ
    /// between the two documents.
    pub fields: NonEmptyFields,
}

/// Compared arena: a registered model arena or a native namespace arena.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ArenaKind {
    /// A model arena declared by `arena_registry!`.
    Model(ArenaName),
    /// A native namespace arena, serialized as `native.{format}.{name}`.
    Native {
        /// Source-format namespace.
        format: String,
        /// Arena name inside that namespace.
        name: String,
    },
}

impl ArenaKind {
    /// Native namespace arena named `native.{format}.{name}` on the wire.
    #[must_use]
    pub fn native(format: impl Into<String>, name: impl Into<String>) -> Self {
        Self::Native {
            format: format.into(),
            name: name.into(),
        }
    }
}

impl fmt::Display for ArenaKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Model(name) => f.write_str(name.as_str()),
            Self::Native { format, name } => write!(f, "native.{format}.{name}"),
        }
    }
}

impl PartialEq<str> for ArenaKind {
    fn eq(&self, other: &str) -> bool {
        match self {
            Self::Model(name) => name.as_str() == other,
            Self::Native { format, name } => {
                other
                    .strip_prefix("native.")
                    .and_then(|rest| rest.split_once('.'))
                    == Some((format.as_str(), name.as_str()))
            }
        }
    }
}

impl PartialEq<&str> for ArenaKind {
    fn eq(&self, other: &&str) -> bool {
        self == *other
    }
}

impl Serialize for ArenaKind {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for ArenaKind {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "ArenaKind".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        String::json_schema(generator)
    }
}

/// Changes within one entity arena.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct ArenaDiff {
    /// Arena name, matching the field name in [`crate::CadIr`] (e.g. `"faces"`).
    pub kind: ArenaKind,
    /// Diff keys of entities present only in the right-hand document.
    pub added: Vec<String>,
    /// Diff keys of entities present only in the left-hand document.
    pub removed: Vec<String>,
    /// Entities present in both documents with at least one differing field.
    pub modified: Vec<ModifiedEntity>,
}

/// Structural changes between two IR documents.
#[derive(Debug, Clone, PartialEq)]
pub struct IrDiff {
    /// `(left, right)` tolerances, present only when the two documents' tolerances differ.
    pub tolerance_change: Option<(crate::units::Tolerances, crate::units::Tolerances)>,
    /// Source-metadata changes, including the informational digest section.
    pub source: SourceDiff,
    /// Per-arena diffs, one entry per arena compared.
    pub per_arena: Vec<ArenaDiff>,
}

impl IrDiff {
    /// Returns `true` when neither tolerances, source metadata, nor any
    /// arena differ.
    ///
    /// A difference confined to [`SourceDiff::local_digests`] leaves this `true`.
    pub fn is_empty(&self) -> bool {
        self.tolerance_change.is_none()
            && self.source.is_empty()
            && self.per_arena.iter().all(|arena| {
                arena.added.is_empty() && arena.removed.is_empty() && arena.modified.is_empty()
            })
    }
}

#[derive(Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename = "IrDiff"))]
struct IrDiffWriteWire<'a> {
    unit_change: Option<(
        crate::units::CanonicalUnitsWire,
        crate::units::CanonicalUnitsWire,
    )>,
    tolerance_change: &'a Option<(crate::units::Tolerances, crate::units::Tolerances)>,
    source: &'a SourceDiff,
    per_arena: &'a [ArenaDiff],
}

impl Serialize for IrDiff {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        IrDiffWriteWire {
            unit_change: None,
            tolerance_change: &self.tolerance_change,
            source: &self.source,
            per_arena: &self.per_arena,
        }
        .serialize(serializer)
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for IrDiff {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "IrDiff".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        IrDiffWriteWire::json_schema(generator)
    }
}

/// Top-level field names whose values do not agree, tolerating last-place
/// disagreement in fractional numbers at any depth beneath a field.
///
/// A field present on one side and absent on the other always counts as
/// differing, so an `Option` that gained or lost a value is reported even when
/// the value would have agreed. The caller has found the two entities unequal,
/// so when their JSON values are identical the difference is one JSON does not
/// state, and the whole value is reported.
fn differing_fields<T: Serialize>(left: &T, right: &T) -> Vec<String> {
    let (Ok(Value::Object(left)), Ok(Value::Object(right))) =
        (serde_json::to_value(left), serde_json::to_value(right))
    else {
        return vec!["value".to_string()];
    };
    if left == right {
        return vec!["value".to_string()];
    }
    left.keys()
        .chain(right.keys())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .filter(|key| match (left.get(*key), right.get(*key)) {
            (Some(before), Some(after)) => values_agree(before, after).is_err(),
            (None, None) => false,
            _ => true,
        })
        .cloned()
        .collect()
}

fn arena<T, F>(kind: ArenaKind, left: &[T], right: &[T], identity: F) -> ArenaDiff
where
    T: PartialEq + Serialize,
    F: for<'a> Fn(&'a T) -> &'a str,
{
    let left: BTreeMap<_, _> = left
        .iter()
        .map(|entity| (identity(entity), entity))
        .collect();
    let right: BTreeMap<_, _> = right
        .iter()
        .map(|entity| (identity(entity), entity))
        .collect();
    let removed = left
        .keys()
        .filter(|id| !right.contains_key(*id))
        .map(|id| (*id).to_owned())
        .collect();
    let added = right
        .keys()
        .filter(|id| !left.contains_key(*id))
        .map(|id| (*id).to_owned())
        .collect();
    let modified = left
        .iter()
        .filter_map(|(id, before)| {
            let after = right.get(id)?;
            // Empty differing_fields means every difference JSON states was
            // below tolerance.
            if *before == *after {
                return None;
            }
            let fields = NonEmptyFields::new(differing_fields(*before, *after))?;
            Some(ModifiedEntity {
                id: (*id).to_owned(),
                fields,
            })
        })
        .collect();
    ArenaDiff {
        kind,
        added,
        removed,
        modified,
    }
}

macro_rules! define_diff_arenas {
    ($( $field:ident: $element:ty, $doc:literal, [$($attribute:meta),*] $(, [$($schema_attr:meta),*])?; )*) => {
        fn diff_arenas(left: &CadIr, right: &CadIr) -> Vec<ArenaDiff> {
            vec![$(arena(
                ArenaKind::Model(ArenaName::registered(stringify!($field))),
                &left.model.$field,
                &right.model.$field,
                crate::schema::EntitySchema::identity,
            )),*]
        }
    };
}
crate::document::arena_registry!(define_diff_arenas);

fn diff_native_namespaces(left: &CadIr, right: &CadIr) -> Vec<ArenaDiff> {
    let namespaces = left
        .native
        .0
        .keys()
        .chain(right.native.0.keys())
        .collect::<std::collections::BTreeSet<_>>();
    namespaces
        .into_iter()
        .flat_map(|namespace| {
            let left_ns = left.native.namespace(namespace);
            let right_ns = right.native.namespace(namespace);
            let arenas = left_ns
                .into_iter()
                .flat_map(|value| value.arenas().keys())
                .chain(right_ns.into_iter().flat_map(|value| value.arenas().keys()))
                .collect::<std::collections::BTreeSet<_>>();
            arenas.into_iter().map(move |name| {
                arena(
                    ArenaKind::native(namespace.as_str(), name.as_str()),
                    left_ns
                        .and_then(|value| value.arenas().get(name))
                        .map(Vec::as_slice)
                        .unwrap_or_default(),
                    right_ns
                        .and_then(|value| value.arenas().get(name))
                        .map(Vec::as_slice)
                        .unwrap_or_default(),
                    |record| record.id(),
                )
            })
        })
        .collect()
}

/// Whether two tolerance declarations agree, each component within the
/// comparator's tolerance.
fn tolerances_agree(left: crate::units::Tolerances, right: crate::units::Tolerances) -> bool {
    floats_agree(left.linear.get(), right.linear.get())
        && floats_agree(left.angular.get(), right.angular.get())
}

/// Compare the source metadata of two documents, classifying each differing
/// attribute as a difference or as an informational machine-local digest.
fn diff_source(left: &CadIr, right: &CadIr) -> SourceDiff {
    let empty_attributes = BTreeMap::new();
    let left_format = left
        .source
        .as_ref()
        .map(crate::document::SourceMeta::format);
    let right_format = right
        .source
        .as_ref()
        .map(crate::document::SourceMeta::format);
    let left_dialects = left.source.as_ref().and_then(|source| source.dialects());
    let right_dialects = right.source.as_ref().and_then(|source| source.dialects());
    let left_attributes = left
        .source
        .as_ref()
        .map_or(&empty_attributes, |source| &source.attributes);
    let right_attributes = right
        .source
        .as_ref()
        .map_or(&empty_attributes, |source| &source.attributes);
    let mut result = SourceDiff {
        format_change: FormatChange::between(left_format, right_format),
        dialects_change: DialectsChange::between(left_dialects, right_dialects),
        ..SourceDiff::default()
    };
    for change in attribute_changes(left_attributes, right_attributes) {
        if is_local_digest_attribute(change.key.as_str()) {
            result.local_digests.push(change);
        } else {
            result.attributes.push(change);
        }
    }
    result
}

/// Compare two string maps by key, reporting one change per differing key in
/// key order.
fn attribute_changes(
    left: &BTreeMap<NonBlankString, String>,
    right: &BTreeMap<NonBlankString, String>,
) -> Vec<AttributeChange> {
    left.keys()
        .chain(right.keys())
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .filter_map(|key| {
            let before = left.get(key);
            let after = right.get(key);
            (before != after).then(|| AttributeChange {
                key: key.clone(),
                left: before.cloned(),
                right: after.cloned(),
            })
        })
        .collect()
}

/// Compare tolerances, source metadata, and every entity arena by stable
/// entity ID.
///
/// Fractional numbers compare within the tolerance stated by
/// [`crate::compare`]; integers, strings, enums, and structure
/// compare exactly. Source attributes are strings and compare exactly; a
/// machine-local digest among them is reported without counting as a difference.
pub fn diff(left: &CadIr, right: &CadIr) -> IrDiff {
    let tolerance_change = (!tolerances_agree(left.tolerances, right.tolerances))
        .then_some((left.tolerances, right.tolerances));
    let mut per_arena = diff_arenas(left, right);
    per_arena.extend(diff_native_namespaces(left, right));
    IrDiff {
        tolerance_change,
        source: diff_source(left, right),
        per_arena,
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::diff;
    use crate::compare;
    use crate::examples::unit_cube;

    #[test]
    fn detects_changes_in_all_document_dimensions() {
        let left = unit_cube().expect("valid unit cube fixture");
        let mut right = left.clone();
        let moved = right.model.points[0].position().get();
        right.model.points[0].set_position(
            crate::features::FinitePoint3::new(crate::math::Point3::new(
                moved.x + 1.0,
                moved.y,
                moved.z,
            ))
            .expect("a finite position is a point"),
        );
        right.model.loops.pop();
        right.model.coedges.pop();

        let result = diff(&left, &right);
        assert!(!result.is_empty());
        assert_eq!(
            result
                .per_arena
                .iter()
                .find(|a| a.kind == "points")
                .expect("required invariant")
                .modified[0]
                .fields,
            ["position"]
        );
        assert_eq!(
            result
                .per_arena
                .iter()
                .find(|a| a.kind == "loops")
                .expect("required invariant")
                .removed
                .len(),
            1
        );
        assert_eq!(
            result
                .per_arena
                .iter()
                .find(|a| a.kind == "coedges")
                .expect("required invariant")
                .removed
                .len(),
            1
        );
    }

    /// Modified entity IDs in one arena of a diff.
    fn modified(result: &super::IrDiff, kind: &str) -> Vec<String> {
        result
            .per_arena
            .iter()
            .find(|arena| arena.kind == *kind)
            .expect("every model arena appears in every diff")
            .modified
            .iter()
            .map(|entity| entity.id.clone())
            .collect()
    }

    /// Index of a point whose `x` is at unit magnitude or above.
    fn scaled_point(ir: &crate::CadIr) -> usize {
        ir.model
            .points
            .iter()
            .position(|point| point.position().get().x.abs() >= 1.0)
            .expect("the cube fixture places points away from the origin")
    }

    /// A coordinate moved by one unit in the last place, which is what the same
    /// file decoded under two platforms' libm produces.
    #[test]
    fn a_last_place_coordinate_move_is_not_a_difference() {
        let left = unit_cube().expect("valid unit cube fixture");
        let mut right = left.clone();
        let index = scaled_point(&left);
        let before = right.model.points[index].position().get().x;
        let after = f64::from_bits(before.to_bits() + 1);
        assert_ne!(
            before.to_bits(),
            after.to_bits(),
            "the coordinate must move, or this test proves nothing"
        );
        let moved = right.model.points[index].position().get();
        right.model.points[index].set_position(
            crate::features::FinitePoint3::new(crate::math::Point3::new(after, moved.y, moved.z))
                .expect("a finite position is a point"),
        );

        assert_ne!(
            serde_json::to_value(&left.model.points).expect("test fixture invariant"),
            serde_json::to_value(&right.model.points).expect("test fixture invariant"),
            "the serialized documents must differ, or exact equality would pass too"
        );
        let result = diff(&left, &right);
        assert!(result.is_empty(), "{result:?}");
    }

    /// A tolerance declaration moved in the last place is the same declaration.
    #[test]
    fn a_last_place_tolerance_move_is_not_a_difference() {
        let left = unit_cube().expect("valid unit cube fixture");
        let mut right = left.clone();
        right.tolerances.linear = crate::scalar::PositiveLength::new(f64::from_bits(
            left.tolerances.linear.get().to_bits() + 1,
        ))
        .expect("positive finite tolerance");
        assert!(diff(&left, &right).is_empty());

        right.tolerances.linear =
            crate::scalar::PositiveLength::new(left.tolerances.linear.get() * 2.0)
                .expect("positive finite tolerance");
        assert!(diff(&left, &right).tolerance_change.is_some());
    }

    /// A change with physical meaning stays reported. A relative `1.0e-6` on a
    /// coordinate is six orders above the tolerance.
    #[test]
    fn a_genuine_coordinate_change_is_still_reported() {
        let left = unit_cube().expect("valid unit cube fixture");
        let mut right = left.clone();
        let index = scaled_point(&left);
        let point = right.model.points[index].position().get();
        right.model.points[index].set_position(
            crate::features::FinitePoint3::new(crate::math::Point3::new(
                point.x.mul_add(1.0e-6, point.x),
                point.y,
                point.z,
            ))
            .expect("a finite position is a point"),
        );

        let result = diff(&left, &right);
        assert!(!result.is_empty());
        assert_eq!(
            modified(&result, "points"),
            [left.model.points[index].id.as_str().to_owned()]
        );
    }

    /// An integer field is never tolerated, however large its magnitude and
    /// however small the change relative to it.
    #[test]
    fn an_integer_field_differing_by_one_is_always_reported() {
        use crate::geometry::{nurbs::NurbsCurve, Curve, CurveGeometry, SolvedCurveGeometry};
        use crate::ids::CurveId;
        use crate::math::Point3;

        let nurbs = |degree: u32| Curve {
            parameter_range: None,
            id: CurveId::mint("synthetic:tolerance:curve#nurbs").expect("valid identity"),
            geometry: CurveGeometry::Solved(SolvedCurveGeometry::Nurbs(
                NurbsCurve::from_lanes(
                    &cadmpeg_test_support::service_decode_context(),
                    degree,
                    if degree == 1 {
                        vec![0.0, 0.0, 0.5, 1.0, 1.0]
                    } else {
                        vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0]
                    },
                    vec![
                        Point3::new(0.0, 0.0, 0.0),
                        Point3::new(1.0, 0.0, 0.0),
                        Point3::new(2.0, 0.0, 0.0),
                    ],
                    None,
                    false,
                )
                .expect("fixture constructor admission")
                .expect("test fixture invariant"),
            )),
            source_object: None,
        };

        let mut left = unit_cube().expect("valid unit cube fixture");
        let mut right = left.clone();
        left.model.curves.push(nurbs(1));
        right.model.curves.push(nurbs(2));

        let result = diff(&left, &right);
        assert!(!result.is_empty());
        assert_eq!(
            modified(&result, "curves"),
            ["synthetic:tolerance:curve#nurbs"]
        );
    }

    /// `NaN` and infinity both serialize as `null`, so the JSON projection of
    /// these entities is identical although the entities differ.
    #[test]
    fn a_difference_json_cannot_state_is_reported_modified() {
        #[derive(PartialEq, serde::Serialize)]
        struct Entity {
            id: &'static str,
            value: f64,
        }

        let left = [Entity {
            id: "test:entity#0",
            value: f64::NAN,
        }];
        let right = [Entity {
            id: "test:entity#0",
            value: f64::INFINITY,
        }];
        let result = super::arena(
            super::ArenaKind::native("test", "entities"),
            &left,
            &right,
            |entity| entity.id,
        );
        assert_eq!(
            result
                .modified
                .iter()
                .map(|entity| entity.id.as_str())
                .collect::<Vec<_>>(),
            ["test:entity#0"]
        );
        assert_eq!(result.modified[0].fields, ["value"]);
    }

    /// A cube carrying source metadata with the given attributes.
    fn with_source(attributes: &[(&str, &str)]) -> crate::CadIr {
        let mut ir = unit_cube().expect("valid unit cube fixture");
        ir.source = Some(crate::document::SourceMeta::classified(
            cadmpeg_core::dialect::DialectLayers::of(
                cadmpeg_core::dialect::DialectMatch::admitted(cadmpeg_core::dialect_id!(
                    "rhino:archive-80"
                )),
            ),
            cadmpeg_core::text::named_entries(
                "the fixture document",
                attributes
                    .iter()
                    .map(|(key, value)| ((*key).to_owned(), (*value).to_owned())),
            )
            .expect("the fixture states named attributes"),
        ));
        ir
    }

    fn classify_source(ir: &mut crate::CadIr, dialect: cadmpeg_core::dialect::DialectMatch) {
        let source = ir
            .source
            .take()
            .expect("the test document has source metadata");
        ir.source = Some(crate::document::SourceMeta::classified(
            cadmpeg_core::dialect::DialectLayers::of(dialect),
            source.attributes,
        ));
    }

    #[test]
    fn a_source_attribute_difference_is_a_difference() {
        let left = with_source(&[("program_version", "1.0"), ("object_count", "3")]);
        let right = with_source(&[("program_version", "1.1"), ("object_count", "3")]);

        let result = diff(&left, &right);
        assert!(!result.is_empty());
        assert_eq!(
            result.source.attributes,
            [super::AttributeChange {
                key: cadmpeg_core::nonblank_literal!("program_version"),
                left: Some("1.0".to_owned()),
                right: Some("1.1".to_owned()),
            }]
        );
        assert!(result.source.local_digests.is_empty());
    }

    /// An attribute present on one side only is a difference in either direction.
    #[test]
    fn an_added_or_removed_source_attribute_is_a_difference() {
        let left = with_source(&[("object_count", "3")]);
        let right = with_source(&[]);

        let forward = diff(&left, &right);
        assert!(!forward.is_empty());
        assert_eq!(forward.source.attributes[0].left.as_deref(), Some("3"));
        assert_eq!(forward.source.attributes[0].right, None);

        let backward = diff(&right, &left);
        assert!(!backward.is_empty());
        assert_eq!(backward.source.attributes[0].left, None);
        assert_eq!(backward.source.attributes[0].right.as_deref(), Some("3"));
    }

    /// A machine-local digest is a bitwise fingerprint of tolerantly compared
    /// values, so two platforms' decodes of one file disagree on it while
    /// agreeing on the model. Such a difference is reported and does not make the
    /// documents different.
    #[test]
    fn a_machine_local_digest_difference_is_reported_but_is_not_a_difference() {
        let left = with_source(&[("document_local_sha256", &"0".repeat(64))]);
        let right = with_source(&[("document_local_sha256", &"1".repeat(64))]);

        let result = diff(&left, &right);
        assert_ne!(left.source, right.source);
        assert!(result.is_empty(), "{result:?}");
        assert!(result.source.attributes.is_empty());
        assert_eq!(
            result
                .source
                .local_digests
                .iter()
                .map(|change| change.key.as_str())
                .collect::<Vec<_>>(),
            ["document_local_sha256"]
        );
    }

    /// Carve-out keys by `_local_sha256` suffix, not a fixed key list.
    #[test]
    fn the_carve_out_follows_the_suffix_convention() {
        let key = format!("future_codec_thing{}", compare::LOCAL_DIGEST_SUFFIX);
        let left = with_source(&[(&key, "a"), ("footer_fingerprint", "f")]);
        let right = with_source(&[(&key, "b"), ("footer_fingerprint", "f")]);
        let result = diff(&left, &right);
        assert!(result.is_empty(), "{result:?}");
        assert_eq!(result.source.local_digests[0].key.as_str(), key);

        // Digests over retained source bytes have no suffix; a change stays a difference.
        let right = with_source(&[(&key, "b"), ("footer_fingerprint", "g")]);
        let result = diff(&left, &right);
        assert!(!result.is_empty());
        assert_eq!(result.source.attributes[0].key, "footer_fingerprint");
    }

    /// A document with no source metadata compares against one that has some
    /// without panicking in either order.
    #[test]
    fn absent_source_metadata_compares_without_panicking() {
        let mut bare = unit_cube().expect("valid unit cube fixture");
        bare.source = None;
        let populated = with_source(&[("object_count", "3")]);

        for (left, right) in [(&bare, &populated), (&populated, &bare)] {
            let result = diff(left, right);
            assert!(!result.is_empty());
            let change = result
                .source
                .format_change
                .as_ref()
                .expect("test fixture invariant");
            assert_ne!(change.before(), change.after());
            assert_eq!(result.source.attributes.len(), 1);
        }

        let rendered =
            serde_json::to_value(&diff(&bare, &populated).source).expect("test fixture invariant");
        assert_eq!(rendered["format_change"], serde_json::json!(["", "rhino"]));

        assert!(diff(&bare, &bare).is_empty());
    }

    #[test]
    fn identical_documents_have_empty_diff() {
        let ir = unit_cube().expect("valid unit cube fixture");
        assert!(diff(&ir, &ir).is_empty());
    }

    /// The dialect and its declared fields are compared, so a divergence there
    /// cannot pass as agreement.
    #[test]
    fn a_dialect_or_declared_divergence_is_a_difference() {
        let mut left = with_source(&[]);
        let mut right = left.clone();
        classify_source(
            &mut left,
            cadmpeg_core::dialect::DialectMatch::admitted(cadmpeg_core::dialect_id!(
                "rhino:archive-70"
            )),
        );
        classify_source(
            &mut right,
            cadmpeg_core::dialect::DialectMatch::admitted(cadmpeg_core::dialect_id!(
                "rhino:archive-80"
            )),
        );

        let result = diff(&left, &right);
        assert!(!result.is_empty());
        let change = result
            .source
            .dialects_change
            .as_ref()
            .expect("test fixture invariant");
        assert_eq!(
            change.before(),
            left.source
                .as_ref()
                .expect("test fixture invariant")
                .dialects()
        );
        assert_eq!(
            change.after(),
            right
                .source
                .as_ref()
                .expect("test fixture invariant")
                .dialects()
        );

        let mut declared_left = with_source(&[]);
        let mut declared_right = declared_left.clone();
        classify_source(
            &mut declared_left,
            cadmpeg_core::dialect::DialectMatch::admitted(cadmpeg_core::dialect_id!(
                "rhino:archive-70"
            ))
            .with_declared(BTreeMap::from([(
                cadmpeg_core::nonblank_literal!("archive_version"),
                "70".into(),
            )])),
        );
        classify_source(
            &mut declared_right,
            cadmpeg_core::dialect::DialectMatch::admitted(cadmpeg_core::dialect_id!(
                "rhino:archive-70"
            ))
            .with_declared(BTreeMap::from([(
                cadmpeg_core::nonblank_literal!("archive_version"),
                "80".into(),
            )])),
        );

        let declared = diff(&declared_left, &declared_right);
        assert!(!declared.is_empty());
        let declared_change = declared
            .source
            .dialects_change
            .as_ref()
            .expect("test fixture invariant");
        assert_eq!(
            declared_change.before(),
            declared_left
                .source
                .as_ref()
                .expect("test fixture invariant")
                .dialects()
        );
        assert_eq!(
            declared_change.after(),
            declared_right
                .source
                .as_ref()
                .expect("test fixture invariant")
                .dialects()
        );
        assert!(declared.source.attributes.is_empty());
    }

    #[test]
    fn admission_and_instance_divergence_are_differences() {
        use cadmpeg_core::dialect::{DialectLayers, DialectMatch};

        let mut left = with_source(&[]);
        let mut right = left.clone();
        classify_source(
            &mut left,
            DialectMatch::admitted(cadmpeg_core::dialect_id!("rhino:archive-80")),
        );
        classify_source(
            &mut right,
            DialectMatch::refused(cadmpeg_core::dialect_id!("rhino:archive-80")),
        );
        assert!(!diff(&left, &right).is_empty());

        classify_source(
            &mut right,
            DialectMatch::admitted(cadmpeg_core::dialect_id!("rhino:archive-80"))
                .with_instance("embedded/model.3dm"),
        );
        assert!(!diff(&left, &right).is_empty());

        let source = right.source.take().expect("test fixture invariant");
        right.source = Some(crate::document::SourceMeta::classified(
            DialectLayers::of(DialectMatch::admitted(cadmpeg_core::dialect_id!(
                "rhino:archive-80",
            )))
            .with(
                DialectMatch::residual(cadmpeg_core::dialect_id!("acis:text-acis"))
                    .with_instance("body.sat"),
            )
            .expect("the test dialect layers have distinct keys"),
            source.attributes,
        ));
        let result = diff(&left, &right);
        assert!(!result.is_empty());
        assert_eq!(
            result
                .source
                .dialects_change
                .as_ref()
                .expect("test fixture invariant")
                .after()
                .expect("test fixture invariant")
                .iter()
                .count(),
            2
        );
    }

    /// The staged fields add nothing to the serialized diff while they are
    /// empty, which is what keeps this output stable across the migration.
    #[test]
    fn an_unpopulated_dialect_adds_no_key_to_the_serialized_diff() {
        let ir = with_source(&[]);
        let rendered =
            serde_json::to_string(&diff(&ir, &ir).source).expect("test fixture invariant");

        assert!(!rendered.contains("dialects_change"), "{rendered}");
    }
}