Skip to main content

icydb_core/db/index/
fingerprint.rs

1use crate::{
2    error::{ErrorClass, ErrorOrigin, InternalError},
3    value::Value,
4};
5use canic_utils::hash::Xxh3;
6
7///
8/// ValueTag
9///
10/// Can we remove ValueTag?
11/// Yes, technically.
12///
13/// Should we?
14/// Almost certainly no, unless you control all serialization + don't need hashing + don't care about stability.
15///
16/// Why keep it?
17/// Binary stability, hashing, sorting, versioning, IC-safe ABI, robustness.
18///
19
20#[repr(u8)]
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum ValueTag {
23    Account = 1,
24    Blob = 2,
25    Bool = 3,
26    Date = 4,
27    Decimal = 5,
28    Duration = 6,
29    Enum = 7,
30    E8s = 8,
31    E18s = 9,
32    Float32 = 10,
33    Float64 = 11,
34    Int = 12,
35    Int128 = 13,
36    IntBig = 14,
37    List = 15,
38    Map = 16,
39    Null = 17,
40    Principal = 18,
41    Subaccount = 19,
42    Text = 20,
43    Timestamp = 21,
44    Uint = 22,
45    Uint128 = 23,
46    UintBig = 24,
47    Ulid = 25,
48    Unit = 26,
49}
50
51impl ValueTag {
52    #[must_use]
53    pub const fn to_u8(self) -> u8 {
54        self as u8
55    }
56}
57
58///
59/// Canonical Byte Representation
60///
61
62const fn value_tag(value: &Value) -> u8 {
63    match value {
64        Value::Account(_) => ValueTag::Account,
65        Value::Blob(_) => ValueTag::Blob,
66        Value::Bool(_) => ValueTag::Bool,
67        Value::Date(_) => ValueTag::Date,
68        Value::Decimal(_) => ValueTag::Decimal,
69        Value::Duration(_) => ValueTag::Duration,
70        Value::Enum(_) => ValueTag::Enum,
71        Value::E8s(_) => ValueTag::E8s,
72        Value::E18s(_) => ValueTag::E18s,
73        Value::Float32(_) => ValueTag::Float32,
74        Value::Float64(_) => ValueTag::Float64,
75        Value::Int(_) => ValueTag::Int,
76        Value::Int128(_) => ValueTag::Int128,
77        Value::IntBig(_) => ValueTag::IntBig,
78        Value::List(_) => ValueTag::List,
79        Value::Map(_) => ValueTag::Map,
80        Value::Null => ValueTag::Null,
81        Value::Principal(_) => ValueTag::Principal,
82        Value::Subaccount(_) => ValueTag::Subaccount,
83        Value::Text(_) => ValueTag::Text,
84        Value::Timestamp(_) => ValueTag::Timestamp,
85        Value::Uint(_) => ValueTag::Uint,
86        Value::Uint128(_) => ValueTag::Uint128,
87        Value::UintBig(_) => ValueTag::UintBig,
88        Value::Ulid(_) => ValueTag::Ulid,
89        Value::Unit => ValueTag::Unit,
90    }
91    .to_u8()
92}
93
94fn feed_i32(h: &mut Xxh3, x: i32) {
95    h.update(&x.to_be_bytes());
96}
97fn feed_i64(h: &mut Xxh3, x: i64) {
98    h.update(&x.to_be_bytes());
99}
100fn feed_i128(h: &mut Xxh3, x: i128) {
101    h.update(&x.to_be_bytes());
102}
103fn feed_u8(h: &mut Xxh3, x: u8) {
104    h.update(&[x]);
105}
106fn feed_u32(h: &mut Xxh3, x: u32) {
107    h.update(&x.to_be_bytes());
108}
109fn feed_u64(h: &mut Xxh3, x: u64) {
110    h.update(&x.to_be_bytes());
111}
112fn feed_u128(h: &mut Xxh3, x: u128) {
113    h.update(&x.to_be_bytes());
114}
115fn feed_bytes(h: &mut Xxh3, b: &[u8]) {
116    h.update(b);
117}
118
119#[cfg(test)]
120thread_local! {
121    static TEST_HASH_OVERRIDE: std::cell::Cell<Option<[u8; 16]>> =
122        const { std::cell::Cell::new(None) };
123}
124
125#[cfg(test)]
126#[allow(clippy::redundant_closure_for_method_calls)]
127fn test_hash_override() -> Option<[u8; 16]> {
128    TEST_HASH_OVERRIDE.with(|cell| cell.get())
129}
130
131#[allow(clippy::cast_possible_truncation)]
132#[allow(clippy::too_many_lines)]
133fn write_to_hasher(value: &Value, h: &mut Xxh3) -> Result<(), InternalError> {
134    feed_u8(h, value_tag(value));
135
136    match value {
137        Value::Account(a) => {
138            let bytes = a.to_bytes().map_err(|err| {
139                InternalError::new(
140                    ErrorClass::Unsupported,
141                    ErrorOrigin::Serialize,
142                    err.to_string(),
143                )
144            })?;
145            feed_bytes(h, &bytes);
146        }
147        Value::Blob(v) => {
148            feed_u8(h, 0x01);
149            feed_u32(h, v.len() as u32);
150            feed_bytes(h, v);
151        }
152        Value::Bool(b) => {
153            feed_u8(h, u8::from(*b));
154        }
155        Value::Date(d) => feed_i32(h, d.get()),
156        Value::Decimal(d) => {
157            // encode (sign, scale, mantissa) deterministically:
158            feed_u8(h, u8::from(d.is_sign_negative()));
159            feed_u32(h, d.scale());
160            feed_bytes(h, &d.mantissa().to_be_bytes());
161        }
162        Value::Duration(t) => {
163            feed_u64(h, t.get());
164        }
165        Value::Enum(v) => {
166            match &v.path {
167                Some(path) => {
168                    feed_u8(h, 0x01); // path present
169                    feed_u32(h, path.len() as u32);
170                    feed_bytes(h, path.as_bytes());
171                }
172                None => feed_u8(h, 0x00), // path absent -> loose match
173            }
174
175            feed_u32(h, v.variant.len() as u32);
176            feed_bytes(h, v.variant.as_bytes());
177
178            match &v.payload {
179                Some(payload) => {
180                    feed_u8(h, 0x01); // payload present
181                    write_to_hasher(payload, h)?; // include nested value
182                }
183                None => feed_u8(h, 0x00),
184            }
185        }
186        Value::E8s(v) => {
187            feed_u64(h, v.get());
188        }
189        Value::E18s(v) => {
190            feed_bytes(h, &v.to_be_bytes());
191        }
192        Value::Float32(v) => {
193            feed_bytes(h, &v.to_be_bytes());
194        }
195        Value::Float64(v) => {
196            feed_bytes(h, &v.to_be_bytes());
197        }
198        Value::Int(i) => {
199            feed_i64(h, *i);
200        }
201        Value::Int128(i) => {
202            feed_i128(h, i.get());
203        }
204        Value::IntBig(v) => {
205            let bytes = v.to_leb128();
206            feed_u32(h, bytes.len() as u32);
207            feed_bytes(h, &bytes);
208        }
209        Value::List(xs) => {
210            feed_u32(h, xs.len() as u32);
211            for x in xs {
212                feed_u8(h, 0xFF);
213                write_to_hasher(x, h)?; // recurse, no sub-hash
214            }
215        }
216        Value::Map(entries) => {
217            feed_u32(h, entries.len() as u32);
218            for (key, value) in entries {
219                feed_u8(h, 0xFD);
220                write_to_hasher(key, h)?;
221                feed_u8(h, 0xFE);
222                write_to_hasher(value, h)?;
223            }
224        }
225        Value::Principal(p) => {
226            let raw = p.to_bytes().map_err(|err| {
227                InternalError::new(
228                    ErrorClass::Unsupported,
229                    ErrorOrigin::Serialize,
230                    err.to_string(),
231                )
232            })?;
233            feed_u32(h, raw.len() as u32);
234            feed_bytes(h, &raw);
235        }
236        Value::Subaccount(s) => {
237            feed_bytes(h, &s.to_bytes());
238        }
239        Value::Text(s) => {
240            // If you need case/Unicode insensitivity, normalize; else skip (much faster)
241            // let norm = normalize_nfkc_casefold(s);
242            // feed_u32( h, norm.len() as u32);
243            // feed_bytes( h, norm.as_bytes());
244            feed_u32(h, s.len() as u32);
245            feed_bytes(h, s.as_bytes());
246        }
247        Value::Timestamp(t) => {
248            feed_u64(h, t.get());
249        }
250        Value::Uint(u) => {
251            feed_u64(h, *u);
252        }
253        Value::Uint128(u) => {
254            feed_u128(h, u.get());
255        }
256        Value::UintBig(v) => {
257            let bytes = v.to_leb128();
258            feed_u32(h, bytes.len() as u32);
259            feed_bytes(h, &bytes);
260        }
261        Value::Ulid(u) => {
262            feed_bytes(h, &u.to_bytes());
263        }
264        Value::Null | Value::Unit => {
265            // NOTE: Non-indexable values intentionally contribute no hash input.
266        }
267    }
268
269    Ok(())
270}
271
272/// Stable hash used for index/storage fingerprints.
273pub fn hash_value(value: &Value) -> Result<[u8; 16], InternalError> {
274    const VERSION: u8 = 1;
275
276    #[cfg(test)]
277    if let Some(override_hash) = test_hash_override() {
278        return Ok(override_hash);
279    }
280
281    let mut h = Xxh3::with_seed(0);
282    feed_u8(&mut h, VERSION); // version
283
284    write_to_hasher(value, &mut h)?;
285    Ok(h.digest128().to_be_bytes())
286}
287
288/// Index fingerprint semantics:
289///
290/// - Only indexable values produce fingerprints.
291/// - `Value::Null` does not produce fingerprints and
292///   therefore do not participate in indexing.
293/// - For unique indexes, uniqueness is enforced only over indexable values.
294///   Multiple rows with non-indexable values are permitted.
295///
296/// This behavior matches SQL-style UNIQUE constraints with NULL values.
297///
298/// Stable 128-bit hash used for index keys; returns `None` for non-indexable values.
299pub fn to_index_fingerprint(value: &Value) -> Result<Option<[u8; 16]>, InternalError> {
300    if matches!(value, Value::Null) {
301        // Intentionally skipped: non-indexable values do not participate in indexes.
302        return Ok(None);
303    }
304
305    Ok(Some(hash_value(value)?))
306}
307
308///
309/// TESTS
310///
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use crate::{
316        types::{Float32 as F32, Float64 as F64},
317        value::{Value, ValueEnum},
318    };
319
320    fn v_f64(x: f64) -> Value {
321        Value::Float64(F64::try_new(x).expect("finite f64"))
322    }
323    fn v_f32(x: f32) -> Value {
324        Value::Float32(F32::try_new(x).expect("finite f32"))
325    }
326    fn v_i(x: i64) -> Value {
327        Value::Int(x)
328    }
329    fn v_txt(s: &str) -> Value {
330        Value::Text(s.to_string())
331    }
332
333    #[test]
334    fn hash_is_deterministic_for_int() {
335        let v = Value::Int(42);
336        let a = hash_value(&v).expect("hash value");
337        let b = hash_value(&v).expect("hash value");
338        assert_eq!(a, b, "hash should be deterministic for same value");
339    }
340
341    #[test]
342    fn different_variants_produce_different_hashes() {
343        let a = hash_value(&Value::Int(5)).expect("hash value");
344        let b = hash_value(&Value::Uint(5)).expect("hash value");
345        assert_ne!(
346            a, b,
347            "Int(5) and Uint(5) must hash differently (different tag)"
348        );
349    }
350
351    #[test]
352    fn enum_hash_tracks_path_presence() {
353        let strict = Value::Enum(ValueEnum::new("A", Some("MyEnum")));
354        let loose = Value::Enum(ValueEnum::new("A", None));
355        assert_ne!(
356            hash_value(&strict).expect("hash value"),
357            hash_value(&loose).expect("hash value"),
358            "Enum hashes must differ when path is present vs absent"
359        );
360    }
361
362    #[test]
363    fn enum_hash_includes_payload() {
364        let base = ValueEnum::new("A", Some("MyEnum"));
365        let with_one = Value::Enum(base.clone().with_payload(Value::Uint(1)));
366        let with_two = Value::Enum(base.with_payload(Value::Uint(2)));
367
368        assert_ne!(
369            hash_value(&with_one).expect("hash value"),
370            hash_value(&with_two).expect("hash value"),
371            "Enum payload must influence hash/fingerprint"
372        );
373    }
374
375    #[test]
376    fn float32_and_float64_hash_differ() {
377        let a = hash_value(&v_f32(1.0)).expect("hash value");
378        let b = hash_value(&v_f64(1.0)).expect("hash value");
379        assert_ne!(
380            a, b,
381            "Float32 and Float64 must hash differently (different tag)"
382        );
383    }
384
385    #[test]
386    fn text_is_length_and_content_sensitive() {
387        let a = hash_value(&v_txt("foo")).expect("hash value");
388        let b = hash_value(&v_txt("bar")).expect("hash value");
389        assert_ne!(a, b, "different strings should hash differently");
390
391        let c = hash_value(&v_txt("foo")).expect("hash value");
392        assert_eq!(a, c, "same string should hash the same");
393    }
394
395    #[test]
396    fn list_hash_is_order_sensitive() {
397        let l1 = Value::from_slice(&[v_i(1), v_i(2)]);
398        let l2 = Value::from_slice(&[v_i(2), v_i(1)]);
399        assert_ne!(
400            hash_value(&l1).expect("hash value"),
401            hash_value(&l2).expect("hash value"),
402            "list order should affect hash"
403        );
404    }
405
406    #[test]
407    fn list_hash_is_length_sensitive() {
408        let l1 = Value::from_slice(&[v_i(1)]);
409        let l2 = Value::from_slice(&[v_i(1), v_i(1)]);
410        assert_ne!(
411            hash_value(&l1).expect("hash value"),
412            hash_value(&l2).expect("hash value"),
413            "list length should affect hash"
414        );
415    }
416
417    #[test]
418    fn list_blob_boundaries_are_length_framed() {
419        let left = Value::List(vec![
420            Value::Blob(vec![0x10, 0xFF, 0x02, 0x11]),
421            Value::Blob(vec![0x12]),
422        ]);
423        let right = Value::List(vec![
424            Value::Blob(vec![0x10]),
425            Value::Blob(vec![0x11, 0xFF, 0x02, 0x12]),
426        ]);
427
428        assert_ne!(
429            hash_value(&left).expect("hash value"),
430            hash_value(&right).expect("hash value"),
431            "blob boundaries must be length-framed to avoid collisions"
432        );
433    }
434}