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
use aedb::AedbInstance;
use aedb::catalog::DdlOperation;
use aedb::catalog::schema::ColumnDef;
use aedb::catalog::types::{ColumnType, Row, Value};
use aedb::commit::tx::{ReadAssertion, TransactionEnvelope, WriteClass, WriteIntent};
use aedb::commit::validation::Mutation;
use aedb::config::{AedbConfig, DurabilityMode, RecoveryMode};
use aedb::error::AedbError;
use aedb::query::plan::{ConsistencyMode, Expr, Query};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tempfile::tempdir;
use tokio::task::JoinSet;

fn u256_be(value: u64) -> [u8; 32] {
    let mut bytes = [0u8; 32];
    bytes[24..].copy_from_slice(&value.to_be_bytes());
    bytes
}

fn u256_from_be(bytes: &[u8; 32]) -> u64 {
    let mut out = [0u8; 8];
    out.copy_from_slice(&bytes[24..]);
    u64::from_be_bytes(out)
}

fn contention_config() -> AedbConfig {
    AedbConfig {
        durability_mode: DurabilityMode::Batch,
        batch_interval_ms: 60_000,
        batch_max_bytes: usize::MAX,
        recovery_mode: RecoveryMode::Permissive,
        hash_chain_required: false,
        ..AedbConfig::default()
    }
}

/// Test Case 1: Single-Row Thundering Herd (Hot Account)
///
/// Stress-tests lock contention on a single hot partition.
/// Critical for validating partition locking performance.
#[tokio::test]
async fn test_single_row_thundering_herd() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(contention_config(), dir.path()).expect("open db"));
    db.create_project("casino").await.expect("create project");

    db.commit(Mutation::Ddl(DdlOperation::CreateTable {
        project_id: "casino".into(),
        scope_id: "app".into(),
        table_name: "hot_accounts".into(),
        owner_id: None,
        if_not_exists: false,
        columns: vec![
            ColumnDef {
                name: "id".into(),
                col_type: ColumnType::Integer,
                nullable: false,
            },
            ColumnDef {
                name: "balance".into(),
                col_type: ColumnType::U256,
                nullable: false,
            },
        ],
        primary_key: vec!["id".into()],
    }))
    .await
    .expect("create table");

    // Setup: Single hot account
    db.commit(Mutation::Upsert {
        project_id: "casino".into(),
        scope_id: "app".into(),
        table_name: "hot_accounts".into(),
        primary_key: vec![Value::Integer(1)],
        row: Row::from_values(vec![Value::Integer(1), Value::U256(u256_be(1_000_000))]),
    })
    .await
    .expect("seed hot account");

    // Action: 100 concurrent CAS operations on same row
    let start = Instant::now();
    let mut tasks = JoinSet::new();

    for i in 0..100 {
        let db = Arc::clone(&db);
        tasks.spawn(async move {
            let base_seq = db
                .snapshot_probe(ConsistencyMode::AtLatest)
                .await
                .expect("probe");
            let result = db
                .commit_envelope(TransactionEnvelope {
                    caller: None,
                    idempotency_key: None,
                    write_class: WriteClass::Standard,
                    assertions: vec![ReadAssertion::RowColumnCompare {
                        project_id: "casino".into(),
                        scope_id: "app".into(),
                        table_name: "hot_accounts".into(),
                        primary_key: vec![Value::Integer(1)],
                        column: "balance".into(),
                        op: aedb::commit::validation::CompareOp::Eq,
                        threshold: Value::U256(u256_be(1_000_000 + i)),
                    }],
                    read_set: Default::default(),
                    write_intent: WriteIntent {
                        mutations: vec![Mutation::Upsert {
                            project_id: "casino".into(),
                            scope_id: "app".into(),
                            table_name: "hot_accounts".into(),
                            primary_key: vec![Value::Integer(1)],
                            row: Row::from_values(vec![
                                Value::Integer(1),
                                Value::U256(u256_be(1_000_000 + i + 1)),
                            ]),
                        }],
                    },
                    base_seq,
                })
                .await;
            (i, result)
        });
    }

    let mut success_count = 0;
    let mut conflict_count = 0;
    let mut timeout_count = 0;

    while let Some(result) = tasks.join_next().await {
        let (_op_id, cas_result) = result.expect("task panicked");
        match cas_result {
            Ok(_) => success_count += 1,
            Err(AedbError::AssertionFailed { .. }) => conflict_count += 1,
            Err(AedbError::Timeout) => timeout_count += 1,
            Err(e) => panic!("unexpected error: {:?}", e),
        }
    }

    let elapsed = start.elapsed();
    let ops_per_sec = 100.0 / elapsed.as_secs_f64();

    println!(
        "Hot account contention: success={}, conflict={}, timeout={}, elapsed={:?}, throughput={:.0} ops/sec",
        success_count, conflict_count, timeout_count, elapsed, ops_per_sec
    );

    // Verify: All operations completed
    assert_eq!(
        success_count + conflict_count + timeout_count,
        100,
        "all operations should complete"
    );

    // Verify: Reasonable timeout rate (<10%)
    assert!(
        timeout_count < 10,
        "timeout rate too high: {} / 100",
        timeout_count
    );

    // Verify: Reasonable throughput (>50 ops/sec for sequential CAS)
    // Note: CAS operations with assertions are sequential, so throughput is lower
    assert!(
        ops_per_sec > 50.0,
        "throughput too low: {:.0} ops/sec",
        ops_per_sec
    );

    // Verify: At least some operations succeeded
    assert!(success_count > 0, "at least one CAS should succeed");
}

/// Test Case 2: Cross-Partition Deadlock Prevention
///
/// Validates that coordinator lock ordering prevents deadlocks.
/// Critical for multi-partition transaction safety.
#[tokio::test]
async fn test_cross_partition_deadlock_prevention() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(contention_config(), dir.path()).expect("open db"));
    db.create_project("casino").await.expect("create project");

    // Setup: Create 4 tables in same scope (to test partition locking)
    for i in 0..4 {
        let table_name = format!("accounts_{}", i);
        db.commit(Mutation::Ddl(DdlOperation::CreateTable {
            project_id: "casino".into(),
            scope_id: "app".into(),
            table_name: table_name.clone(),
            owner_id: None,
            if_not_exists: false,
            columns: vec![
                ColumnDef {
                    name: "id".into(),
                    col_type: ColumnType::Integer,
                    nullable: false,
                },
                ColumnDef {
                    name: "balance".into(),
                    col_type: ColumnType::U256,
                    nullable: false,
                },
            ],
            primary_key: vec!["id".into()],
        }))
        .await
        .expect("create table");

        db.commit(Mutation::Upsert {
            project_id: "casino".into(),
            scope_id: "app".into(),
            table_name: table_name.clone(),
            primary_key: vec![Value::Integer(1)],
            row: Row::from_values(vec![Value::Integer(1), Value::U256(u256_be(1000))]),
        })
        .await
        .expect("seed account");
    }

    // Action: 50 concurrent transactions accessing different tables
    // Tests partition lock coordination
    let start = Instant::now();
    let mut tasks = JoinSet::new();

    for i in 0..50i64 {
        let db = Arc::clone(&db);
        tasks.spawn(async move {
            // Access table based on i
            let table1 = format!("accounts_{}", i % 4);
            let table2 = format!("accounts_{}", (i + 2) % 4);

            if table1 == table2 {
                // Same table - simple operation
                db.table_inc_u256(
                    "casino",
                    "app",
                    &table1,
                    vec![Value::Integer(1)],
                    "balance",
                    u256_be(10),
                )
                .await
            } else {
                // Different tables - potential coordination scenario
                db.table_inc_u256(
                    "casino",
                    "app",
                    &table1,
                    vec![Value::Integer(1)],
                    "balance",
                    u256_be(5),
                )
                .await?;

                db.table_inc_u256(
                    "casino",
                    "app",
                    &table2,
                    vec![Value::Integer(1)],
                    "balance",
                    u256_be(5),
                )
                .await
            }
        });
    }

    let mut success_count = 0;
    let mut error_count = 0;

    while let Some(result) = tasks.join_next().await {
        match result.expect("task panicked") {
            Ok(_) => success_count += 1,
            Err(_) => error_count += 1,
        }
    }

    let elapsed = start.elapsed();

    println!(
        "Cross-partition test: success={}, errors={}, elapsed={:?}",
        success_count, error_count, elapsed
    );

    // Verify: All transactions completed within reasonable time (no deadlocks)
    assert!(
        elapsed < Duration::from_secs(5),
        "transactions took too long (possible deadlock): {:?}",
        elapsed
    );

    // Verify: Most operations succeeded
    assert!(
        success_count > 40,
        "too many failures: {} / 50",
        error_count
    );
}

/// Test Case 3: Read-Set Conflict Under Heavy Write Load
///
/// Validates read-set validation under concurrent writes.
/// Critical for snapshot isolation guarantees.
#[tokio::test]
async fn test_read_set_conflict_under_write_load() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(contention_config(), dir.path()).expect("open db"));
    db.create_project("casino").await.expect("create project");

    db.commit(Mutation::Ddl(DdlOperation::CreateTable {
        project_id: "casino".into(),
        scope_id: "app".into(),
        table_name: "accounts".into(),
        owner_id: None,
        if_not_exists: false,
        columns: vec![
            ColumnDef {
                name: "id".into(),
                col_type: ColumnType::Integer,
                nullable: false,
            },
            ColumnDef {
                name: "balance".into(),
                col_type: ColumnType::U256,
                nullable: false,
            },
        ],
        primary_key: vec!["id".into()],
    }))
    .await
    .expect("create table");

    // Setup: 10 accounts
    for i in 0..10 {
        db.commit(Mutation::Upsert {
            project_id: "casino".into(),
            scope_id: "app".into(),
            table_name: "accounts".into(),
            primary_key: vec![Value::Integer(i)],
            row: Row::from_values(vec![Value::Integer(i), Value::U256(u256_be(1000))]),
        })
        .await
        .expect("seed account");
    }

    // Action: 10 reader threads + 10 writer threads
    let mut tasks = JoinSet::new();

    // Spawn writers
    for i in 0..10 {
        let db = Arc::clone(&db);
        tasks.spawn(async move {
            for _ in 0..5 {
                let _ = db
                    .table_inc_u256(
                        "casino",
                        "app",
                        "accounts",
                        vec![Value::Integer(i % 5)],
                        "balance",
                        u256_be(100),
                    )
                    .await;
                tokio::time::sleep(Duration::from_micros(100)).await;
            }
            ("writer", Ok::<(), AedbError>(()))
        });
    }

    // Spawn readers
    for i in 0..10 {
        let db = Arc::clone(&db);
        tasks.spawn(async move {
            for _ in 0..5 {
                let _ = db
                    .query_with_options(
                        "casino",
                        "app",
                        Query::select(&["balance"])
                            .from("accounts")
                            .where_(Expr::Eq("id".into(), Value::Integer(i % 5))),
                        aedb::query::plan::QueryOptions {
                            consistency: ConsistencyMode::AtLatest,
                            ..Default::default()
                        },
                    )
                    .await;
                tokio::time::sleep(Duration::from_micros(50)).await;
            }
            ("reader", Ok(()))
        });
    }

    let mut writer_count = 0;
    let mut reader_count = 0;

    while let Some(result) = tasks.join_next().await {
        let (task_type, _task_result) = result.expect("task panicked");
        match task_type {
            "reader" => {
                reader_count += 1;
            }
            "writer" => {
                writer_count += 1;
            }
            _ => {}
        }
    }

    println!(
        "Read-set conflict test: {} writers, {} readers completed",
        writer_count, reader_count
    );

    // Verify: All tasks completed
    assert_eq!(writer_count, 10, "all writers should complete");
    assert_eq!(reader_count, 10, "all readers should complete");
}

/// Test Case 4: High Concurrency Stress Test
///
/// Validates behavior under extreme concurrent load.
/// Critical for production readiness assessment.
#[tokio::test]
async fn test_high_concurrency_stress() {
    let dir = tempdir().expect("temp dir");
    let db = Arc::new(AedbInstance::open(contention_config(), dir.path()).expect("open db"));
    db.create_project("casino").await.expect("create project");

    db.commit(Mutation::Ddl(DdlOperation::CreateTable {
        project_id: "casino".into(),
        scope_id: "app".into(),
        table_name: "accounts".into(),
        owner_id: None,
        if_not_exists: false,
        columns: vec![
            ColumnDef {
                name: "id".into(),
                col_type: ColumnType::Integer,
                nullable: false,
            },
            ColumnDef {
                name: "balance".into(),
                col_type: ColumnType::U256,
                nullable: false,
            },
        ],
        primary_key: vec!["id".into()],
    }))
    .await
    .expect("create table");

    // Setup: 20 accounts
    for i in 0..20 {
        db.commit(Mutation::Upsert {
            project_id: "casino".into(),
            scope_id: "app".into(),
            table_name: "accounts".into(),
            primary_key: vec![Value::Integer(i)],
            row: Row::from_values(vec![Value::Integer(i), Value::U256(u256_be(10000))]),
        })
        .await
        .expect("seed account");
    }

    // Action: 200 concurrent operations
    let start = Instant::now();
    let mut tasks = JoinSet::new();

    for i in 0..200i64 {
        let db = Arc::clone(&db);
        tasks.spawn(async move {
            tokio::time::sleep(Duration::from_micros(((i % 10) * 50) as u64)).await;
            db.table_inc_u256(
                "casino",
                "app",
                "accounts",
                vec![Value::Integer(i % 20)],
                "balance",
                u256_be(10),
            )
            .await
        });
    }

    let mut success_count = 0;
    let mut error_count = 0;

    while let Some(result) = tasks.join_next().await {
        match result.expect("task panicked") {
            Ok(_) => success_count += 1,
            Err(_) => error_count += 1,
        }
    }

    let elapsed = start.elapsed();
    let throughput = success_count as f64 / elapsed.as_secs_f64();

    println!(
        "High concurrency stress: success={}, errors={}, elapsed={:?}, throughput={:.0} ops/sec",
        success_count, error_count, elapsed, throughput
    );

    // Verify: Most operations succeeded
    assert!(
        success_count > 150,
        "too many failures: {} / 200",
        error_count
    );

    // Verify: Reasonable throughput (>500 ops/sec)
    assert!(
        throughput > 500.0,
        "throughput too low: {:.0} ops/sec",
        throughput
    );

    // Verify: Balance consistency
    let total_expected = 10000 * 20 + (success_count * 10);
    let mut total_actual = 0;

    for i in 0..20 {
        let row = db
            .query_with_options(
                "casino",
                "app",
                Query::select(&["balance"])
                    .from("accounts")
                    .where_(Expr::Eq("id".into(), Value::Integer(i))),
                aedb::query::plan::QueryOptions {
                    consistency: ConsistencyMode::AtLatest,
                    ..Default::default()
                },
            )
            .await
            .expect("query balance")
            .rows
            .into_iter()
            .next()
            .expect("account exists");

        let Value::U256(balance_be) = row.values[0] else {
            panic!("expected U256 balance");
        };
        total_actual += u256_from_be(&balance_be);
    }

    assert_eq!(
        total_actual, total_expected,
        "balance conservation violated! expected={}, actual={}",
        total_expected, total_actual
    );
}