ifc_lite_diff/
fingerprint.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Canonical, order-independent data fingerprinting for model diffing.
6//!
7//! A byte-exact port of `packages/diff/src/fingerprint.ts`. Callers extract a
8//! plain [`DataFingerprintInput`] from whatever store they have and hash it
9//! here, so base and head adapters produce identical fingerprints for an
10//! unchanged entity — across adapters, machines and now languages.
11//!
12//! The rules that are load-bearing rather than incidental, each of which the
13//! TypeScript module argues for at length:
14//!
15//! - **An assigned type is identified by name and IFC class, never by
16//!   `GlobalId`.** `IfcTypeObject` is an `IfcRoot`, so a from-scratch
17//!   re-export regenerates its id; hashing it moved the fingerprint of every
18//!   *typed* element on exactly the re-export where nothing substantive
19//!   changed, defeating the content-matching pass that exists for that case.
20//! - **`Tag` participates for type objects only.** For a type object it is
21//!   design content and often the only discriminator between same-named
22//!   types. For an occurrence it is the authoring tool's own element id, so
23//!   two tools exporting one design disagree on it for every element.
24//! - **Absent and empty hash alike** for materials and classifications: the
25//!   key is omitted entirely when the projection is empty, so shipping those
26//!   fields did not move the fingerprint of every material-less entity.
27//! - **[`core_attributes`] is one function, not two literals.** The
28//!   `attr:core` sub-hash is a collision *guard* on the whole-blob hash, and
29//!   that only holds while the two project identically.
30
31use crate::JsString;
32use crate::sparse_collection::SparseCollection;
33
34use crate::input::{DataFingerprintInput, PropertyEntryInput, PropertyValue, TypeAssignmentInput};
35use crate::js_json::{cmp_sorted, non_finite_token, JsonValue};
36
37#[path = "fingerprint_checked.rs"]
38mod checked;
39pub use checked::{
40    build_component_fingerprint_entries, build_component_fingerprint_entries_checked,
41    build_component_fingerprints, build_data_fingerprint, build_data_fingerprint_checked,
42    check_property_sets, check_quantity_sets, check_type_assignments,
43};
44
45#[path = "fingerprint_pair.rs"]
46mod pair;
47pub use pair::build_fingerprint_pair_checked;
48
49/// A normalized scalar: what a property value collapses to before hashing.
50#[derive(Debug, Clone, PartialEq)]
51enum NormalizedValue {
52    Null,
53    Bool(bool),
54    /// Always finite — a non-finite input becomes [`NormalizedValue::String`].
55    Number(f64),
56    String(JsString),
57}
58
59impl NormalizedValue {
60    fn to_json(&self) -> JsonValue {
61        match self {
62            NormalizedValue::Null => JsonValue::Null,
63            NormalizedValue::Bool(value) => JsonValue::Bool(*value),
64            NormalizedValue::Number(value) => JsonValue::Number(*value),
65            NormalizedValue::String(value) => JsonValue::String(value.clone()),
66        }
67    }
68}
69
70/// Collapse a property value to a stable scalar.
71///
72/// Non-finite numbers become their `String(n)` token rather than reaching the
73/// serializer, because `JSON.stringify` maps `NaN`/`Infinity`/`-Infinity` to
74/// `null` — the same token an absent property produces. An `Infinity` value
75/// (reachable from a STEP `IfcReal` with an extreme exponent) would otherwise
76/// hash identically to the property being absent, and the content pass treats
77/// an equal hash as identity, so that collision could retire a genuine
78/// added/deleted pair as unchanged.
79///
80/// Composite values are serialized with **sorted** keys, so two structurally
81/// equal values hash alike regardless of key insertion order.
82fn normalize_value(value: &PropertyValue) -> NormalizedValue {
83    match value {
84        PropertyValue::Null => NormalizedValue::Null,
85        PropertyValue::Bool(flag) => NormalizedValue::Bool(*flag),
86        PropertyValue::Number(number) if number.is_finite() => NormalizedValue::Number(*number),
87        _ => NormalizedValue::String(canonical_value_string(value).expect("text-normalized value")),
88    }
89}
90
91/// The text produced when fingerprint normalization collapses a value to a string.
92///
93/// Strings are kept verbatim, non-finite scalars become their ECMAScript token,
94/// and composites use the diff engine's sorted-key JSON serializer. Null,
95/// booleans and finite numbers retain their scalar type and return `None`.
96/// Other adapters should use this function rather than choose another JSON form.
97pub fn canonical_value_string(value: &PropertyValue) -> Option<JsString> {
98    match value {
99        PropertyValue::String(text) => Some(text.clone()),
100        PropertyValue::Number(number) if !number.is_finite() => Some(non_finite_token(*number).into()),
101        PropertyValue::Array(_) | PropertyValue::Object(_) => Some(crate::property_json::stringify_property_sorted(value).into()),
102        _ => None,
103    }
104}
105
106/// A normalized, named record: the unit both sorted collections hold.
107struct NamedEntry {
108    name: JsString,
109    value: NormalizedValue,
110}
111
112impl NamedEntry {
113    fn to_json(&self) -> JsonValue {
114        // Fixed member field names account for two allocations per property.
115        // The shared code units are immutable and keep the same JSON order.
116        static KEYS: std::sync::OnceLock<[JsString; 2]> = std::sync::OnceLock::new();
117        let [name, value] = KEYS.get_or_init(|| ["name".into(), "value".into()]);
118        JsonValue::Object(vec![
119            (name.clone(), JsonValue::String(self.name.clone())),
120            (value.clone(), self.value.to_json()),
121        ])
122    }
123}
124
125/// Total order over named records: name first, then serialized content.
126///
127/// The name alone is **not** a total order, and the sorted result is hashed,
128/// so ties would make the fingerprint depend on the order the adapter walked
129/// its relationships in — same content, two orders, two hashes. Same-named
130/// property sets are not hypothetical: a type pset and an occurrence pset of
131/// one name is a normal IFC arrangement. Tiebreaking on serialized content
132/// makes the order total and content-derived.
133fn cmp_name_then_content(a: (&JsString, &JsonValue), b: (&JsString, &JsonValue)) -> std::cmp::Ordering {
134    // Code-unit order of the two stableSerialize texts, hole runs compared
135    // without materializing them (#8114).
136    a.0.cmp(b.0).then_with(|| cmp_sorted(a.1, b.1))
137}
138
139fn sorted_entries(entries: &SparseCollection<PropertyEntryInput>) -> Vec<JsonValue> {
140    let mut normalized: Vec<NamedEntry> = entries
141        .present()
142        .map(|entry| NamedEntry {
143            name: entry.name.clone(),
144            value: normalize_value(&entry.value),
145        })
146        .collect();
147    normalized.sort_by(|a, b| {
148        // #8042: most names differ; do not allocate JSON for an unused tiebreak.
149        a.name.cmp(&b.name).then_with(|| cmp_sorted(&a.to_json(), &b.to_json()))
150    });
151    with_holes(normalized.into_iter().map(|entry| entry.to_json()).collect(), entries.holes())
152}
153
154/// The direct-attribute slice, in one place because two functions hash it and
155/// they are required to hash the same thing.
156fn core_attributes(input: &DataFingerprintInput) -> Vec<(JsString, JsonValue)> {
157    let text = |value: &Option<JsString>| JsonValue::String(value.clone().unwrap_or_default());
158    vec![
159        ("Type".into(), JsonValue::String(input.ifc_type.clone())),
160        ("Name".into(), text(&input.name)),
161        ("Description".into(), text(&input.description)),
162        ("ObjectType".into(), text(&input.object_type)),
163        ("PredefinedType".into(), text(&input.predefined_type)),
164        ("Tag".into(), text(&input.tag)),
165    ]
166}
167
168/// A set's canonical JSON form: `{ name, <members-key>: [...] }`, in that
169/// order, because the key order is part of the hashed format.
170fn set_to_json(name: &JsString, members_key: &str, members: &[JsonValue]) -> JsonValue {
171    JsonValue::Object(vec![
172        ("name".into(), JsonValue::String(name.clone())),
173        (
174            members_key.into(),
175            JsonValue::Array(members.to_vec()),
176        ),
177    ])
178}
179
180fn sorted_property_sets(input: &DataFingerprintInput) -> Vec<(JsString, JsonValue)> {
181    let mut sets: Vec<(JsString, JsonValue)> = input
182        .property_sets
183        .present()
184        .map(|set| {
185            let members = sorted_entries(&set.properties);
186            (set.name.clone(), set_to_json(&set.name, "properties", &members))
187        })
188        .collect();
189    sets.sort_by(|a, b| cmp_name_then_content((&a.0, &a.1), (&b.0, &b.1)));
190    sets
191}
192
193fn sorted_quantity_sets(input: &DataFingerprintInput) -> Vec<(JsString, JsonValue)> {
194    let mut sets: Vec<(JsString, JsonValue)> = input
195        .quantity_sets
196        .present()
197        .map(|set| {
198            let members = sorted_entries(&set.quantities);
199            (set.name.clone(), set_to_json(&set.name, "quantities", &members))
200        })
201        .collect();
202    sets.sort_by(|a, b| cmp_name_then_content((&a.0, &a.1), (&b.0, &b.1)));
203    sets
204}
205
206/// Canonical projection of the assigned types: semantic identity only.
207///
208/// Sorted by (class, name). Those two fields are the whole projected record,
209/// so two assignments tying on both are identical and their relative order
210/// cannot affect the serialization — the sort is total on the output even
211/// though it is not total on the input.
212///
213/// Duplicates are kept rather than collapsed: cardinality is content, and IFC
214/// allows an occurrence at most one `IfcRelDefinesByType`, so two assignments
215/// are an anomaly a diff should surface rather than normalize away.
216fn sorted_type_assignments(types: &SparseCollection<TypeAssignmentInput>) -> Vec<JsonValue> {
217    let mut projected: Vec<(JsString, JsString)> = types
218        .present()
219        .map(|assignment| {
220            (
221                assignment.name.clone().unwrap_or_default(),
222                assignment.type_name.clone().unwrap_or_default(),
223            )
224        })
225        .collect();
226    projected.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
227    let values = projected
228        .into_iter()
229        .map(|(name, type_name)| {
230            JsonValue::Object(vec![
231                ("name".into(), JsonValue::String(name)),
232                ("type".into(), JsonValue::String(type_name)),
233            ])
234        })
235        .collect();
236    with_holes(values, types.holes())
237}
238
239/// Sorting moves holes after the records; keep them as ONE trailing run.
240fn with_holes(mut values: Vec<JsonValue>, holes: usize) -> Vec<JsonValue> {
241    if holes > 0 { values.push(JsonValue::Holes(holes)); }
242    values
243}
244
245fn string_array(values: &[JsString]) -> JsonValue {
246    JsonValue::Array(values.iter().cloned().map(JsonValue::String).collect())
247}
248
249#[cfg(test)]
250#[path = "fingerprint_sparse_tests.rs"]
251mod sparse_tests;
252
253#[cfg(test)]
254#[path = "fingerprint_counted_tests.rs"]
255mod counted_tests;
256
257#[cfg(test)]
258#[path = "fingerprint_set_ordinal_tests.rs"]
259mod set_ordinal_tests;