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    None = 16,
39    Principal = 17,
40    Subaccount = 18,
41    Text = 19,
42    Timestamp = 20,
43    Uint = 21,
44    Uint128 = 22,
45    UintBig = 23,
46    Ulid = 24,
47    Unit = 25,
48    Unsupported = 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::None => ValueTag::None,
80        Value::Principal(_) => ValueTag::Principal,
81        Value::Subaccount(_) => ValueTag::Subaccount,
82        Value::Text(_) => ValueTag::Text,
83        Value::Timestamp(_) => ValueTag::Timestamp,
84        Value::Uint(_) => ValueTag::Uint,
85        Value::Uint128(_) => ValueTag::Uint128,
86        Value::UintBig(_) => ValueTag::UintBig,
87        Value::Ulid(_) => ValueTag::Ulid,
88        Value::Unit => ValueTag::Unit,
89        Value::Unsupported => ValueTag::Unsupported,
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)]
126pub(crate) fn with_test_hash_override<T>(hash: [u8; 16], f: impl FnOnce() -> T) -> T {
127    TEST_HASH_OVERRIDE.with(|cell| {
128        let previous = cell.replace(Some(hash));
129        let out = f();
130        cell.set(previous);
131        out
132    })
133}
134
135#[cfg(test)]
136#[allow(clippy::redundant_closure_for_method_calls)]
137fn test_hash_override() -> Option<[u8; 16]> {
138    TEST_HASH_OVERRIDE.with(|cell| cell.get())
139}
140
141#[allow(clippy::cast_possible_truncation)]
142#[allow(clippy::too_many_lines)]
143fn write_to_hasher(value: &Value, h: &mut Xxh3) -> Result<(), InternalError> {
144    feed_u8(h, value_tag(value));
145
146    match value {
147        Value::Account(a) => {
148            let bytes = a.to_bytes().map_err(|err| {
149                InternalError::new(
150                    ErrorClass::Unsupported,
151                    ErrorOrigin::Serialize,
152                    err.to_string(),
153                )
154            })?;
155            feed_bytes(h, &bytes);
156        }
157        Value::Blob(v) => {
158            feed_u8(h, 0x01);
159            feed_u32(h, v.len() as u32);
160            feed_bytes(h, v);
161        }
162        Value::Bool(b) => {
163            feed_u8(h, u8::from(*b));
164        }
165        Value::Date(d) => feed_i32(h, d.get()),
166        Value::Decimal(d) => {
167            // encode (sign, scale, mantissa) deterministically:
168            feed_u8(h, u8::from(d.is_sign_negative()));
169            feed_u32(h, d.scale());
170            feed_bytes(h, &d.mantissa().to_be_bytes());
171        }
172        Value::Duration(t) => {
173            feed_u64(h, t.get());
174        }
175        Value::Enum(v) => {
176            match &v.path {
177                Some(path) => {
178                    feed_u8(h, 0x01); // path present
179                    feed_u32(h, path.len() as u32);
180                    feed_bytes(h, path.as_bytes());
181                }
182                None => feed_u8(h, 0x00), // path absent -> loose match
183            }
184
185            feed_u32(h, v.variant.len() as u32);
186            feed_bytes(h, v.variant.as_bytes());
187
188            match &v.payload {
189                Some(payload) => {
190                    feed_u8(h, 0x01); // payload present
191                    write_to_hasher(payload, h)?; // include nested value
192                }
193                None => feed_u8(h, 0x00),
194            }
195        }
196        Value::E8s(v) => {
197            feed_u64(h, v.get());
198        }
199        Value::E18s(v) => {
200            feed_bytes(h, &v.to_be_bytes());
201        }
202        Value::Float32(v) => {
203            feed_bytes(h, &v.to_be_bytes());
204        }
205        Value::Float64(v) => {
206            feed_bytes(h, &v.to_be_bytes());
207        }
208        Value::Int(i) => {
209            feed_i64(h, *i);
210        }
211        Value::Int128(i) => {
212            feed_i128(h, i.get());
213        }
214        Value::IntBig(v) => {
215            let bytes = v.to_leb128();
216            feed_u32(h, bytes.len() as u32);
217            feed_bytes(h, &bytes);
218        }
219        Value::List(xs) => {
220            feed_u32(h, xs.len() as u32);
221            for x in xs {
222                feed_u8(h, 0xFF);
223                write_to_hasher(x, h)?; // recurse, no sub-hash
224            }
225        }
226        Value::Principal(p) => {
227            let raw = p.to_bytes().map_err(|err| {
228                InternalError::new(
229                    ErrorClass::Unsupported,
230                    ErrorOrigin::Serialize,
231                    err.to_string(),
232                )
233            })?;
234            feed_u32(h, raw.len() as u32);
235            feed_bytes(h, &raw);
236        }
237        Value::Subaccount(s) => {
238            feed_bytes(h, &s.to_bytes());
239        }
240        Value::Text(s) => {
241            // If you need case/Unicode insensitivity, normalize; else skip (much faster)
242            // let norm = normalize_nfkc_casefold(s);
243            // feed_u32( h, norm.len() as u32);
244            // feed_bytes( h, norm.as_bytes());
245            feed_u32(h, s.len() as u32);
246            feed_bytes(h, s.as_bytes());
247        }
248        Value::Timestamp(t) => {
249            feed_u64(h, t.get());
250        }
251        Value::Uint(u) => {
252            feed_u64(h, *u);
253        }
254        Value::Uint128(u) => {
255            feed_u128(h, u.get());
256        }
257        Value::UintBig(v) => {
258            let bytes = v.to_leb128();
259            feed_u32(h, bytes.len() as u32);
260            feed_bytes(h, &bytes);
261        }
262        Value::Ulid(u) => {
263            feed_bytes(h, &u.to_bytes());
264        }
265        Value::None | Value::Unit | Value::Unsupported => {}
266    }
267
268    Ok(())
269}
270
271/// Stable hash used for index/storage fingerprints.
272pub fn hash_value(value: &Value) -> Result<[u8; 16], InternalError> {
273    const VERSION: u8 = 1;
274
275    #[cfg(test)]
276    if let Some(override_hash) = test_hash_override() {
277        return Ok(override_hash);
278    }
279
280    let mut h = Xxh3::with_seed(0);
281    feed_u8(&mut h, VERSION); // version
282
283    write_to_hasher(value, &mut h)?;
284    Ok(h.digest128().to_be_bytes())
285}
286
287/// Index fingerprint semantics:
288///
289/// - Only indexable values produce fingerprints.
290/// - `Value::None` and `Value::Unsupported` do not produce fingerprints and
291///   therefore do not participate in indexing.
292/// - For unique indexes, uniqueness is enforced only over indexable values.
293///   Multiple rows with non-indexable values are permitted.
294///
295/// This behavior matches SQL-style UNIQUE constraints with NULL values.
296///
297/// Stable 128-bit hash used for index keys; returns `None` for non-indexable values.
298pub fn to_index_fingerprint(value: &Value) -> Result<Option<[u8; 16]>, InternalError> {
299    match value {
300        Value::None | Value::Unsupported => {
301            // Intentionally skipped: non-indexable values do not participate in indexes.
302            return Ok(None);
303        }
304        _ => {}
305    }
306
307    Ok(Some(hash_value(value)?))
308}
309
310///
311/// TESTS
312///
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317    use crate::{
318        types::{Float32 as F32, Float64 as F64},
319        value::{Value, ValueEnum},
320    };
321
322    fn v_f64(x: f64) -> Value {
323        Value::Float64(F64::try_new(x).expect("finite f64"))
324    }
325    fn v_f32(x: f32) -> Value {
326        Value::Float32(F32::try_new(x).expect("finite f32"))
327    }
328    fn v_i(x: i64) -> Value {
329        Value::Int(x)
330    }
331    fn v_txt(s: &str) -> Value {
332        Value::Text(s.to_string())
333    }
334
335    #[test]
336    fn hash_is_deterministic_for_int() {
337        let v = Value::Int(42);
338        let a = hash_value(&v).expect("hash value");
339        let b = hash_value(&v).expect("hash value");
340        assert_eq!(a, b, "hash should be deterministic for same value");
341    }
342
343    #[test]
344    fn different_variants_produce_different_hashes() {
345        let a = hash_value(&Value::Int(5)).expect("hash value");
346        let b = hash_value(&Value::Uint(5)).expect("hash value");
347        assert_ne!(
348            a, b,
349            "Int(5) and Uint(5) must hash differently (different tag)"
350        );
351    }
352
353    #[test]
354    fn enum_hash_tracks_path_presence() {
355        let strict = Value::Enum(ValueEnum::new("A", Some("MyEnum")));
356        let loose = Value::Enum(ValueEnum::new("A", None));
357        assert_ne!(
358            hash_value(&strict).expect("hash value"),
359            hash_value(&loose).expect("hash value"),
360            "Enum hashes must differ when path is present vs absent"
361        );
362    }
363
364    #[test]
365    fn enum_hash_includes_payload() {
366        let base = ValueEnum::new("A", Some("MyEnum"));
367        let with_one = Value::Enum(base.clone().with_payload(Value::Uint(1)));
368        let with_two = Value::Enum(base.with_payload(Value::Uint(2)));
369
370        assert_ne!(
371            hash_value(&with_one).expect("hash value"),
372            hash_value(&with_two).expect("hash value"),
373            "Enum payload must influence hash/fingerprint"
374        );
375    }
376
377    #[test]
378    fn float32_and_float64_hash_differ() {
379        let a = hash_value(&v_f32(1.0)).expect("hash value");
380        let b = hash_value(&v_f64(1.0)).expect("hash value");
381        assert_ne!(
382            a, b,
383            "Float32 and Float64 must hash differently (different tag)"
384        );
385    }
386
387    #[test]
388    fn text_is_length_and_content_sensitive() {
389        let a = hash_value(&v_txt("foo")).expect("hash value");
390        let b = hash_value(&v_txt("bar")).expect("hash value");
391        assert_ne!(a, b, "different strings should hash differently");
392
393        let c = hash_value(&v_txt("foo")).expect("hash value");
394        assert_eq!(a, c, "same string should hash the same");
395    }
396
397    #[test]
398    fn list_hash_is_order_sensitive() {
399        let l1 = Value::from_list(&[v_i(1), v_i(2)]);
400        let l2 = Value::from_list(&[v_i(2), v_i(1)]);
401        assert_ne!(
402            hash_value(&l1).expect("hash value"),
403            hash_value(&l2).expect("hash value"),
404            "list order should affect hash"
405        );
406    }
407
408    #[test]
409    fn list_hash_is_length_sensitive() {
410        let l1 = Value::from_list(&[v_i(1)]);
411        let l2 = Value::from_list(&[v_i(1), v_i(1)]);
412        assert_ne!(
413            hash_value(&l1).expect("hash value"),
414            hash_value(&l2).expect("hash value"),
415            "list length should affect hash"
416        );
417    }
418
419    #[test]
420    fn list_blob_boundaries_are_length_framed() {
421        let left = Value::List(vec![
422            Value::Blob(vec![0x10, 0xFF, 0x02, 0x11]),
423            Value::Blob(vec![0x12]),
424        ]);
425        let right = Value::List(vec![
426            Value::Blob(vec![0x10]),
427            Value::Blob(vec![0x11, 0xFF, 0x02, 0x12]),
428        ]);
429
430        assert_ne!(
431            hash_value(&left).expect("hash value"),
432            hash_value(&right).expect("hash value"),
433            "blob boundaries must be length-framed to avoid collisions"
434        );
435    }
436}