ic-db 0.30.2

Experimental embedded Internet Computer database
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
//! Frozen IcyDB time-policy regressions on the single typed commit path.

use ic_db::design::prelude::*;
use ic_db::{Batch, Database, Error};
use ic_storage::{
    AllocationGrants, GenericAllocationPolicy, MemoryAuthority, MemoryRequest, MemoryRuntime,
    SealedDeclarationSnapshot, StableKey, VectorMemory, adapter::StableBTreeMap,
};

///
/// CreatedAt
/// Gives `Timestamp` a distinct schema identity.
///

#[newtype(item(prim = "Timestamp"))]
struct CreatedAt {}

///
/// UpdatedAt
/// Gives `Timestamp` a distinct schema identity.
///

#[newtype(item(prim = "Timestamp"))]
struct UpdatedAt {}
type Changed = UpdatedAt;

///
/// Counter
/// Gives `Int64` a distinct schema identity.
///

#[newtype(item(prim = "Int64"))]
struct Counter {}

///
/// Entry
/// Exercises indexed access by `body` and `changed` on rows keyed by `id`.
///

#[entity(
    store = ic_db::testing::FixtureStore,
    pk(field = "id"),
    index(field = "body", unique),
    index(field = "changed"),
    fields(
        field(name = "id", value(item(prim = "Nat64"))),
        field(
            name = "body",
            value(item(prim = "Text", max_bytes = 32)),
            default = "ready"
        ),
        field(name = "born", value(item(is = "CreatedAt")), managed = "created_at"),
        field(
            name = "changed",
            value(item(is = "Changed", indirect)),
            managed = "updated_at"
        )
    )
)]
struct Entry {}

///
/// CreationOnly
/// Stores `value` and `time` under the `id` primary key.
///

#[entity(
    store = ic_db::testing::FixtureStore,
    pk(field = "id"),
    fields(
        field(name = "id", value(item(prim = "Nat64"))),
        field(name = "value", value(item(prim = "Nat64")), default = 0),
        field(name = "time", value(item(prim = "Timestamp")), managed = "created_at")
    )
)]
struct CreationOnly {}

///
/// UpdateOnly
/// Stores `value` and `time` under the `id` primary key.
///

#[entity(
    store = ic_db::testing::FixtureStore,
    pk(field = "id"),
    fields(
        field(name = "id", value(item(prim = "Nat64"))),
        field(name = "value", value(item(prim = "Nat64")), default = 0),
        field(name = "time", value(item(prim = "Timestamp")), managed = "updated_at")
    )
)]
struct UpdateOnly {}

#[test]
fn independent_roles_share_batch_time_and_deletes_need_no_clock() {
    let host = runtime(VectorMemory::default());
    let mut db = Database::create(
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap(),
        Schema::new(&[CreationOnly::SCHEMA, UpdateOnly::SCHEMA]).unwrap(),
        [1; 16],
    )
    .unwrap();
    let mut batch = Batch::at_for_test(time(-1));
    let mut created = batch.insert_input(CreationOnly::insert().id(1)).unwrap();
    let mut updated = batch.insert_input(UpdateOnly::insert().id(1)).unwrap();
    assert_eq!(created.time, updated.time);
    db.commit(batch).unwrap();
    created.value = 1;
    updated.value = 1;
    let mut batch = Batch::at_for_test(time(10));
    batch.replace(&created).unwrap();
    batch.replace(&updated).unwrap();
    let stored = db.commit_returning(batch, updated.id()).unwrap();
    assert_eq!(stored.value, updated.value);
    assert_eq!(stored.time, time(10));
    assert_eq!(db.get::<CreationOnly>(1).unwrap().unwrap().time, time(-1));
    assert_eq!(db.get::<UpdateOnly>(1).unwrap().unwrap().time, time(10));
    let mut batch = Batch::new();
    batch.delete::<CreationOnly>(1).unwrap();
    batch.delete::<UpdateOnly>(1).unwrap();
    db.commit(batch).unwrap();
    assert!(db.get::<CreationOnly>(1).unwrap().is_none());
    assert!(db.get::<UpdateOnly>(1).unwrap().is_none());
}

fn time(n: i64) -> Timestamp {
    Timestamp::from_millis(n)
}

fn runtime(backing: VectorMemory) -> MemoryRuntime<VectorMemory> {
    let mut runtime = MemoryRuntime::new(backing).unwrap();
    runtime
        .bootstrap(
            &SealedDeclarationSnapshot::new(vec![
                MemoryRequest::new("test", "test.db.v1").unwrap(),
            ])
            .unwrap(),
            &AllocationGrants::new(vec![MemoryAuthority::new("test", "test.").unwrap()]).unwrap(),
            &GenericAllocationPolicy,
        )
        .unwrap();

    runtime
}

#[test]
fn one_batch_time_preserves_creation_and_updates_only_real_changes() {
    let backing = VectorMemory::default();
    let host = runtime(backing.clone());
    let mut db = Database::create(
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap(),
        Schema::new(&[Entry::SCHEMA]).unwrap(),
        [1; 16],
    )
    .unwrap();
    let mut automatic = Batch::new();
    let a = automatic.insert_input(Entry::insert().id(1)).unwrap();
    let b = automatic.insert_input(Entry::insert().id(2)).unwrap();
    assert_eq!(a.born, b.born);
    let mut batch = Batch::at_for_test(time(100));
    let first = batch.insert_input(Entry::insert().id(1)).unwrap();
    let second = batch
        .insert_input(Entry::insert().id(2).body("second".into()))
        .unwrap();
    assert_eq!(
        (
            first.born.0,
            first.changed.0,
            second.born.0,
            second.changed.0
        ),
        (time(100), time(100), time(100), time(100))
    );
    assert!(matches!(
        Batch::at_for_test(time(100)).insert(&first),
        Err(Error::ManagedField)
    ));
    db.commit(batch).unwrap();
    let mut updated = first;
    updated.body = "a longer replacement".into();
    let mut batch = Batch::at_for_test(time(200));
    batch.replace(&updated).unwrap();
    db.commit(batch).unwrap();
    let current = db.get::<Entry>(1).unwrap().unwrap();
    assert_eq!((current.born.0, current.changed.0), (time(100), time(200)));
    assert_eq!(
        db.index_prefix::<Entry>("changed", &[time(100).into()], 32)
            .unwrap(),
        vec![second]
    );
    assert_eq!(
        db.index_prefix::<Entry>("changed", &[time(200).into()], 32)
            .unwrap(),
        vec![current.clone()]
    );
    let before = backing.borrow().clone();
    for now in [0, 200, 300] {
        let mut batch = Batch::at_for_test(time(now));
        batch.replace(&current).unwrap();
        assert_eq!(db.commit_returning(batch, current.id()).unwrap(), current);
        assert_eq!(*backing.borrow(), before);
    }
    drop(db);
    let db = Database::open(
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap(),
        Schema::new(&[Entry::SCHEMA]).unwrap(),
    )
    .unwrap();
    assert_eq!(db.get::<Entry>(1).unwrap(), Some(current));
}

#[test]
fn upsert_assigns_managed_times_and_replays_the_original_request() {
    let backing = VectorMemory::default();
    let host = runtime(backing.clone());
    let mut db = Database::create(
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap(),
        Schema::new(&[Entry::SCHEMA]).unwrap(),
        [1; 16],
    )
    .unwrap();
    let mut request = Entry {
        id: 1,
        body: "pending".into(),
        born: CreatedAt(time(5)),
        changed: Box::new(UpdatedAt(time(6))),
    };
    for (now, body, updated, revision) in [
        (100, "pending", 100, 1),
        (200, "a longer nomination", 200, 2),
        (300, "a longer nomination", 200, 2),
    ] {
        let before = backing.borrow().clone();
        request.body = body.into();
        let mut batch = Batch::at_for_test(time(now));
        batch.upsert(&request).unwrap();
        let stored = db.commit_returning(batch, request.id()).unwrap();
        assert_eq!(
            (stored.born.0, stored.changed.0),
            (time(100), time(updated))
        );
        assert_eq!(stored.body, body);
        assert_eq!(db.get(request.id()).unwrap(), Some(stored.clone()));
        assert_eq!(
            db.index_prefix::<Entry>("changed", &[time(updated).into()], 32)
                .unwrap(),
            vec![stored]
        );
        assert_eq!(db.cardinality::<Entry>().unwrap(), 1);
        assert_eq!(db.revision::<Entry>().unwrap(), revision);
        if now == 300 {
            assert_eq!(*backing.borrow(), before);
        }
    }
    let before = backing.borrow().clone();
    request.body = "too early".into();
    let mut batch = Batch::at_for_test(time(199));
    batch.upsert(&request).unwrap();
    assert!(matches!(db.commit(batch), Err(Error::TimestampRegression)));
    assert_eq!(*backing.borrow(), before);

    // Two distinct primary keys cannot claim the same secondary unique value.
    let mut batch = Batch::at_for_test(time(400));
    batch.upsert(&request).unwrap();
    request.id = 2;
    batch.upsert(&request).unwrap();
    assert!(matches!(db.commit(batch), Err(Error::UniqueViolation)));
    assert_eq!(*backing.borrow(), before);
}

#[test]
fn single_row_session_writes_supply_managed_time_and_preserve_replays() {
    let host = runtime(VectorMemory::default());
    let db = Database::create(
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap(),
        Schema::new(&[Entry::SCHEMA]).unwrap(),
        [1; 16],
    )
    .unwrap();
    let db = ic_db::DatabaseSession::new(db);
    let mut seed = Batch::at_for_test(time(100));
    let mut old = seed.insert_input(Entry::insert().id(1)).unwrap();
    db.commit(seed).unwrap();

    let before = Timestamp::now();
    let inserted = db
        .insert_input(Entry::insert().id(2).body("reserved".into()))
        .unwrap();
    assert_eq!(db.get::<Entry>(2).unwrap(), Some(inserted.clone()));
    assert_eq!(inserted.born.0, inserted.changed.0);
    assert!((before..=Timestamp::now()).contains(&inserted.born.0));

    db.replace(&old).unwrap();
    assert_eq!(db.get::<Entry>(1).unwrap(), Some(old.clone()));
    old.body = "confirmed".into();
    db.replace(&old).unwrap();
    let confirmed = db.get::<Entry>(1).unwrap().unwrap();
    assert_eq!(confirmed.born.0, time(100));
    assert_eq!(confirmed.body, "confirmed");
    assert!((before..=Timestamp::now()).contains(&confirmed.changed.0));
}

#[test]
fn ownership_regression_and_constraint_refusals_leave_the_complete_batch_unchanged() {
    let backing = VectorMemory::default();
    let host = runtime(backing.clone());
    let mut db = Database::create(
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap(),
        Schema::new(&[Entry::SCHEMA]).unwrap(),
        [1; 16],
    )
    .unwrap();
    let mut batch = Batch::at_for_test(time(100));
    let row = batch.insert_input(Entry::insert().id(1)).unwrap();
    db.commit(batch).unwrap();
    let before = backing.borrow().clone();
    for mode in 0..4 {
        let mut candidate = row.clone();
        candidate.body = "changed".into();
        match mode {
            0 => candidate.born.0 = time(90),
            1 => candidate.changed.0 = time(101),
            _ => {}
        }
        let mut batch = Batch::at_for_test(time(if mode == 2 { 99 } else { 200 }));
        batch
            .insert_input(
                Entry::insert()
                    .id(2)
                    .body(if mode == 3 { "changed" } else { "other" }.into()),
            )
            .unwrap();
        batch.replace(&candidate).unwrap();
        let result = db.commit_returning(batch, candidate.id());
        match mode {
            0 | 1 => assert!(matches!(result, Err(Error::ManagedField))),
            2 => assert!(matches!(result, Err(Error::TimestampRegression))),
            3 => assert!(matches!(result, Err(Error::UniqueViolation))),
            _ => unreachable!(),
        }
        assert_eq!(*backing.borrow(), before);
    }
    for delete_selected in [false, true] {
        let mut batch = Batch::at_for_test(time(200));
        batch
            .insert_input(Entry::insert().id(2).body("other".into()))
            .unwrap();
        if delete_selected {
            batch.delete::<Entry>(1).unwrap();
        }
        assert!(matches!(
            db.commit_returning(batch, row.id()),
            Err(Error::Missing)
        ));
        assert_eq!(*backing.borrow(), before);
    }
    // Equal time is permitted for a real change; there is no hidden counter.
    let mut changed = row;
    changed.body = "equal time".into();
    let mut batch = Batch::at_for_test(time(100));
    batch.replace(&changed).unwrap();
    db.commit(batch).unwrap();
    assert_eq!(db.get::<Entry>(1).unwrap(), Some(changed));
}

#[test]
fn corrupt_managed_order_refuses_reads_and_noop_replacement_without_repair() {
    let backing = VectorMemory::default();
    let host = runtime(backing.clone());
    let memory = || {
        host.open_memory(&StableKey::parse("test.db.v1").unwrap())
            .unwrap()
    };
    let schema = || Schema::new(&[Entry::SCHEMA]).unwrap();
    let mut db = Database::create(memory(), schema(), [1; 16]).unwrap();
    let mut batch = Batch::at_for_test(time(100));
    let row = batch.insert_input(Entry::insert().id(1)).unwrap();
    db.commit(batch).unwrap();
    drop(db);
    let mut corrupt = row.encode().unwrap();
    // Independent framing: u32 text length, five UTF-8 bytes, then born/changed i64.
    corrupt[9..17].copy_from_slice(&101_i64.to_le_bytes());
    assert!(matches!(Entry::decode(&corrupt), Err(Error::Corrupt)));
    let mut map = StableBTreeMap::<Vec<u8>, Vec<u8>, _>::load(memory());
    let mut key = vec![2];
    key.extend(Entry::SCHEMA.id.to_be_bytes());
    key.extend(1_u64.to_be_bytes());
    map.insert(key, corrupt);
    drop(map);
    let before = backing.borrow().clone();
    let mut db = Database::open(memory(), schema()).unwrap();
    assert!(matches!(db.get::<Entry>(1), Err(Error::Corrupt)));
    let mut batch = Batch::at_for_test(time(200));
    batch.replace(&row).unwrap();
    assert!(matches!(db.commit(batch), Err(Error::Corrupt)));
    assert_eq!(*backing.borrow(), before);
}

#[test]
fn managed_policy_changes_identity_and_refuses_incompatible_reopen_intact() {
    let original = Schema::new(&[Entry::SCHEMA]).unwrap();
    let mut fields = Entry::SCHEMA.fields.to_vec();
    for field in &mut fields {
        field.managed = None;
    }
    let unowned = Box::leak(Box::new(ic_db::EntitySchema {
        fields: Box::leak(fields.into_boxed_slice()),
        ..*Entry::SCHEMA
    }));
    let different = Schema::new(&[unowned]).unwrap();
    assert_ne!(original.fingerprint(), different.fingerprint());
    let backing = VectorMemory::default();
    let host = runtime(backing.clone());
    drop(
        Database::create(
            host.open_memory(&StableKey::parse("test.db.v1").unwrap())
                .unwrap(),
            original,
            [1; 16],
        )
        .unwrap(),
    );
    let before = backing.borrow().clone();
    assert!(matches!(
        Database::open(
            host.open_memory(&StableKey::parse("test.db.v1").unwrap())
                .unwrap(),
            different
        ),
        Err(Error::IncompatibleSchema)
    ));
    assert_eq!(*backing.borrow(), before);
    for mode in 0..5 {
        let mut fields = Entry::SCHEMA.fields.to_vec();
        let born = fields.iter_mut().find(|f| f.name == "born").unwrap();
        match mode {
            0 => born.optional = true,
            1 => born.value = ic_db::FieldType::Int64,
            2 => born.default = Some(&ic_db::LiteralDefault::Int(0)),
            3 => born.managed = Some(ic_db::ManagedTimestamp::UpdatedAt),
            4 => {
                use ic_db::Value;
                born.value = ic_db::FieldType::Named(ic_db::TypeLink {
                    name: Counter::NAME,
                    definition: Counter::definition,
                });
            }
            _ => unreachable!(),
        }
        let invalid = Box::leak(Box::new(ic_db::EntitySchema {
            fields: Box::leak(fields.into_boxed_slice()),
            ..*Entry::SCHEMA
        }));
        assert!(matches!(Schema::new(&[invalid]), Err(Error::InvalidSchema)));
    }
}