aedb 0.2.2

Embedded Rust storage engine with transactional commits, WAL durability, and snapshot-consistent reads
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use aedb::AedbInstance;
use aedb::catalog::DdlOperation;
use aedb::commit::validation::Mutation;
use aedb::error::AedbError;
use aedb::permission::{CallerContext, Permission};
use aedb::preflight::PreflightResult;
use aedb::query::plan::ConsistencyMode;
use tempfile::tempdir;
use tokio::time::{Duration, sleep};

async fn wait_for_projected(
    db: &AedbInstance,
    project_id: &str,
    scope_id: &str,
    accumulator_name: &str,
    expected: i64,
) {
    for _ in 0..50 {
        let value = db
            .accumulator_value(
                project_id,
                scope_id,
                accumulator_name,
                ConsistencyMode::AtLatest,
            )
            .await
            .expect("projected read");
        if value == expected {
            return;
        }
        sleep(Duration::from_millis(10)).await;
    }
    panic!("projected value did not converge to expected");
}

#[tokio::test]
async fn accumulator_exactly_once_and_projected_reads() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");

    db.accumulate("p", "app", "house_balance", 100, "tx-1".into(), 1)
        .await
        .expect("accumulate 1");
    db.accumulate("p", "app", "house_balance", -25, "tx-2".into(), 2)
        .await
        .expect("accumulate 2");
    db.accumulate("p", "app", "house_balance", -25, "tx-2".into(), 2)
        .await
        .expect("duplicate idempotent retry");

    let strong = db
        .accumulator_value_strong("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("strong value");
    assert_eq!(strong, 75);

    let mut lag = db
        .accumulator_lag("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("lag");
    for _ in 0..20 {
        if lag.lag_orders == 0 && lag.projector_error.is_none() {
            break;
        }
        sleep(Duration::from_millis(10)).await;
        lag = db
            .accumulator_lag("p", "app", "house_balance", ConsistencyMode::AtLatest)
            .await
            .expect("lag refresh");
    }
    assert_eq!(lag.lag_orders, 0, "projector should eventually catch up");

    let projected = db
        .accumulator_value("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("projected value");
    assert_eq!(projected, 75);
}

#[tokio::test]
async fn accumulator_rejects_out_of_order_and_bad_dedupe_reuse() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");

    db.accumulate("p", "app", "house_balance", 10, "tx-a".into(), 10)
        .await
        .expect("accumulate baseline");

    let out_of_order = db
        .accumulate("p", "app", "house_balance", 5, "tx-b".into(), 9)
        .await
        .expect_err("out of order should fail");
    assert!(matches!(out_of_order, AedbError::Validation(_)));

    db.accumulate("p", "app", "house_balance", 5, "tx-c".into(), 11)
        .await
        .expect("next in order");
    let bad_retry = db
        .accumulate("p", "app", "house_balance", 5, "tx-c".into(), 12)
        .await
        .expect_err("dedupe key reuse with changed order should fail");
    assert!(matches!(bad_retry, AedbError::Validation(_)));
}

#[tokio::test]
async fn accumulator_recovers_from_wal_and_checkpoint() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 2)
        .await
        .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 40, "tx-1".into(), 1)
        .await
        .expect("acc 1");
    db.accumulate("p", "app", "house_balance", 2, "tx-2".into(), 2)
        .await
        .expect("acc 2");
    db.checkpoint_now().await.expect("checkpoint");
    db.shutdown().await.expect("shutdown");

    let reopened = AedbInstance::open(Default::default(), dir.path()).expect("reopen");
    let strong = reopened
        .accumulator_value_strong("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("strong");
    assert_eq!(strong, 42);
}

#[tokio::test]
async fn accumulator_overflow_is_exposed_as_health_error() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");

    db.accumulate("p", "app", "house_balance", i64::MAX, "tx-max".into(), 1)
        .await
        .expect("max");
    db.accumulate("p", "app", "house_balance", 1, "tx-over".into(), 2)
        .await
        .expect("overflow delta append");

    let mut lag = db
        .accumulator_lag("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("lag");
    for _ in 0..30 {
        if lag.projector_error.is_some() {
            break;
        }
        sleep(Duration::from_millis(10)).await;
        lag = db
            .accumulator_lag("p", "app", "house_balance", ConsistencyMode::AtLatest)
            .await
            .expect("lag refresh");
    }
    assert!(
        lag.projector_error.is_some(),
        "projector error should be reported"
    );

    let strong = db
        .accumulator_value_strong("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect_err("strong read should fail while projector unhealthy");
    assert!(matches!(strong, AedbError::Validation(_)));
}

#[tokio::test]
async fn accumulator_authenticated_apis_enforce_permissions() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    let alice = CallerContext::new("alice");

    let denied_create = db
        .create_accumulator_as(alice.clone(), "p", "app", "house_balance", Some(100), 1000)
        .await
        .expect_err("create should require ddl permission");
    assert!(matches!(denied_create, AedbError::PermissionDenied(_)));

    db.commit(Mutation::Ddl(DdlOperation::GrantPermission {
        caller_id: "alice".into(),
        permission: Permission::TableDdl {
            project_id: "p".into(),
        },
        actor_id: None,
        delegable: false,
    }))
    .await
    .expect("grant ddl");
    db.commit(Mutation::Ddl(DdlOperation::GrantPermission {
        caller_id: "alice".into(),
        permission: Permission::KvWrite {
            project_id: "p".into(),
            scope_id: Some("app".into()),
            prefix: None,
        },
        actor_id: None,
        delegable: false,
    }))
    .await
    .expect("grant kv write");
    db.commit(Mutation::Ddl(DdlOperation::GrantPermission {
        caller_id: "alice".into(),
        permission: Permission::KvRead {
            project_id: "p".into(),
            scope_id: Some("app".into()),
            prefix: None,
        },
        actor_id: None,
        delegable: false,
    }))
    .await
    .expect("grant kv read");

    db.create_accumulator_as(alice.clone(), "p", "app", "house_balance", Some(100), 1000)
        .await
        .expect("authorized create");
    db.accumulate_as(
        alice.clone(),
        "p",
        "app",
        "house_balance",
        7,
        "tx-1".into(),
        1,
    )
    .await
    .expect("authorized accumulate");

    let value = db
        .accumulator_value_as(
            &alice,
            "p",
            "app",
            "house_balance",
            ConsistencyMode::AtLatest,
        )
        .await
        .expect("authorized read");
    assert_eq!(value, 7);

    db.expose_accumulator_as(alice.clone(), "p", "app", "house_balance", 2, "h-1".into())
        .await
        .expect("authorized expose");
    let exposure = db
        .accumulator_exposure_as(
            &alice,
            "p",
            "app",
            "house_balance",
            ConsistencyMode::AtLatest,
        )
        .await
        .expect("authorized exposure read");
    assert_eq!(exposure, 2);
}

#[tokio::test]
async fn accumulator_exposure_margin_enforced_and_release_is_idempotent() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator_with_options(
        "p",
        "app",
        "house_balance",
        Some(1_000),
        10_000,
        1_000,
        None,
    )
    .await
    .expect("create accumulator");

    db.accumulate("p", "app", "house_balance", 1_000, "seed".into(), 1)
        .await
        .expect("seed balance");
    wait_for_projected(&db, "p", "app", "house_balance", 1_000).await;

    db.expose_accumulator("p", "app", "house_balance", 400, "hand-1".into())
        .await
        .expect("reserve hand 1");
    db.expose_accumulator("p", "app", "house_balance", 500, "hand-2".into())
        .await
        .expect("reserve hand 2");
    let over = db
        .expose_accumulator("p", "app", "house_balance", 1, "hand-3".into())
        .await
        .expect_err("excess reserve should fail");
    assert!(matches!(over, AedbError::Validation(_)));

    let exposure = db
        .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure");
    assert_eq!(exposure, 900);
    let available = db
        .accumulator_available("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("available");
    assert_eq!(available, 100);
    let metrics = db
        .accumulator_exposure_metrics("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure metrics");
    assert_eq!(metrics.total_exposure, 900);
    assert_eq!(metrics.available, 100);
    assert_eq!(metrics.rejection_count, 0);
    assert_eq!(metrics.open_exposure_count, 2);

    db.accumulate_with_release(
        "p",
        "app",
        "house_balance",
        -50,
        "settle-1".into(),
        2,
        Some("hand-1".into()),
    )
    .await
    .expect("settle hand 1");
    db.accumulate_with_release(
        "p",
        "app",
        "house_balance",
        -50,
        "settle-1".into(),
        2,
        Some("hand-1".into()),
    )
    .await
    .expect("idempotent settle retry");
    wait_for_projected(&db, "p", "app", "house_balance", 950).await;

    let exposure_after = db
        .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure after release");
    assert_eq!(exposure_after, 500);
    let available_after = db
        .accumulator_available("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("available after release");
    assert_eq!(available_after, 450);
    let metrics_after = db
        .accumulator_exposure_metrics("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("metrics after release");
    assert_eq!(metrics_after.total_exposure, 500);
    assert_eq!(metrics_after.open_exposure_count, 1);
}

#[tokio::test]
async fn accumulator_exposure_uses_strong_value_not_stale_projection() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator_with_options(
        "p",
        "app",
        "house_balance",
        Some(1_000),
        10_000,
        1_000,
        None,
    )
    .await
    .expect("create accumulator");

    db.accumulate("p", "app", "house_balance", 1_000, "seed".into(), 1)
        .await
        .expect("seed");
    wait_for_projected(&db, "p", "app", "house_balance", 1_000).await;

    db.accumulate("p", "app", "house_balance", -900, "loss".into(), 2)
        .await
        .expect("loss");

    let err = db
        .expose_accumulator("p", "app", "house_balance", 101, "hand-stale".into())
        .await
        .expect_err("exposure should be checked against strong value");
    assert!(matches!(err, AedbError::Validation(_)));

    let available = db
        .accumulator_available("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("available");
    assert_eq!(available, 100);

    let metrics = db
        .accumulator_exposure_metrics("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("metrics");
    assert_eq!(metrics.available, 100);

    let preflight_err = db
        .expose_accumulator_with_preflight(
            "p",
            "app",
            "house_balance",
            101,
            "hand-preflight".into(),
        )
        .await
        .expect_err("preflight should also use the strong value");
    assert!(matches!(preflight_err, AedbError::Validation(_)));
}

#[tokio::test]
async fn accumulator_release_without_exposure_is_rejected() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 100, "seed".into(), 1)
        .await
        .expect("seed");
    let err = db
        .accumulate_with_release(
            "p",
            "app",
            "house_balance",
            -5,
            "settle-missing".into(),
            2,
            Some("unknown-hand".into()),
        )
        .await
        .expect_err("release without expose should fail");
    assert!(matches!(err, AedbError::Validation(_)));
}

#[tokio::test]
async fn accumulator_expose_dedupe_is_exactly_once() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 100, "seed".into(), 1)
        .await
        .expect("seed");
    wait_for_projected(&db, "p", "app", "house_balance", 100).await;

    db.expose_accumulator("p", "app", "house_balance", 20, "hand-1".into())
        .await
        .expect("first expose");
    db.expose_accumulator("p", "app", "house_balance", 20, "hand-1".into())
        .await
        .expect("idempotent expose retry");

    let wrong_retry = db
        .expose_accumulator("p", "app", "house_balance", 21, "hand-1".into())
        .await
        .expect_err("mismatched idempotent expose should fail");
    assert!(matches!(wrong_retry, AedbError::Validation(_)));

    let exposure = db
        .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure");
    assert_eq!(exposure, 20);
}

#[tokio::test]
async fn accumulator_exposure_recovers_after_restart() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 500, "seed".into(), 1)
        .await
        .expect("seed");
    wait_for_projected(&db, "p", "app", "house_balance", 500).await;
    db.expose_accumulator("p", "app", "house_balance", 40, "hand-1".into())
        .await
        .expect("expose");
    db.checkpoint_now().await.expect("checkpoint");
    db.shutdown().await.expect("shutdown");

    let reopened = AedbInstance::open(Default::default(), dir.path()).expect("reopen");
    let exposure = reopened
        .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure");
    assert_eq!(exposure, 40);
    let available = reopened
        .accumulator_available("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("available");
    assert_eq!(available, 460);
}

#[tokio::test]
async fn accumulator_exposure_ttl_prunes_orphaned_hands() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator_with_options(
        "p",
        "app",
        "house_balance",
        Some(1_000),
        10_000,
        1_000,
        Some(2),
    )
    .await
    .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 200, "seed".into(), 1)
        .await
        .expect("seed");
    wait_for_projected(&db, "p", "app", "house_balance", 200).await;
    db.expose_accumulator("p", "app", "house_balance", 25, "orphan".into())
        .await
        .expect("expose");

    db.accumulate("p", "app", "house_balance", 0, "tick-1".into(), 2)
        .await
        .expect("tick 1");
    db.accumulate("p", "app", "house_balance", 0, "tick-2".into(), 3)
        .await
        .expect("tick 2");
    db.accumulate("p", "app", "house_balance", 0, "tick-3".into(), 4)
        .await
        .expect("tick 3");

    for _ in 0..50 {
        let exposure = db
            .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
            .await
            .expect("exposure read");
        if exposure == 0 {
            return;
        }
        sleep(Duration::from_millis(10)).await;
    }
    panic!("exposure ttl did not prune orphaned exposure");
}

#[tokio::test]
async fn accumulator_expose_many_atomic_reserves_all_or_none() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 100, "seed".into(), 1)
        .await
        .expect("seed");
    wait_for_projected(&db, "p", "app", "house_balance", 100).await;

    db.expose_accumulator_many_atomic(
        "p",
        "app",
        "house_balance",
        vec![(20, "h1".into()), (30, "h2".into())],
    )
    .await
    .expect("batch expose");
    let exposure = db
        .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure");
    assert_eq!(exposure, 50);

    let err = db
        .expose_accumulator_many_atomic(
            "p",
            "app",
            "house_balance",
            vec![(10, "h3".into()), (10, "".into())],
        )
        .await
        .expect_err("invalid batch should fail");
    assert!(matches!(err, AedbError::Validation(_)));
    let exposure_after = db
        .accumulator_exposure("p", "app", "house_balance", ConsistencyMode::AtLatest)
        .await
        .expect("exposure unchanged");
    assert_eq!(exposure_after, 50);
}

#[tokio::test]
async fn accumulator_batch_preflight_rejects_duplicate_ids_with_different_amounts() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(Default::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.create_accumulator("p", "app", "house_balance", Some(1_000), 10_000)
        .await
        .expect("create accumulator");
    db.accumulate("p", "app", "house_balance", 100, "seed".into(), 1)
        .await
        .expect("seed");
    wait_for_projected(&db, "p", "app", "house_balance", 100).await;

    let preflight = db
        .preflight(Mutation::ExposeAccumulatorBatch {
            project_id: "p".into(),
            scope_id: "app".into(),
            accumulator_name: "house_balance".into(),
            exposures: vec![(20, "dup".into()), (21, "dup".into())],
        })
        .await;

    assert!(matches!(
        preflight,
        PreflightResult::Err { ref reason }
            if reason.contains("duplicate exposure id with different amount in batch")
    ));
}