aedb 0.2.3

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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
use aedb::AedbInstance;
use aedb::catalog::DdlOperation;
use aedb::catalog::schema::ColumnDef;
use aedb::catalog::types::{ColumnType, Row, Value};
use aedb::commit::tx::{
    IdempotencyKey, ReadAssertion, ReadKey, ReadSet, ReadSetEntry, TransactionEnvelope, WriteClass,
    WriteIntent,
};
use aedb::commit::validation::{
    CompareOp, KvU64MissingPolicy, KvU64OverflowPolicy, KvU64UnderflowPolicy, Mutation,
};
use aedb::config::AedbConfig;
use aedb::error::AedbError;
use aedb::offline;
use aedb::permission::{CallerContext, Permission};
use aedb::query::plan::{ConsistencyMode, Query};
use std::sync::Arc;
use tempfile::tempdir;

fn one_u256() -> [u8; 32] {
    let mut out = [0u8; 32];
    out[31] = 1;
    out
}

fn u64_be(value: u64) -> [u8; 8] {
    value.to_be_bytes()
}

fn decode_u64(bytes: &[u8]) -> u64 {
    assert_eq!(bytes.len(), 8, "u64 values must use 8 bytes");
    let mut out = [0u8; 8];
    out.copy_from_slice(bytes);
    u64::from_be_bytes(out)
}

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

    let err = db
        .commit_envelope(TransactionEnvelope {
            caller: None,
            idempotency_key: None,
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: ReadSet::default(),
            write_intent: WriteIntent {
                mutations: vec![
                    Mutation::KvSet {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"must_not_persist".to_vec(),
                        value: b"x".to_vec(),
                    },
                    Mutation::KvDecU256 {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"missing-counter".to_vec(),
                        amount_be: one_u256(),
                    },
                ],
            },
            base_seq: 0,
        })
        .await
        .expect_err("envelope should fail atomically");
    assert!(matches!(
        err,
        AedbError::Underflow | AedbError::Validation(_)
    ));

    let entry = db
        .kv_get_no_auth("p", "app", b"must_not_persist", ConsistencyMode::AtLatest)
        .await
        .expect("kv read");
    assert!(entry.is_none(), "failing envelope must not partially apply");
}

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

    let seed = db
        .commit(Mutation::KvSet {
            project_id: "p".into(),
            scope_id: "app".into(),
            key: b"guarded".to_vec(),
            value: b"v1".to_vec(),
        })
        .await
        .expect("seed");

    db.commit(Mutation::KvSet {
        project_id: "p".into(),
        scope_id: "app".into(),
        key: b"guarded".to_vec(),
        value: b"v2".to_vec(),
    })
    .await
    .expect("concurrent update");

    let err = db
        .commit_envelope(TransactionEnvelope {
            caller: None,
            idempotency_key: None,
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: ReadSet {
                points: vec![ReadSetEntry {
                    key: ReadKey::KvKey {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"guarded".to_vec(),
                    },
                    version_at_read: seed.commit_seq,
                }],
                ranges: Vec::new(),
            },
            write_intent: WriteIntent {
                mutations: vec![Mutation::KvSet {
                    project_id: "p".into(),
                    scope_id: "app".into(),
                    key: b"guarded".to_vec(),
                    value: b"stale-overwrite".to_vec(),
                }],
            },
            base_seq: db
                .snapshot_probe(ConsistencyMode::AtLatest)
                .await
                .expect("probe"),
        })
        .await
        .expect_err("stale read-set overwrite must conflict");
    assert!(
        matches!(err, AedbError::Conflict(ref msg) if msg.contains("read set conflict")),
        "expected read set conflict, got {err:?}"
    );

    let current = db
        .kv_get_no_auth("p", "app", b"guarded", ConsistencyMode::AtLatest)
        .await
        .expect("read guarded")
        .expect("guarded value");
    assert_eq!(current.value, b"v2".to_vec());
}

#[tokio::test]
async fn security_stale_table_preflight_plan_cannot_overwrite_row() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(AedbConfig::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.commit(Mutation::Ddl(DdlOperation::CreateTable {
        project_id: "p".into(),
        scope_id: "app".into(),
        table_name: "state".into(),
        owner_id: None,
        columns: vec![
            ColumnDef {
                name: "id".into(),
                col_type: ColumnType::Integer,
                nullable: false,
            },
            ColumnDef {
                name: "value".into(),
                col_type: ColumnType::Integer,
                nullable: false,
            },
        ],
        primary_key: vec!["id".into()],
        if_not_exists: false,
    }))
    .await
    .expect("create state table");
    db.commit(Mutation::Upsert {
        project_id: "p".into(),
        scope_id: "app".into(),
        table_name: "state".into(),
        primary_key: vec![Value::Integer(1)],
        row: Row::from_values(vec![Value::Integer(1), Value::Integer(10)]),
    })
    .await
    .expect("seed row");

    let plan = db
        .preflight_plan(Mutation::Upsert {
            project_id: "p".into(),
            scope_id: "app".into(),
            table_name: "state".into(),
            primary_key: vec![Value::Integer(1)],
            row: Row::from_values(vec![Value::Integer(1), Value::Integer(20)]),
        })
        .await;
    assert!(plan.valid, "preflight plan should be valid");
    assert_eq!(plan.read_set.points.len(), 1);

    db.commit(Mutation::Upsert {
        project_id: "p".into(),
        scope_id: "app".into(),
        table_name: "state".into(),
        primary_key: vec![Value::Integer(1)],
        row: Row::from_values(vec![Value::Integer(1), Value::Integer(30)]),
    })
    .await
    .expect("concurrent state transition");

    let err = db
        .commit_envelope(TransactionEnvelope {
            caller: None,
            idempotency_key: None,
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: plan.read_set,
            write_intent: plan.write_intent,
            base_seq: plan.base_seq,
        })
        .await
        .expect_err("stale table plan must conflict");
    assert!(
        matches!(err, AedbError::Conflict(ref msg) if msg.contains("read set conflict")),
        "expected read set conflict, got {err:?}"
    );

    let rows = db
        .query("p", "app", Query::select(&["*"]).from("state").limit(10))
        .await
        .expect("query state");
    assert_eq!(rows.rows.len(), 1);
    assert_eq!(rows.rows[0].values.get(1), Some(&Value::Integer(30)));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn security_parallel_asserted_state_transition_has_single_winner() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(AedbConfig::default(), dir.path()).expect("open"));
    db.create_project("p").await.expect("project");
    db.kv_set("p", "app", b"machine:1".to_vec(), b"open".to_vec())
        .await
        .expect("seed machine state");
    let base_seq = db
        .snapshot_probe(ConsistencyMode::AtLatest)
        .await
        .expect("probe");

    let mut tasks = Vec::new();
    for _ in 0..32 {
        let db = Arc::clone(&db);
        tasks.push(tokio::spawn(async move {
            db.commit_envelope(TransactionEnvelope {
                caller: None,
                idempotency_key: None,
                write_class: WriteClass::Standard,
                assertions: vec![ReadAssertion::KeyEquals {
                    project_id: "p".into(),
                    scope_id: "app".into(),
                    key: b"machine:1".to_vec(),
                    expected: b"open".to_vec(),
                }],
                read_set: ReadSet::default(),
                write_intent: WriteIntent {
                    mutations: vec![Mutation::KvSet {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"machine:1".to_vec(),
                        value: b"closed".to_vec(),
                    }],
                },
                base_seq,
            })
            .await
        }));
    }

    let mut applied = 0usize;
    let mut rejected = 0usize;
    for task in tasks {
        match task.await.expect("transition task") {
            Ok(_) => applied += 1,
            Err(AedbError::AssertionFailed { .. }) | Err(AedbError::Conflict(_)) => rejected += 1,
            Err(err) => panic!("unexpected transition error: {err:?}"),
        }
    }
    assert_eq!(applied, 1, "only one asserted transition may win");
    assert_eq!(rejected, 31, "all stale transitions must be rejected");

    let current = db
        .kv_get_no_auth("p", "app", b"machine:1", ConsistencyMode::AtLatest)
        .await
        .expect("read machine")
        .expect("machine state");
    assert_eq!(current.value, b"closed".to_vec());
}

#[tokio::test]
async fn security_multi_key_atomic_update_reverts_all_on_failure() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(AedbConfig::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.kv_set("p", "app", b"from".to_vec(), u64_be(5).to_vec())
        .await
        .expect("seed from");
    db.kv_set("p", "app", b"to".to_vec(), u64_be(7).to_vec())
        .await
        .expect("seed to");

    let err = db
        .commit_envelope(TransactionEnvelope {
            caller: None,
            idempotency_key: None,
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: ReadSet::default(),
            write_intent: WriteIntent {
                mutations: vec![
                    Mutation::KvAddU64Ex {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"to".to_vec(),
                        amount_be: u64_be(10),
                        on_missing: KvU64MissingPolicy::Reject,
                        on_overflow: KvU64OverflowPolicy::Reject,
                    },
                    Mutation::KvSubU64Ex {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"from".to_vec(),
                        amount_be: u64_be(10),
                        on_missing: KvU64MissingPolicy::Reject,
                        on_underflow: KvU64UnderflowPolicy::Reject,
                    },
                ],
            },
            base_seq: db
                .snapshot_probe(ConsistencyMode::AtLatest)
                .await
                .expect("probe"),
        })
        .await
        .expect_err("underflow must abort the whole transaction");
    assert!(matches!(err, AedbError::Underflow));

    let from = db
        .kv_get_no_auth("p", "app", b"from", ConsistencyMode::AtLatest)
        .await
        .expect("read from")
        .expect("from key");
    let to = db
        .kv_get_no_auth("p", "app", b"to", ConsistencyMode::AtLatest)
        .await
        .expect("read to")
        .expect("to key");
    assert_eq!(decode_u64(&from.value), 5);
    assert_eq!(decode_u64(&to.value), 7);
}

#[tokio::test]
async fn security_postflight_check_reverts_prior_atomic_updates() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(AedbConfig::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    db.kv_set("p", "app", b"balance".to_vec(), u64_be(5).to_vec())
        .await
        .expect("seed balance");
    db.kv_set("p", "app", b"ledger".to_vec(), u64_be(7).to_vec())
        .await
        .expect("seed ledger");

    let err = db
        .commit_envelope(TransactionEnvelope {
            caller: None,
            idempotency_key: None,
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: ReadSet::default(),
            write_intent: WriteIntent {
                mutations: vec![
                    Mutation::KvAddU64Ex {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"ledger".to_vec(),
                        amount_be: u64_be(1),
                        on_missing: KvU64MissingPolicy::Reject,
                        on_overflow: KvU64OverflowPolicy::Reject,
                    },
                    Mutation::KvSubU64Ex {
                        project_id: "p".into(),
                        scope_id: "app".into(),
                        key: b"balance".to_vec(),
                        amount_be: u64_be(5),
                        on_missing: KvU64MissingPolicy::Reject,
                        on_underflow: KvU64UnderflowPolicy::Reject,
                    },
                    Mutation::PostflightCheck {
                        assertions: vec![ReadAssertion::KeyCompare {
                            project_id: "p".into(),
                            scope_id: "app".into(),
                            key: b"balance".to_vec(),
                            op: CompareOp::Gt,
                            threshold: u64_be(0).to_vec(),
                        }],
                    },
                ],
            },
            base_seq: db
                .snapshot_probe(ConsistencyMode::AtLatest)
                .await
                .expect("probe"),
        })
        .await
        .expect_err("postflight check must abort the whole transaction");
    assert!(matches!(err, AedbError::AssertionFailed { .. }));

    let balance = db
        .kv_get_no_auth("p", "app", b"balance", ConsistencyMode::AtLatest)
        .await
        .expect("read balance")
        .expect("balance key");
    let ledger = db
        .kv_get_no_auth("p", "app", b"ledger", ConsistencyMode::AtLatest)
        .await
        .expect("read ledger")
        .expect("ledger key");
    assert_eq!(decode_u64(&balance.value), 5);
    assert_eq!(decode_u64(&ledger.value), 7);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn security_parallel_atomic_adds_do_not_lose_updates() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(AedbConfig::default(), dir.path()).expect("open"));
    db.create_project("p").await.expect("project");
    db.kv_set("p", "app", b"counter".to_vec(), u64_be(0).to_vec())
        .await
        .expect("seed counter");

    let mut tasks = Vec::new();
    for _ in 0..64 {
        let db = Arc::clone(&db);
        tasks.push(tokio::spawn(async move {
            db.commit(Mutation::KvAddU64Ex {
                project_id: "p".into(),
                scope_id: "app".into(),
                key: b"counter".to_vec(),
                amount_be: u64_be(1),
                on_missing: KvU64MissingPolicy::Reject,
                on_overflow: KvU64OverflowPolicy::Reject,
            })
            .await
        }));
    }

    for task in tasks {
        task.await
            .expect("atomic add task")
            .expect("atomic add should commit");
    }
    let counter = db
        .kv_get_no_auth("p", "app", b"counter", ConsistencyMode::AtLatest)
        .await
        .expect("read counter")
        .expect("counter key");
    assert_eq!(decode_u64(&counter.value), 64);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn security_hot_key_atomic_postflight_does_not_use_stale_precondition() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(AedbConfig::default(), dir.path()).expect("open"));
    db.create_project("p").await.expect("project");
    db.kv_set("p", "app", b"balance".to_vec(), u64_be(32).to_vec())
        .await
        .expect("seed balance");

    let mut tasks = Vec::new();
    for _ in 0..64 {
        let db = Arc::clone(&db);
        tasks.push(tokio::spawn(async move {
            db.commit_envelope(TransactionEnvelope {
                caller: None,
                idempotency_key: None,
                write_class: WriteClass::Standard,
                assertions: Vec::new(),
                read_set: ReadSet::default(),
                write_intent: WriteIntent {
                    mutations: vec![
                        Mutation::KvSubU64Ex {
                            project_id: "p".into(),
                            scope_id: "app".into(),
                            key: b"balance".to_vec(),
                            amount_be: u64_be(1),
                            on_missing: KvU64MissingPolicy::Reject,
                            on_underflow: KvU64UnderflowPolicy::NoOp,
                        },
                        Mutation::PostflightCheck {
                            assertions: vec![ReadAssertion::KeyCompare {
                                project_id: "p".into(),
                                scope_id: "app".into(),
                                key: b"balance".to_vec(),
                                op: CompareOp::Gt,
                                threshold: u64_be(0).to_vec(),
                            }],
                        },
                    ],
                },
                base_seq: db
                    .snapshot_probe(ConsistencyMode::AtLatest)
                    .await
                    .expect("probe"),
            })
            .await
        }));
    }

    let mut applied = 0usize;
    let mut rejected = 0usize;
    for task in tasks {
        match task.await.expect("hot-key debit task") {
            Ok(_) => applied += 1,
            Err(AedbError::AssertionFailed { .. }) => rejected += 1,
            Err(err) => panic!("unexpected hot-key debit error: {err:?}"),
        }
    }
    assert_eq!(applied, 31);
    assert_eq!(rejected, 33);

    let balance = db
        .kv_get_no_auth("p", "app", b"balance", ConsistencyMode::AtLatest)
        .await
        .expect("read balance")
        .expect("balance key");
    assert_eq!(decode_u64(&balance.value), 1);
}

#[tokio::test]
async fn security_idempotency_survives_restart_exactly_once() {
    let dir = tempdir().expect("temp dir");
    let config = AedbConfig::production([7u8; 32]);
    let db = AedbInstance::open(config.clone(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");

    let key = IdempotencyKey([4u8; 16]);
    let envelope = TransactionEnvelope {
        caller: None,
        idempotency_key: Some(key.clone()),
        write_class: WriteClass::Economic,
        assertions: Vec::new(),
        read_set: ReadSet::default(),
        write_intent: WriteIntent {
            mutations: vec![Mutation::KvSet {
                project_id: "p".into(),
                scope_id: "app".into(),
                key: b"idem-restart".to_vec(),
                value: b"v1".to_vec(),
            }],
        },
        base_seq: 0,
    };

    let first = db
        .commit_envelope(envelope.clone())
        .await
        .expect("first commit");
    let second = db
        .commit_envelope(envelope.clone())
        .await
        .expect("idempotent retry");
    assert_eq!(second.commit_seq, first.commit_seq);
    db.shutdown().await.expect("shutdown");
    drop(db);

    let reopened = AedbInstance::open(config, dir.path()).expect("reopen");
    let third = reopened
        .commit_envelope(envelope)
        .await
        .expect("idempotent retry after restart");
    assert_eq!(third.commit_seq, first.commit_seq);
}

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

    let key = IdempotencyKey([6u8; 16]);
    let first = TransactionEnvelope {
        caller: None,
        idempotency_key: Some(key.clone()),
        write_class: WriteClass::Standard,
        assertions: Vec::new(),
        read_set: ReadSet::default(),
        write_intent: WriteIntent {
            mutations: vec![Mutation::KvSet {
                project_id: "p".into(),
                scope_id: "app".into(),
                key: b"idem-mismatch".to_vec(),
                value: b"v1".to_vec(),
            }],
        },
        base_seq: 0,
    };
    db.commit_envelope(first).await.expect("first commit");

    let err = db
        .commit_envelope(TransactionEnvelope {
            caller: None,
            idempotency_key: Some(key),
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: ReadSet::default(),
            write_intent: WriteIntent {
                mutations: vec![Mutation::KvSet {
                    project_id: "p".into(),
                    scope_id: "app".into(),
                    key: b"idem-mismatch".to_vec(),
                    value: b"v2".to_vec(),
                }],
            },
            base_seq: 0,
        })
        .await
        .expect_err("reusing key for different payload must fail");
    assert!(matches!(err, AedbError::Validation(_)));
}

#[tokio::test]
async fn security_idempotency_is_scoped_to_caller() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open(AedbConfig::default(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    for caller_id in ["alice", "bob"] {
        db.commit(Mutation::Ddl(
            aedb::catalog::DdlOperation::GrantPermission {
                actor_id: None,
                delegable: false,
                caller_id: caller_id.into(),
                permission: Permission::KvWrite {
                    project_id: "p".into(),
                    scope_id: Some("app".into()),
                    prefix: None,
                },
            },
        ))
        .await
        .expect("grant kv write");
    }

    let key = IdempotencyKey([7u8; 16]);
    let first = TransactionEnvelope {
        caller: Some(CallerContext::new("alice")),
        idempotency_key: Some(key.clone()),
        write_class: WriteClass::Standard,
        assertions: Vec::new(),
        read_set: ReadSet::default(),
        write_intent: WriteIntent {
            mutations: vec![Mutation::KvSet {
                project_id: "p".into(),
                scope_id: "app".into(),
                key: b"idem-caller".to_vec(),
                value: b"v1".to_vec(),
            }],
        },
        base_seq: 0,
    };
    let first = db.commit_envelope(first).await.expect("first commit");

    let second = db
        .commit_envelope(TransactionEnvelope {
            caller: Some(CallerContext::new("bob")),
            idempotency_key: Some(key),
            write_class: WriteClass::Standard,
            assertions: Vec::new(),
            read_set: ReadSet::default(),
            write_intent: WriteIntent {
                mutations: vec![Mutation::KvSet {
                    project_id: "p".into(),
                    scope_id: "app".into(),
                    key: b"idem-caller".to_vec(),
                    value: b"v1".to_vec(),
                }],
            },
            base_seq: 0,
        })
        .await
        .expect("same key under different caller should apply independently");
    assert!(matches!(
        first.idempotency,
        aedb::commit::executor::IdempotencyOutcome::Applied
    ));
    assert!(matches!(
        second.idempotency,
        aedb::commit::executor::IdempotencyOutcome::Applied
    ));
    assert_ne!(first.commit_seq, second.commit_seq);
}

#[tokio::test]
async fn security_replay_is_deterministic_via_snapshot_parity() {
    let dir = tempdir().expect("temp dir");
    let dump_a = tempdir().expect("dump a");
    let dump_b = tempdir().expect("dump b");
    let dump_a_file = dump_a.path().join("state-a.aedbdump");
    let dump_b_file = dump_b.path().join("state-b.aedbdump");
    let config = AedbConfig::production([8u8; 32]);

    let db = AedbInstance::open(config.clone(), dir.path()).expect("open");
    db.create_project("p").await.expect("project");
    for i in 0..500u64 {
        db.commit(Mutation::KvSet {
            project_id: "p".into(),
            scope_id: "app".into(),
            key: format!("replay:{i}").into_bytes(),
            value: i.to_be_bytes().to_vec(),
        })
        .await
        .expect("commit");
    }
    db.shutdown().await.expect("shutdown");

    let report_a =
        offline::export_snapshot_dump(dir.path(), &config, &dump_a_file).expect("export a");
    let report_b =
        offline::export_snapshot_dump(dir.path(), &config, &dump_b_file).expect("export b");
    assert_eq!(report_a.current_seq, report_b.current_seq);
    assert_eq!(
        report_a.parity_checksum_hex, report_b.parity_checksum_hex,
        "replay parity must be deterministic"
    );
}

#[tokio::test]
async fn security_secure_mode_enforces_authenticated_commit_calls() {
    let dir = tempdir().expect("temp dir");
    let db = AedbInstance::open_secure(AedbConfig::production([9u8; 32]), dir.path())
        .expect("open secure");

    let err = db
        .commit(Mutation::Ddl(aedb::catalog::DdlOperation::CreateProject {
            owner_id: None,
            if_not_exists: true,
            project_id: "p".into(),
        }))
        .await
        .expect_err("anonymous commit should be rejected in secure mode");
    assert!(matches!(err, AedbError::PermissionDenied(_)));
}