icydb-core 0.180.12

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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use super::*;
use crate::metrics::sink::MutationCommitClass;

fn mutation_commit_classes_for_entity(
    events: &[MetricsEvent],
    entity_path: &'static str,
) -> Vec<MutationCommitClass> {
    events
        .iter()
        .filter_map(|event| match event {
            MetricsEvent::MutationCommitPlan {
                entity_path: path,
                class,
            } if *path == entity_path => Some(*class),
            _ => None,
        })
        .collect()
}

fn capture_mutation_commit_classes<R>(
    entity_path: &'static str,
    run: impl FnOnce() -> R,
) -> (R, Vec<MutationCommitClass>) {
    let sink = SessionMetricsCaptureSink::default();
    let output = with_metrics_sink(&sink, run);
    let classes = mutation_commit_classes_for_entity(&sink.into_events(), entity_path);

    (output, classes)
}

fn public_projection_rows<E>(session: &DbSession<SessionSqlCanister>, sql: &str) -> Vec<Vec<Value>>
where
    E: PersistedRow<Canister = SessionSqlCanister> + EntityValue,
{
    let result = session
        .execute_sql_query::<E>(sql)
        .unwrap_or_else(|err| panic!("public SQL query should succeed: {sql}: {err}"));

    let SqlStatementResult::Projection { rows, .. } = result else {
        panic!("public SQL query should emit projection rows: {sql}");
    };

    rows.into_iter()
        .map(|row| row.into_iter().map(runtime_output).collect())
        .collect()
}

fn public_explain_text<E>(session: &DbSession<SessionSqlCanister>, sql: &str) -> String
where
    E: PersistedRow<Canister = SessionSqlCanister> + EntityValue,
{
    let result = session
        .execute_sql_query::<E>(sql)
        .unwrap_or_else(|err| panic!("public EXPLAIN query should succeed: {sql}: {err}"));

    let SqlStatementResult::Explain(explain) = result else {
        panic!("public EXPLAIN query should emit explain text: {sql}");
    };

    explain
}

fn seed_journaled_session_entities(session: &DbSession<SessionSqlCanister>) {
    for (id, name, age) in [(1, "Atlas", 20), (2, "Beryl", 30), (3, "Cato", 40)] {
        session
            .insert(JournaledSessionSqlEntity {
                id,
                name: name.to_string(),
                age,
            })
            .expect("journaled typed insert should succeed while live");
    }
}

fn first_journaled_session_batch() -> JournalBatch {
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow(|store| {
        let mut captured = None;
        store
            .visit_batches_after(JournalSequence::new(0), |batch| {
                captured = Some(batch.clone());
                Ok(JournalTailVisit::Stop)
            })
            .expect("journal tail should be readable");

        captured.expect("journal tail should contain at least one committed batch")
    })
}

#[test]
fn journaled_session_write_read_and_index_query_round_trip_while_live() {
    reset_journaled_session_sql_store();
    let session = journaled_sql_session();
    seed_journaled_session_entities(&session);

    let loaded = session
        .load::<JournaledSessionSqlEntity>()
        .order_term(crate::db::asc("id"))
        .execute()
        .and_then(crate::db::LoadQueryResult::into_rows)
        .expect("journaled fluent load should read live rows")
        .entities();
    assert_eq!(
        loaded
            .iter()
            .map(|entity| (entity.id, entity.name.as_str(), entity.age))
            .collect::<Vec<_>>(),
        vec![(1, "Atlas", 20), (2, "Beryl", 30), (3, "Cato", 40)],
    );

    let rows = public_projection_rows::<JournaledSessionSqlEntity>(
        &session,
        "SELECT name, age FROM JournaledSessionSqlEntity \
         WHERE name >= 'B' AND name < 'D' \
         ORDER BY name ASC",
    );
    assert_eq!(
        rows,
        vec![
            vec![Value::Text("Beryl".to_string()), Value::Nat64(30)],
            vec![Value::Text("Cato".to_string()), Value::Nat64(40)],
        ],
    );

    let explain = public_explain_text::<JournaledSessionSqlEntity>(
        &session,
        "EXPLAIN EXECUTION SELECT name \
         FROM JournaledSessionSqlEntity \
         WHERE name >= 'B' AND name < 'D' \
         ORDER BY name ASC",
    );
    assert!(
        explain.contains("access_strategy=IndexRange(name)"),
        "journaled indexed query should keep the secondary-index route: {explain}",
    );
    assert!(
        !explain.contains("access=FullScan"),
        "journaled indexed query should not collapse to a full scan: {explain}",
    );
}

#[test]
fn journaled_session_writes_append_journal_and_leave_canonical_btrees_untouched() {
    reset_journaled_session_sql_store();
    let session = journaled_sql_session();
    seed_journaled_session_entities(&session);

    JOURNALED_SESSION_SQL_DATA_STORE.with_borrow(|store| {
        assert_eq!(store.len(), 3);
        assert_eq!(
            store.canonical_len_for_tests(),
            0,
            "normal journaled writes must not fold into canonical data BTree",
        );
    });
    JOURNALED_SESSION_SQL_INDEX_STORE.with_borrow(|store| {
        assert_eq!(store.len(), 3);
        assert_eq!(
            store.canonical_len_for_tests(),
            0,
            "normal journaled writes must not fold into canonical index BTree",
        );
    });
    JOURNALED_SESSION_SQL_SCHEMA_STORE.with_borrow(|store| {
        assert_eq!(store.len(), 1);
        assert_eq!(
            store.canonical_len_for_tests(),
            0,
            "live schema reconciliation must not fold into canonical schema BTree",
        );
    });
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow(|store| {
        assert_eq!(
            store.len(),
            3,
            "each committed row mutation should append one marker-bound journal batch",
        );
    });
}

#[test]
fn journaled_session_recovery_folds_committed_tail_into_canonical_btrees() {
    reset_journaled_session_sql_store();
    let session = journaled_sql_session();
    seed_journaled_session_entities(&session);

    reinitialize_journaled_session_sql_store();
    let recovered_session = journaled_sql_session();

    let loaded = recovered_session
        .load::<JournaledSessionSqlEntity>()
        .order_term(crate::db::asc("id"))
        .execute()
        .and_then(crate::db::LoadQueryResult::into_rows)
        .expect("journaled recovery should restore live rows from the tail")
        .entities();
    assert_eq!(
        loaded
            .iter()
            .map(|entity| (entity.id, entity.name.as_str(), entity.age))
            .collect::<Vec<_>>(),
        vec![(1, "Atlas", 20), (2, "Beryl", 30), (3, "Cato", 40)],
    );

    let rows = public_projection_rows::<JournaledSessionSqlEntity>(
        &recovered_session,
        "SELECT name, age FROM JournaledSessionSqlEntity \
         WHERE name >= 'B' AND name < 'D' \
         ORDER BY name ASC",
    );
    assert_eq!(
        rows,
        vec![
            vec![Value::Text("Beryl".to_string()), Value::Nat64(30)],
            vec![Value::Text("Cato".to_string()), Value::Nat64(40)],
        ],
    );

    JOURNALED_SESSION_SQL_DATA_STORE.with_borrow(|store| {
        assert_eq!(store.len(), 3);
        assert_eq!(
            store.canonical_len_for_tests(),
            3,
            "recovery fold must apply committed row batches to canonical data",
        );
    });
    JOURNALED_SESSION_SQL_INDEX_STORE.with_borrow(|store| {
        assert_eq!(store.len(), 3);
        assert_eq!(
            store.canonical_len_for_tests(),
            3,
            "recovery fold must materialize derived indexes into canonical index",
        );
    });
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow(|store| {
        let watermark = store
            .fold_watermark()
            .expect("journal fold watermark should be readable");
        assert_eq!(store.len(), 0);
        assert_eq!(watermark.highest_folded_journal_sequence().get(), 3);
        assert_eq!(watermark.fold_epoch(), 1);
    });
}

#[test]
fn journaled_session_recovery_repairs_missing_marker_bound_journal_tail_batch() {
    reset_journaled_session_sql_store();
    let session = journaled_sql_session();
    session
        .insert(JournaledSessionSqlEntity {
            id: 1,
            name: "Atlas".to_string(),
            age: 20,
        })
        .expect("journaled typed insert should succeed while live");

    let batch = first_journaled_session_batch();
    JOURNALED_SESSION_SQL_DATA_STORE
        .with_borrow_mut(|store| *store = DataStore::init_journaled(test_memory(180)));
    JOURNALED_SESSION_SQL_INDEX_STORE
        .with_borrow_mut(|store| *store = IndexStore::init_journaled(test_memory(181)));
    JOURNALED_SESSION_SQL_SCHEMA_STORE
        .with_borrow_mut(|store| *store = SchemaStore::init_journaled(test_memory(182)));
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow_mut(JournalTailStore::clear);

    let marker = crate::db::commit::CommitMarker::from_parts(
        batch.commit_marker_id(),
        Vec::new(),
        vec![batch],
    )
    .expect("marker-bound journal recovery fixture should build");
    crate::db::commit::begin_commit(marker)
        .expect("marker-bound journal recovery fixture should persist marker");
    ensure_recovered(&JOURNALED_SESSION_SQL_DB)
        .expect("journaled recovery should repair marker-bound journal publication");

    let recovered_session = journaled_sql_session();
    let loaded = recovered_session
        .load::<JournaledSessionSqlEntity>()
        .execute()
        .and_then(crate::db::LoadQueryResult::into_rows)
        .expect("journaled recovery should replay repaired journal batch")
        .entities();
    assert_eq!(loaded.len(), 1);
    assert_eq!(loaded[0].name, "Atlas");
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow(|store| {
        let watermark = store
            .fold_watermark()
            .expect("journal fold watermark should be readable");
        assert_eq!(
            store.len(),
            0,
            "recovery should publish then fold the embedded marker-bound batch",
        );
        assert_eq!(watermark.highest_folded_journal_sequence().get(), 1);
    });
    JOURNALED_SESSION_SQL_DATA_STORE.with_borrow(|store| {
        assert_eq!(
            store.canonical_len_for_tests(),
            1,
            "repaired marker-bound batch should fold into canonical data",
        );
    });
}

#[test]
fn journaled_session_recovery_reuses_matching_marker_bound_journal_tail_batch() {
    reset_journaled_session_sql_store();
    let session = journaled_sql_session();
    session
        .insert(JournaledSessionSqlEntity {
            id: 1,
            name: "Atlas".to_string(),
            age: 20,
        })
        .expect("journaled typed insert should succeed while live");

    let batch = first_journaled_session_batch();
    JOURNALED_SESSION_SQL_DATA_STORE
        .with_borrow_mut(|store| *store = DataStore::init_journaled(test_memory(180)));
    JOURNALED_SESSION_SQL_INDEX_STORE
        .with_borrow_mut(|store| *store = IndexStore::init_journaled(test_memory(181)));
    JOURNALED_SESSION_SQL_SCHEMA_STORE
        .with_borrow_mut(|store| *store = SchemaStore::init_journaled(test_memory(182)));

    let marker = crate::db::commit::CommitMarker::from_parts(
        batch.commit_marker_id(),
        Vec::new(),
        vec![batch],
    )
    .expect("marker-bound journal recovery fixture should build");
    crate::db::commit::begin_commit(marker)
        .expect("marker-bound journal recovery fixture should persist marker");
    ensure_recovered(&JOURNALED_SESSION_SQL_DB)
        .expect("journaled recovery should treat an existing matching journal batch as idempotent");

    let recovered_session = journaled_sql_session();
    let loaded = recovered_session
        .load::<JournaledSessionSqlEntity>()
        .execute()
        .and_then(crate::db::LoadQueryResult::into_rows)
        .expect("journaled recovery should replay the idempotent journal batch once")
        .entities();
    assert_eq!(loaded.len(), 1);
    assert_eq!(loaded[0].name, "Atlas");
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow(|store| {
        let watermark = store
            .fold_watermark()
            .expect("journal fold watermark should be readable");
        assert_eq!(
            store.len(),
            0,
            "recovery should fold the already-persisted matching batch exactly once",
        );
        assert_eq!(watermark.highest_folded_journal_sequence().get(), 1);
    });
    JOURNALED_SESSION_SQL_DATA_STORE.with_borrow(|store| {
        assert_eq!(
            store.canonical_len_for_tests(),
            1,
            "idempotent marker-bound recovery should not duplicate canonical rows",
        );
    });
    JOURNALED_SESSION_SQL_INDEX_STORE.with_borrow(|store| {
        assert_eq!(
            store.canonical_len_for_tests(),
            1,
            "idempotent marker-bound recovery should not duplicate derived index rows",
        );
    });
}

#[test]
fn journaled_session_recovery_rejects_mismatched_marker_bound_journal_tail_batch() {
    reset_journaled_session_sql_store();
    let session = journaled_sql_session();
    session
        .insert(JournaledSessionSqlEntity {
            id: 1,
            name: "Atlas".to_string(),
            age: 20,
        })
        .expect("journaled typed insert should succeed while live");

    let existing = first_journaled_session_batch();
    let conflicting = JournalBatch::new(
        [0xE1; 16],
        [0xE2; 16],
        existing.journal_sequence(),
        existing.records().to_vec(),
    )
    .expect("conflicting same-sequence journal batch should build");
    let marker = crate::db::commit::CommitMarker::from_parts(
        conflicting.commit_marker_id(),
        Vec::new(),
        vec![conflicting],
    )
    .expect("conflicting marker-bound journal fixture should build");
    crate::db::commit::begin_commit(marker)
        .expect("conflicting marker-bound journal fixture should persist marker");

    let err = ensure_recovered(&JOURNALED_SESSION_SQL_DB)
        .expect_err("recovery should reject marker payload that conflicts with journal tail bytes");
    assert_eq!(err.class, ErrorClass::Corruption);
    assert_eq!(err.origin, ErrorOrigin::Store);
    assert!(
        crate::db::commit::commit_marker_present().expect("commit marker check should succeed"),
        "failed journal publication must keep the marker persisted for retry",
    );
    JOURNALED_SESSION_SQL_JOURNAL_STORE.with_borrow(|store| {
        let watermark = store
            .fold_watermark()
            .expect("journal fold watermark should be readable");
        assert_eq!(
            watermark.highest_folded_journal_sequence().get(),
            0,
            "conflicting marker-bound batch must fail before fold watermark advances",
        );
        assert_eq!(
            store.len(),
            1,
            "conflicting marker-bound recovery must not mutate the existing journal tail",
        );
    });

    crate::db::commit::clear_commit_marker_for_tests()
        .expect("failed marker cleanup should succeed");
}

#[test]
fn stable_source_strong_relation_to_journaled_target_uses_durable_capabilities() {
    reset_mixed_journaled_relation_stores();
    let session = mixed_journaled_relation_sql_session();
    session
        .insert(JournaledSessionSqlEntity {
            id: 1,
            name: "Atlas".to_string(),
            age: 20,
        })
        .expect("journaled relation target should seed while live");

    let (result, classes) = capture_mutation_commit_classes(
        StableSessionSqlSourceToJournaledTargetEntity::PATH,
        || {
            session.insert(StableSessionSqlSourceToJournaledTargetEntity {
                id: 10,
                target_id: 1,
            })
        },
    );
    result.expect("stable source strong relation to journaled target should validate as durable");
    assert_eq!(
        classes,
        vec![MutationCommitClass::DurableOnly],
        "journaled durable targets must not make stable-source relation writes live-only or mixed",
    );

    let persisted = session
        .load::<StableSessionSqlSourceToJournaledTargetEntity>()
        .execute()
        .and_then(crate::db::LoadQueryResult::into_rows)
        .expect("stable-source journaled-target relation load should succeed")
        .entities();
    assert_eq!(
        persisted,
        vec![StableSessionSqlSourceToJournaledTargetEntity {
            id: 10,
            target_id: 1,
        }],
    );
}