diskann-label-filter 0.50.1

DiskANN is a fast approximate nearest neighbor search library for high dimensional data
Documentation
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
/*
 * Copyright (c) Microsoft Corporation.
 * Licensed under the MIT license.
 */

use crate::attribute::AttributeValue;

/// A trait for encoding and decoding field-value pairs into keys.
///
/// This trait defines how to convert field-value pairs into byte keys suitable
/// for storage in key-value stores. The encoding should preserve ordering for
/// numeric types to enable efficient range queries.
pub trait KeyCodec: Send + Sync + 'static {
    /// Encodes a field-value pair into a byte key.
    ///
    /// The encoding should be deterministic and preserve ordering for numeric types.
    ///
    /// # Arguments
    ///
    /// * `field` - The field name.
    /// * `value` - The value to encode.
    ///
    /// # Returns
    ///
    /// A byte vector representing the encoded key.
    fn encode_field_value_key(&self, field: &str, value: &AttributeValue) -> Vec<u8>;

    /// Decodes a byte key back into a field-value pair.
    ///
    /// This is an optional debuging method with a default implementation that returns `None`.
    ///
    /// # Arguments
    ///
    /// * `key` - The encoded key bytes.
    ///
    /// # Returns
    ///
    /// `Some((field, value))` if decoding succeeds, or `None` if not implemented or fails.
    fn decode_field_value_key(&self, key: &[u8]) -> Option<(String, AttributeValue)>;
}

/// Type prefix constants for key encoding.
pub const TYPE_PREFIX_INTEGER: &str = "I";
pub const TYPE_PREFIX_FLOAT: &str = "F";
pub const TYPE_PREFIX_STRING: &str = "S";
pub const TYPE_PREFIX_BOOL: &str = "B";

/// Field separator in encoded keys.
pub const FIELD_SEPARATOR: &str = "\0";

/// The default key codec implementation.
///
/// This codec encodes field-value pairs using a format that preserves ordering
/// for numeric types. It uses special type prefixes (I for integers, F for floats,
/// S for strings, B for booleans) and encodes numbers in a way that maintains
/// lexicographic ordering of the byte representation.
#[derive(Debug, Clone)]
pub struct DefaultKeyCodec {}

impl DefaultKeyCodec {
    /// Creates a new `DefaultKeyCodec` instance.
    pub fn new() -> Self {
        Self {}
    }

    /// Encodes a signed 64-bit integer to preserve ordering.
    ///
    /// XORs with the sign bit to ensure negative numbers sort before positive ones.
    #[inline]
    fn encode_i64(n: i64) -> u64 {
        (n as u64) ^ 0x8000000000000000 // XOR with sign bit
    }

    /// Encodes a 64-bit float to preserve ordering.
    ///
    /// Handles IEEE 754 floating-point encoding to ensure proper sorting.
    #[inline]
    fn encode_f64(f: f64) -> u64 {
        let bits = f.to_bits();
        if (bits >> 63) == 0 {
            bits ^ 0x8000000000000000
        } else {
            !bits
        }
    }

    /// Formats an integer value with field name and type prefix.
    ///
    /// Takes a raw i64 value and encodes it internally to preserve ordering.
    fn format_integer_value(field: &str, value: i64) -> Vec<u8> {
        let encoded = Self::encode_i64(value);
        format!(
            "{}{}{}{:016x}",
            field, FIELD_SEPARATOR, TYPE_PREFIX_INTEGER, encoded
        )
        .into_bytes()
    }

    /// Formats a float value with field name and type prefix.
    ///
    /// Takes a raw f64 value and encodes it internally to preserve ordering.
    fn format_float_value(field: &str, value: f64) -> Vec<u8> {
        let encoded = Self::encode_f64(value);
        format!(
            "{}{}{}{:016x}",
            field, FIELD_SEPARATOR, TYPE_PREFIX_FLOAT, encoded
        )
        .into_bytes()
    }

    /// Formats a string value with field name and type prefix.
    fn format_string_value(field: &str, value: &str) -> Vec<u8> {
        format!(
            "{}{}{}{}",
            field, FIELD_SEPARATOR, TYPE_PREFIX_STRING, value
        )
        .into_bytes()
    }

    /// Formats a boolean key with field name and type prefix.
    fn format_bool_value(field: &str, value: bool) -> Vec<u8> {
        format!(
            "{}{}{}{}",
            field,
            FIELD_SEPARATOR,
            TYPE_PREFIX_BOOL,
            if value { "1" } else { "0" }
        )
        .into_bytes()
    }
}

impl Default for DefaultKeyCodec {
    fn default() -> Self {
        Self::new()
    }
}

impl KeyCodec for DefaultKeyCodec {
    fn encode_field_value_key(&self, field: &str, value: &AttributeValue) -> Vec<u8> {
        match value {
            AttributeValue::Integer(i) => Self::format_integer_value(field, *i),
            AttributeValue::Real(f) => Self::format_float_value(field, *f),
            AttributeValue::String(s) => Self::format_string_value(field, s),
            AttributeValue::Bool(b) => Self::format_bool_value(field, *b),
            AttributeValue::Empty => {
                // Handle empty values - maybe as a special case or skip
                Self::format_string_value(field, "")
            }
        }
    }

    fn decode_field_value_key(&self, _key: &[u8]) -> Option<(String, AttributeValue)> {
        todo!()
    }
}

#[cfg(test)]
#[allow(clippy::approx_constant)]
mod tests {
    use super::*;
    use serde_json::json;

    fn make_int(n: i64) -> AttributeValue {
        AttributeValue::try_from(&json!(n)).unwrap()
    }

    fn make_float(f: f64) -> AttributeValue {
        AttributeValue::try_from(&json!(f)).unwrap()
    }

    fn make_string(s: &str) -> AttributeValue {
        AttributeValue::try_from(&json!(s)).unwrap()
    }

    fn make_bool(b: bool) -> AttributeValue {
        AttributeValue::try_from(&json!(b)).unwrap()
    }

    #[test]
    fn test_integer_ordering() {
        let codec = DefaultKeyCodec::new();

        let key_neg100 = codec.encode_field_value_key("age", &make_int(-100));
        let key_neg10 = codec.encode_field_value_key("age", &make_int(-10));
        let key_neg1 = codec.encode_field_value_key("age", &make_int(-1));
        let key_zero = codec.encode_field_value_key("age", &make_int(0));
        let key_pos1 = codec.encode_field_value_key("age", &make_int(1));
        let key_pos10 = codec.encode_field_value_key("age", &make_int(10));
        let key_pos100 = codec.encode_field_value_key("age", &make_int(100));

        assert!(key_neg100 < key_neg10);
        assert!(key_neg10 < key_neg1);
        assert!(key_neg1 < key_zero);
        assert!(key_zero < key_pos1);
        assert!(key_pos1 < key_pos10);
        assert!(key_pos10 < key_pos100);
    }

    #[test]
    fn test_float_ordering() {
        let codec = DefaultKeyCodec::new();

        let key_neg100 = codec.encode_field_value_key("price", &make_float(-100.5));
        let key_neg1 = codec.encode_field_value_key("price", &make_float(-1.5));
        let key_neg_tiny = codec.encode_field_value_key("price", &make_float(-0.001));
        let key_zero = codec.encode_field_value_key("price", &make_float(0.0));
        let key_pos_tiny = codec.encode_field_value_key("price", &make_float(0.001));
        let key_pos1 = codec.encode_field_value_key("price", &make_float(1.5));
        let key_pos100 = codec.encode_field_value_key("price", &make_float(100.5));

        assert!(key_neg100 < key_neg1);
        assert!(key_neg1 < key_neg_tiny);
        assert!(key_neg_tiny < key_zero);
        assert!(key_zero < key_pos_tiny);
        assert!(key_pos_tiny < key_pos1);
        assert!(key_pos1 < key_pos100);
    }

    #[test]
    fn test_string_ordering() {
        let codec = DefaultKeyCodec::new();

        let key_a = codec.encode_field_value_key("name", &make_string("Alice"));
        let key_b = codec.encode_field_value_key("name", &make_string("Bob"));
        let key_c = codec.encode_field_value_key("name", &make_string("Charlie"));

        assert!(key_a < key_b);
        assert!(key_b < key_c);
    }

    #[test]
    fn test_boolean_ordering() {
        let codec = DefaultKeyCodec::new();

        let key_false = codec.encode_field_value_key("active", &make_bool(false));
        let key_true = codec.encode_field_value_key("active", &make_bool(true));

        assert!(key_false < key_true);
    }

    #[test]
    fn test_type_isolation() {
        let codec = DefaultKeyCodec::new();

        let key_int = codec.encode_field_value_key("value", &make_int(42));
        let key_str = codec.encode_field_value_key("value", &make_string("42"));
        let key_bool = codec.encode_field_value_key("value", &make_bool(true));

        assert_ne!(key_int, key_str);
        assert_ne!(key_int, key_bool);
        assert_ne!(key_str, key_bool);

        // Check for type prefixes
        let bool_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_BOOL).into_bytes();
        let int_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_INTEGER).into_bytes();
        let str_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_STRING).into_bytes();

        assert!(key_bool
            .windows(bool_prefix.len())
            .any(|w| w == bool_prefix)); // Boolean prefix
        assert!(key_int.windows(int_prefix.len()).any(|w| w == int_prefix)); // Integer prefix
        assert!(key_str.windows(str_prefix.len()).any(|w| w == str_prefix)); // String prefix
    }

    #[test]
    fn test_range_query_simulation() {
        let codec = DefaultKeyCodec::new();

        let mut keys = [
            (10, codec.encode_field_value_key("age", &make_int(10))),
            (25, codec.encode_field_value_key("age", &make_int(25))),
            (30, codec.encode_field_value_key("age", &make_int(30))),
            (35, codec.encode_field_value_key("age", &make_int(35))),
            (50, codec.encode_field_value_key("age", &make_int(50))),
            (100, codec.encode_field_value_key("age", &make_int(100))),
        ];

        keys.sort_by(|a, b| a.1.cmp(&b.1));

        let values: Vec<_> = keys.iter().map(|(v, _)| v).collect();
        assert_eq!(values, vec![&10, &25, &30, &35, &50, &100]);

        let start_key = codec.encode_field_value_key("age", &make_int(25));
        let end_key = codec.encode_field_value_key("age", &make_int(50));

        let results: Vec<_> = keys
            .iter()
            .filter(|(_, key)| key >= &start_key && key < &end_key)
            .map(|(v, _)| v)
            .collect();

        assert_eq!(results, vec![&25, &30, &35]);
    }

    #[test]
    fn test_edge_cases() {
        let codec = DefaultKeyCodec::new();

        let key_min = codec.encode_field_value_key("x", &make_int(i64::MIN));
        let key_max = codec.encode_field_value_key("x", &make_int(i64::MAX));
        assert!(key_min < key_max);

        let key_neg_zero = codec.encode_field_value_key("x", &make_float(-0.0));
        let key_pos_zero = codec.encode_field_value_key("x", &make_float(0.0));
        assert!(key_neg_zero <= key_pos_zero || key_pos_zero <= key_neg_zero);

        let key_empty = codec.encode_field_value_key("name", &make_string(""));
        let key_a = codec.encode_field_value_key("name", &make_string("a"));
        assert!(key_empty < key_a);
    }

    #[test]
    fn test_field_prefix_separation() {
        let codec = DefaultKeyCodec::new();

        let age_10 = codec.encode_field_value_key("age", &make_int(10));
        let score_5 = codec.encode_field_value_key("score", &make_int(5));

        assert!(age_10 < score_5);
    }

    // Tests for individual formatting functions
    #[test]
    fn test_format_integer_key() {
        let key = DefaultKeyCodec::format_integer_value("age", 42);
        let key_str = String::from_utf8(key.clone()).unwrap();

        // Check structure: field + separator + type prefix + encoded value
        assert!(key_str.starts_with("age"));
        assert!(key_str.contains(FIELD_SEPARATOR));
        assert!(key_str.contains(TYPE_PREFIX_INTEGER));

        // Verify format consistency
        let key_neg = DefaultKeyCodec::format_integer_value("age", -42);
        assert_eq!(key.len(), key_neg.len()); // Same length for all integers

        // Verify ordering: negative < positive
        assert!(key_neg < key);
    }

    #[test]
    fn test_format_float_key() {
        let key = DefaultKeyCodec::format_float_value("score", 3.14);
        let key_str = String::from_utf8(key.clone()).unwrap();

        // Check structure
        assert!(key_str.starts_with("score"));
        assert!(key_str.contains(FIELD_SEPARATOR));
        assert!(key_str.contains(TYPE_PREFIX_FLOAT));

        // Verify encoding preserves ordering
        let key1 = DefaultKeyCodec::format_float_value("score", 1.5);
        let key2 = DefaultKeyCodec::format_float_value("score", 2.5);
        assert!(key1 < key2);

        // Test negative floats
        let key_neg = DefaultKeyCodec::format_float_value("score", -1.5);
        let key_pos = DefaultKeyCodec::format_float_value("score", 1.5);
        assert!(key_neg < key_pos);
    }

    #[test]
    fn test_format_string_key() {
        let key = DefaultKeyCodec::format_string_value("name", "alice");
        let key_str = String::from_utf8(key).unwrap();

        // Check structure
        assert!(key_str.starts_with("name"));
        assert!(key_str.contains(FIELD_SEPARATOR));
        assert!(key_str.contains(TYPE_PREFIX_STRING));
        assert!(key_str.ends_with("alice"));

        // Test with special characters
        let key_special = DefaultKeyCodec::format_string_value("text", "hello\nworld");
        let key_special_str = String::from_utf8(key_special).unwrap();
        assert!(key_special_str.contains("hello\nworld"));

        // Test empty string
        let key_empty = DefaultKeyCodec::format_string_value("text", "");
        let key_empty_str = String::from_utf8(key_empty).unwrap();
        assert!(key_empty_str.contains(TYPE_PREFIX_STRING));
    }

    #[test]
    fn test_format_bool_key() {
        let key_true = DefaultKeyCodec::format_bool_value("active", true);
        let key_false = DefaultKeyCodec::format_bool_value("active", false);

        let key_true_str = String::from_utf8(key_true.clone()).unwrap();
        let key_false_str = String::from_utf8(key_false.clone()).unwrap();

        // Check structure
        assert!(key_true_str.starts_with("active"));
        assert!(key_true_str.contains(FIELD_SEPARATOR));
        assert!(key_true_str.contains(TYPE_PREFIX_BOOL));
        assert!(key_true_str.ends_with("1"));

        assert!(key_false_str.starts_with("active"));
        assert!(key_false_str.contains(FIELD_SEPARATOR));
        assert!(key_false_str.contains(TYPE_PREFIX_BOOL));
        assert!(key_false_str.ends_with("0"));

        // Verify ordering: false < true
        assert!(key_false < key_true);
    }

    #[test]
    fn test_format_functions_type_isolation() {
        // Ensure different types produce different prefixes
        let key_int = DefaultKeyCodec::format_integer_value("value", 42);
        let key_float = DefaultKeyCodec::format_float_value("value", 42.0);
        let key_string = DefaultKeyCodec::format_string_value("value", "42");
        let key_bool = DefaultKeyCodec::format_bool_value("value", true);

        // All should have different type prefixes
        let int_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_INTEGER).into_bytes();
        let float_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_FLOAT).into_bytes();
        let string_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_STRING).into_bytes();
        let bool_prefix = format!("{}{}", FIELD_SEPARATOR, TYPE_PREFIX_BOOL).into_bytes();

        assert!(key_int.windows(int_prefix.len()).any(|w| w == int_prefix));
        assert!(key_float
            .windows(float_prefix.len())
            .any(|w| w == float_prefix));
        assert!(key_string
            .windows(string_prefix.len())
            .any(|w| w == string_prefix));
        assert!(key_bool
            .windows(bool_prefix.len())
            .any(|w| w == bool_prefix));

        // None should match the wrong prefix
        assert!(!key_int
            .windows(float_prefix.len())
            .any(|w| w == float_prefix));
        assert!(!key_float.windows(int_prefix.len()).any(|w| w == int_prefix));
        assert!(!key_string
            .windows(int_prefix.len())
            .any(|w| w == int_prefix));
        assert!(!key_bool.windows(int_prefix.len()).any(|w| w == int_prefix));
    }

    #[test]
    fn test_format_functions_field_names() {
        // Test various field names
        let key_short = DefaultKeyCodec::format_integer_value("a", 42);
        let key_long = DefaultKeyCodec::format_integer_value("very_long_field_name", 42);
        let key_dots = DefaultKeyCodec::format_integer_value("nested.field.path", 42);

        // All should contain the field name at the start
        assert!(key_short.starts_with(b"a"));
        assert!(key_long.starts_with(b"very_long_field_name"));
        assert!(key_dots.starts_with(b"nested.field.path"));

        // All should contain the separator
        let separator = FIELD_SEPARATOR.as_bytes();
        assert!(key_short.windows(separator.len()).any(|w| w == separator));
        assert!(key_long.windows(separator.len()).any(|w| w == separator));
        assert!(key_dots.windows(separator.len()).any(|w| w == separator));
    }
}