icydb-core 0.264.7

IcyDB — A schema-first typed query engine and persistence runtime for Internet Computer canisters
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
use super::{
    KeyEnvelope, continuation_advanced, key_within_envelope, resume_bounds_for_continuation,
    resume_bounds_from_refs, resume_prefix_bounds_for_continuation,
    validate_index_scan_continuation_advancement, validate_index_scan_continuation_envelope,
};
use crate::{
    db::{
        direction::Direction,
        index::{
            EncodedValue, RawIndexStoreKey, build_index_prefix_bounds_for_encoded_components,
            envelope_is_empty,
            key::{IndexId, IndexKeyKind, OrderedValueEncodeError},
        },
    },
    error::{ErrorClass, ErrorOrigin},
    value::Value,
};
use ic_memory::ic_stable_structures::Storable;
use proptest::prelude::*;
use std::{borrow::Cow, cmp::Ordering, ops::Bound};

#[test]
fn key_envelope_contains_respects_inclusive_and_exclusive_bounds() {
    let envelope = KeyEnvelope::new(Bound::Included(10_u8), Bound::Excluded(20_u8));

    assert!(envelope.contains(&10));
    assert!(envelope.contains(&19));
    assert!(!envelope.contains(&9));
    assert!(!envelope.contains(&20));
}

#[test]
fn key_envelope_contains_handles_unbounded_edges() {
    let lower_unbounded = KeyEnvelope::new(Bound::Unbounded::<u8>, Bound::Included(3_u8));
    assert!(lower_unbounded.contains(&0));
    assert!(lower_unbounded.contains(&3));
    assert!(!lower_unbounded.contains(&4));

    let upper_unbounded = KeyEnvelope::new(Bound::Excluded(5_u8), Bound::Unbounded::<u8>);
    assert!(!upper_unbounded.contains(&5));
    assert!(upper_unbounded.contains(&6));
}

#[test]
fn key_within_envelope_matches_key_envelope_contains() {
    let lower = Bound::Excluded(100_u16);
    let upper = Bound::Included(120_u16);
    let key = 120_u16;

    assert_eq!(
        key_within_envelope(&key, &lower, &upper),
        KeyEnvelope::new(lower, upper).contains(&key),
        "free helper should delegate to envelope semantics",
    );
}

#[test]
fn continuation_advanced_is_directional() {
    let anchor = 0x10_u8;
    let asc_candidate = 0x11_u8;
    let desc_candidate = 0x0F_u8;

    assert!(continuation_advanced(
        Direction::Asc,
        &asc_candidate,
        &anchor
    ));
    assert!(!continuation_advanced(
        Direction::Asc,
        &desc_candidate,
        &anchor
    ));
    assert!(continuation_advanced(
        Direction::Desc,
        &desc_candidate,
        &anchor
    ));
    assert!(!continuation_advanced(
        Direction::Desc,
        &asc_candidate,
        &anchor
    ));
}

#[test]
fn continuation_advancement_guard_rejects_non_advanced_candidate_asc() {
    let anchor = 0x10_u8;
    let candidate = 0x10_u8;

    let err =
        validate_index_scan_continuation_advancement(Direction::Asc, Some(&anchor), &candidate)
            .expect_err("ASC continuation candidate equal to anchor must be rejected");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Index);
}

#[test]
fn continuation_advancement_guard_rejects_non_advanced_candidate_desc() {
    let anchor = 0x10_u8;
    let candidate = 0x11_u8;

    let err =
        validate_index_scan_continuation_advancement(Direction::Desc, Some(&anchor), &candidate)
            .expect_err("DESC continuation candidate not strictly after anchor must be rejected");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Index);
}

#[test]
fn anchor_containment_guard_rejects_out_of_envelope_anchor() {
    let lower = Bound::Included(0x10_u8);
    let upper = Bound::Excluded(0x20_u8);
    let anchor = 0x20_u8;

    let err = validate_index_scan_continuation_envelope(Some(&anchor), &lower, &upper)
        .expect_err("out-of-envelope continuation anchor must be rejected");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Index);
}

#[test]
fn anchor_equal_to_upper_resumes_to_empty_envelope() {
    let lower = Bound::Included(raw_key(0x10));
    let upper = Bound::Included(raw_key(0x20));
    let anchor = raw_key(0x20);

    let (resumed_lower, resumed_upper) =
        resume_bounds_from_refs(Direction::Asc, &lower, &upper, &anchor);
    assert!(
        envelope_is_empty(&resumed_lower, &resumed_upper),
        "anchor==upper must resume to an empty envelope so scan can short-circuit",
    );
}

#[test]
fn desc_anchor_equal_to_lower_resumes_to_empty_envelope() {
    let lower = Bound::Included(raw_key(0x10));
    let upper = Bound::Included(raw_key(0x20));
    let anchor = raw_key(0x10);

    let (resumed_lower, resumed_upper) =
        resume_bounds_from_refs(Direction::Desc, &lower, &upper, &anchor);
    assert!(
        envelope_is_empty(&resumed_lower, &resumed_upper),
        "DESC anchor==lower must resume to an empty envelope so scan can short-circuit",
    );
}

#[test]
fn resume_bounds_for_continuation_returns_original_bounds_without_anchor() {
    let lower = Bound::Included(raw_key(0x10));
    let upper = Bound::Excluded(raw_key(0x20));

    let resumed = resume_bounds_for_continuation(Direction::Asc, None, &lower, &upper)
        .expect("anchor-free continuation should preserve original bounds");

    assert_eq!(resumed, (lower, upper));
}

#[test]
fn resume_bounds_for_continuation_rejects_out_of_envelope_anchor() {
    let lower = Bound::Included(raw_key(0x10));
    let upper = Bound::Excluded(raw_key(0x20));
    let anchor = raw_key(0x20);

    let err = resume_bounds_for_continuation(Direction::Asc, Some(&anchor), &lower, &upper)
        .expect_err("out-of-envelope anchor must fail before resume-bounds derivation");

    assert_eq!(err.class, ErrorClass::InvariantViolation);
    assert_eq!(err.origin, ErrorOrigin::Index);
}

#[test]
fn envelope_emptiness_identifies_empty_equal_exclusive_bounds() {
    let lower = Bound::Included(raw_key(0x10));
    let upper = Bound::Excluded(raw_key(0x10));

    assert!(envelope_is_empty(&lower, &upper));
}

fn raw_key(byte: u8) -> RawIndexStoreKey {
    <RawIndexStoreKey as Storable>::from_bytes(Cow::Owned(vec![byte]))
}

fn property_index_id() -> IndexId {
    IndexId::new(crate::types::EntityTag::new(0xC01A_71C0_0000_0001), 0)
}

// Build one canonical raw index key from semantic composite components.
fn canonical_raw_key(values: &[Value]) -> RawIndexStoreKey {
    let encoded = values
        .iter()
        .map(EncodedValue::try_from_ref)
        .collect::<Result<Vec<_>, _>>()
        .expect("property-domain values must remain canonically index-encodable");
    let (lower, _) = crate::db::query::preparation::with_preparation_work(|work| {
        build_index_prefix_bounds_for_encoded_components(
            &property_index_id(),
            IndexKeyKind::User,
            values.len(),
            encoded.as_slice(),
            work,
        )
    })
    .expect("test index range bounds should encode");

    let Bound::Included(key) = lower else {
        panic!("canonical prefix lower bound should be included");
    };

    key
}

#[test]
fn global_prefix_resume_intersects_completed_boundary_and_future_branches() {
    let lower = Bound::Included(canonical_raw_key(&[Value::Nat64(10)]));
    let upper = Bound::Excluded(canonical_raw_key(&[Value::Nat64(20)]));
    for (position, empty_asc, empty_desc) in [
        (5, false, true),
        (10, false, true),
        (15, false, false),
        (20, true, false),
        (25, true, false),
    ] {
        let anchor = canonical_raw_key(&[Value::Nat64(position)]);
        for (direction, empty) in [(Direction::Asc, empty_asc), (Direction::Desc, empty_desc)] {
            let (resumed_lower, resumed_upper) =
                resume_prefix_bounds_for_continuation(direction, Some(&anchor), &lower, &upper)
                    .unwrap();
            assert_eq!(envelope_is_empty(&resumed_lower, &resumed_upper), empty);
            for candidate in [5, 10, 14, 15, 16, 19, 20, 25] {
                let key = canonical_raw_key(&[Value::Nat64(candidate)]);
                assert_eq!(
                    key_within_envelope(&key, &resumed_lower, &resumed_upper),
                    key_within_envelope(&key, &lower, &upper)
                        && continuation_advanced(direction, &key, &anchor)
                );
            }
        }
    }
    assert_eq!(
        resume_prefix_bounds_for_continuation(Direction::Asc, None, &lower, &upper).unwrap(),
        (lower, upper)
    );
}

#[test]
fn global_prefix_resume_rejects_namespace_shape_and_malformed_anchors() {
    let lower = Bound::Included(canonical_raw_key(&[Value::Nat64(10)]));
    let upper = Bound::Included(canonical_raw_key(&[Value::Nat64(20)]));
    let encoded = EncodedValue::try_from_ref(&Value::Nat64(15)).unwrap();
    let wrong_namespace = crate::db::index::raw_keys_for_component_prefix_with_kind(
        &IndexId::new(crate::types::EntityTag::new(123), 0),
        IndexKeyKind::User,
        1,
        std::slice::from_ref(&encoded),
    )
    .unwrap()
    .0;
    let wrong_generation = crate::db::index::raw_keys_for_component_prefix_with_kind(
        &IndexId::new_with_generation(crate::types::EntityTag::new(0xC01A_71C0_0000_0001), 0, 99),
        IndexKeyKind::User,
        1,
        std::slice::from_ref(&encoded),
    )
    .unwrap()
    .0;
    let wrong_kind = crate::db::index::raw_keys_for_component_prefix_with_kind(
        &property_index_id(),
        IndexKeyKind::System,
        1,
        &[encoded],
    )
    .unwrap()
    .0;
    for anchor in [
        wrong_namespace,
        wrong_generation,
        wrong_kind,
        canonical_raw_key(&[Value::Nat64(15), Value::Nat64(1)]),
        raw_key(0),
    ] {
        for direction in [Direction::Asc, Direction::Desc] {
            let error =
                resume_prefix_bounds_for_continuation(direction, Some(&anchor), &lower, &upper)
                    .unwrap_err();
            let expected = crate::error::InternalError::index_scan_continuation_anchor_within_envelope_required();
            assert_eq!(error.diagnostic(), expected.diagnostic());
        }
    }
}

fn int_component_strategy() -> impl Strategy<Value = Value> {
    prop_oneof![
        Just(Value::Int64(i64::MIN)),
        Just(Value::Int64(-1_i64)),
        Just(Value::Int64(0_i64)),
        Just(Value::Int64(1_i64)),
        Just(Value::Int64(i64::MAX)),
    ]
}

fn text_component_strategy() -> impl Strategy<Value = Value> {
    prop_oneof![
        Just(Value::Text(String::new())),
        Just(Value::Text("a".to_string())),
        Just(Value::Text("mm".to_string())),
        Just(Value::Text("zz".to_string())),
    ]
}

fn nat_component_strategy() -> impl Strategy<Value = Value> {
    prop_oneof![
        Just(Value::Nat64(0_u64)),
        Just(Value::Nat64(1_u64)),
        Just(Value::Nat64(1024_u64)),
        Just(Value::Nat64(u64::MAX)),
    ]
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(256))]

    #[test]
    fn cross_layer_canonical_ordering_is_consistent(
        left_int in int_component_strategy(),
        left_text in text_component_strategy(),
        left_nat in nat_component_strategy(),
        right_int in int_component_strategy(),
        right_text in text_component_strategy(),
        right_nat in nat_component_strategy(),
    ) {
        // Phase 1: canonicalize through encode -> decode -> re-encode for both keys.
        let left_recanonical = canonical_raw_key(&[left_int, left_text, left_nat]);
        let right_recanonical = canonical_raw_key(&[right_int, right_text, right_nat]);

        // Phase 2: treat left as anchor and right as candidate under all comparator gates.
        let ordering = left_recanonical.cmp(&right_recanonical);
        let lower_included_asc = key_within_envelope(
            &right_recanonical,
            &Bound::Included(left_recanonical.clone()),
            &Bound::Unbounded,
        );
        let lower_excluded_asc = key_within_envelope(
            &right_recanonical,
            &Bound::Excluded(left_recanonical.clone()),
            &Bound::Unbounded,
        );
        let upper_included_asc = key_within_envelope(
            &right_recanonical,
            &Bound::Unbounded,
            &Bound::Included(left_recanonical.clone()),
        );
        let upper_excluded_asc = key_within_envelope(
            &right_recanonical,
            &Bound::Unbounded,
            &Bound::Excluded(left_recanonical.clone()),
        );
        let lower_included_desc = key_within_envelope(
            &right_recanonical,
            &Bound::Included(left_recanonical.clone()),
            &Bound::Unbounded,
        );
        let lower_excluded_desc = key_within_envelope(
            &right_recanonical,
            &Bound::Excluded(left_recanonical.clone()),
            &Bound::Unbounded,
        );
        let upper_included_desc = key_within_envelope(
            &right_recanonical,
            &Bound::Unbounded,
            &Bound::Included(left_recanonical.clone()),
        );
        let upper_excluded_desc = key_within_envelope(
            &right_recanonical,
            &Bound::Unbounded,
            &Bound::Excluded(left_recanonical.clone()),
        );
        let asc_advanced =
            continuation_advanced(Direction::Asc, &right_recanonical, &left_recanonical);
        let desc_advanced =
            continuation_advanced(Direction::Desc, &right_recanonical, &left_recanonical);

        // Phase 3: assert all cross-layer checks agree on the same ordering domain.
        prop_assert_eq!(
            lower_included_asc,
            ordering != Ordering::Greater,
            "included lower-bound containment must match raw-key comparator",
        );
        prop_assert_eq!(
            lower_excluded_asc,
            ordering == Ordering::Less,
            "excluded lower-bound containment must match strict raw-key comparator",
        );
        prop_assert_eq!(
            upper_included_asc,
            ordering != Ordering::Less,
            "included upper-bound containment must match raw-key comparator",
        );
        prop_assert_eq!(
            upper_excluded_asc,
            ordering == Ordering::Greater,
            "excluded upper-bound containment must match strict raw-key comparator",
        );
        prop_assert_eq!(
            lower_included_desc,
            lower_included_asc,
            "envelope containment must be direction-symmetric for included lower bounds",
        );
        prop_assert_eq!(
            lower_excluded_desc,
            lower_excluded_asc,
            "envelope containment must be direction-symmetric for excluded lower bounds",
        );
        prop_assert_eq!(
            upper_included_desc,
            upper_included_asc,
            "envelope containment must be direction-symmetric for included upper bounds",
        );
        prop_assert_eq!(
            upper_excluded_desc,
            upper_excluded_asc,
            "envelope containment must be direction-symmetric for excluded upper bounds",
        );
        prop_assert_eq!(
            asc_advanced,
            ordering == Ordering::Less,
            "ASC continuation advancement must match strict raw-key ordering",
        );
        prop_assert_eq!(
            desc_advanced,
            ordering == Ordering::Greater,
            "DESC continuation advancement must match strict raw-key ordering",
        );
    }
}

#[test]
fn canonical_ordering_property_domain_rejects_null_components() {
    let err = EncodedValue::try_from_ref(&Value::Null)
        .expect_err("null values must remain non-indexable for canonical key domains");
    std::assert_matches!(err, OrderedValueEncodeError::NullNotIndexable);
}