tonbo 0.4.0-a1

Embedded database for serverless and edge runtimes, storing data as Parquet on S3
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
use std::{fs, path::PathBuf, sync::Arc, time::Duration};

use arrow_array::{Int32Array, RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use fusio::{DynFs, disk::LocalFs, executor::tokio::TokioExecutor, path::Path as FusioPath};

use crate::{
    db::{
        BatchesThreshold, DB, DbInner, Expr, NeverSeal, WalConfig as BuilderWalConfig,
        WalSyncPolicy,
    },
    tests_internal::common::config_with_pk,
    wal::{WalExt, state::FsWalStateStore},
};

fn workspace_temp_dir(prefix: &str) -> PathBuf {
    let base = std::env::current_dir().expect("cwd");
    let dir = base.join("target").join("tmp").join(format!(
        "{prefix}-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("time")
            .as_nanos()
    ));
    fs::create_dir_all(&dir).expect("create workspace temp dir");
    dir
}

fn wal_cfg_with_backend(
    wal_dir: &PathBuf,
    with_state_store: bool,
) -> Result<BuilderWalConfig, Box<dyn std::error::Error>> {
    fs::create_dir_all(wal_dir)?;
    let wal_path = FusioPath::from_filesystem_path(wal_dir)?;
    let wal_fs = Arc::new(LocalFs {});
    let wal_backend: Arc<dyn DynFs> = wal_fs.clone();
    let wal_state = with_state_store.then(|| Arc::new(FsWalStateStore::new(wal_fs)));

    let mut cfg = BuilderWalConfig::default()
        .wal_dir(wal_path)
        .segment_backend(wal_backend)
        .segment_max_bytes(512)
        .flush_interval(Duration::from_millis(1))
        .sync_policy(WalSyncPolicy::Disabled);
    if let Some(state) = wal_state {
        cfg = cfg.state_store(Some(state));
    }
    Ok(cfg)
}

async fn rows_from_db(
    db: &DB<LocalFs, TokioExecutor>,
) -> Result<Vec<(String, i32)>, Box<dyn std::error::Error>> {
    let predicate = Expr::is_not_null("id");
    let batches = db.scan().filter(predicate).collect().await?;
    let mut rows: Vec<(String, i32)> = batches
        .into_iter()
        .flat_map(|batch| {
            let ids = batch
                .column(0)
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("id col");
            let vals = batch
                .column(1)
                .as_any()
                .downcast_ref::<Int32Array>()
                .expect("value col");
            ids.iter()
                .zip(vals.iter())
                .filter_map(|(id, v)| Some((id?.to_string(), v?)))
                .collect::<Vec<_>>()
        })
        .collect();
    rows.sort();
    Ok(rows)
}

async fn rows_from_db_inner(
    db: &DbInner<LocalFs, TokioExecutor>,
) -> Result<Vec<(String, i32)>, Box<dyn std::error::Error>> {
    let predicate = Expr::is_not_null("id");
    let batches = db.scan().filter(predicate).collect().await?;
    let mut rows: Vec<(String, i32)> = batches
        .into_iter()
        .flat_map(|batch| {
            let ids = batch
                .column(0)
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("id col");
            let vals = batch
                .column(1)
                .as_any()
                .downcast_ref::<Int32Array>()
                .expect("value col");
            ids.iter()
                .zip(vals.iter())
                .filter_map(|(id, v)| Some((id?.to_string(), v?)))
                .collect::<Vec<_>>()
        })
        .collect();
    rows.sort();
    Ok(rows)
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durability_restart_via_public_compaction_path() -> Result<(), Box<dyn std::error::Error>> {
    let temp_root = workspace_temp_dir("durability-public");
    let root_str = temp_root.to_string_lossy().into_owned();

    let build_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let schema = build_config.schema();
    let executor = Arc::new(TokioExecutor::default());

    // WAL config with local fs backend and state store.
    let wal_dir = temp_root.join("wal");
    let wal_cfg = wal_cfg_with_backend(&wal_dir, true)?;

    // Use builder with minor compaction configured (threshold=1, level=0, start_id=1).
    // SST files will be written to <root>/sst/ automatically.
    let mut db: DbInner<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(build_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg.clone())
            .with_minor_compaction(1, 0)
            .open_with_executor(Arc::clone(&executor))
            .await?
            .into_inner();
    db.set_seal_policy(Arc::new(BatchesThreshold { batches: 1 }));

    let expected_rows = vec![
        ("alpha".to_string(), 10),
        ("bravo".to_string(), 20),
        ("charlie".to_string(), 30),
    ];
    for (id, value) in &expected_rows {
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![id.clone()])) as _,
                Arc::new(Int32Array::from(vec![*value])) as _,
            ],
        )?;
        // Ingest triggers seal (due to BatchesThreshold) and then minor compaction flushes.
        db.ingest(batch).await?;
    }

    drop(db);

    // Restart and rely on manifest+WAL replay only through public builder.
    let recover_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let recovered: DB<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(recover_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg)
            .open_with_executor(Arc::clone(&executor))
            .await?;

    let rows = rows_from_db(&recovered).await?;
    assert_eq!(rows, expected_rows);

    recovered.into_inner().disable_wal().await?;
    if let Err(err) = fs::remove_dir_all(&temp_root) {
        eprintln!("failed to clean test dir {:?}: {err}", &temp_root);
    }

    Ok(())
}

/// End-user path: ingest only (no flush), restart, and recover purely from WAL replay.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durability_restart_via_wal_only() -> Result<(), Box<dyn std::error::Error>> {
    let temp_root = workspace_temp_dir("durability-wal-only");
    let root_str = temp_root.to_string_lossy().into_owned();

    let build_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let schema = build_config.schema();
    let executor = Arc::new(TokioExecutor::default());

    // WAL config with local fs backend and state store.
    let wal_dir = temp_root.join("wal");
    let wal_cfg = wal_cfg_with_backend(&wal_dir, true)?;

    let mut db: DbInner<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(build_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg.clone())
            .disable_minor_compaction()
            .open_with_executor(Arc::clone(&executor))
            .await?
            .into_inner();
    db.set_seal_policy(Arc::new(BatchesThreshold { batches: 1 }));

    let expected_rows = vec![("delta".to_string(), 100), ("echo".to_string(), 200)];
    for (id, value) in &expected_rows {
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![id.clone()])) as _,
                Arc::new(Int32Array::from(vec![*value])) as _,
            ],
        )?;
        db.ingest(batch).await?;
    }

    // Do not flush; rely solely on WAL replay.
    drop(db);

    let recover_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let recovered: DB<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(recover_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg)
            .open_with_executor(Arc::clone(&executor))
            .await?;

    let rows = rows_from_db(&recovered).await?;
    assert_eq!(rows, expected_rows);

    recovered.into_inner().disable_wal().await?;
    if let Err(err) = fs::remove_dir_all(&temp_root) {
        eprintln!("failed to clean test dir {:?}: {err}", &temp_root);
    }

    Ok(())
}

/// Mixed immutable (flushed) + mutable (wal-only) recovery through public APIs.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durability_restart_mixed_sst_and_wal() -> Result<(), Box<dyn std::error::Error>> {
    let temp_root = workspace_temp_dir("durability-mixed");
    let root_str = temp_root.to_string_lossy().into_owned();

    let build_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let schema = build_config.schema();
    let executor = Arc::new(TokioExecutor::default());

    // WAL config with state store.
    let wal_dir = temp_root.join("wal");
    let wal_cfg = wal_cfg_with_backend(&wal_dir, true)?;

    // Use builder with minor compaction configured (threshold=1, level=0, start_id=10).
    let mut db: DbInner<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(build_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg.clone())
            .with_minor_compaction(1, 0)
            .open_with_executor(Arc::clone(&executor))
            .await?
            .into_inner();
    db.set_seal_policy(Arc::new(BatchesThreshold { batches: 1 }));

    // First batch: will be sealed + flushed automatically by minor compaction.
    let flushed_rows = vec![("f1".to_string(), 1), ("f2".to_string(), 2)];
    for (id, value) in &flushed_rows {
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![id.clone()])) as _,
                Arc::new(Int32Array::from(vec![*value])) as _,
            ],
        )?;
        db.ingest(batch).await?;
    }

    // Second batch: stays mutable/WAL only (disable sealing).
    let wal_only_rows = vec![("w1".to_string(), 100), ("w2".to_string(), 200)];
    db.set_seal_policy(Arc::new(NeverSeal));
    for (id, value) in &wal_only_rows {
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![id.clone()])) as _,
                Arc::new(Int32Array::from(vec![*value])) as _,
            ],
        )?;
        db.ingest(batch).await?;
    }

    drop(db);

    let recover_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let recovered: DB<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(recover_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg)
            .open_with_executor(Arc::clone(&executor))
            .await?;

    let mut rows = rows_from_db(&recovered).await?;
    rows.sort();
    let mut expected = flushed_rows;
    expected.extend_from_slice(&wal_only_rows);
    expected.sort();
    assert_eq!(rows, expected);

    Ok(())
}

/// Multiple restarts remain idempotent and keep commit clock monotonic.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durability_multi_restart_idempotent() -> Result<(), Box<dyn std::error::Error>> {
    let temp_root = workspace_temp_dir("durability-multi");
    let root_str = temp_root.to_string_lossy().into_owned();
    let wal_dir = temp_root.join("wal");
    let wal_cfg = wal_cfg_with_backend(&wal_dir, true)?;
    let build_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let schema = build_config.schema();
    let executor = Arc::new(TokioExecutor::default());

    async fn reopen_once(
        root: &str,
        wal_cfg: &BuilderWalConfig,
        executor: Arc<TokioExecutor>,
        schema: Arc<Schema>,
        rows: Vec<(String, i32)>,
    ) -> Result<DbInner<LocalFs, TokioExecutor>, Box<dyn std::error::Error>> {
        let reopen_config = config_with_pk(
            vec![
                Field::new("id", DataType::Utf8, false),
                Field::new("value", DataType::Int32, false),
            ],
            &["id"],
        );
        let mut db: DbInner<LocalFs, TokioExecutor> =
            DB::<LocalFs, TokioExecutor>::builder(reopen_config)
                .on_disk(root)?
                .wal_config(wal_cfg.clone())
                .open_with_executor(Arc::clone(&executor))
                .await?
                .into_inner();
        db.set_seal_policy(Arc::new(NeverSeal));
        for (id, value) in rows {
            let batch = RecordBatch::try_new(
                schema.clone(),
                vec![
                    Arc::new(StringArray::from(vec![id.clone()])) as _,
                    Arc::new(Int32Array::from(vec![value])) as _,
                ],
            )?;
            db.ingest(batch).await?;
        }
        Ok(db)
    }

    let db = reopen_once(
        &root_str,
        &wal_cfg,
        Arc::clone(&executor),
        Arc::clone(&schema),
        vec![("a".into(), 1), ("b".into(), 2)],
    )
    .await?;
    drop(db);

    let db = reopen_once(
        &root_str,
        &wal_cfg,
        Arc::clone(&executor),
        Arc::clone(&schema),
        vec![("c".into(), 3)],
    )
    .await?;
    drop(db);

    let db = reopen_once(
        &root_str,
        &wal_cfg,
        Arc::clone(&executor),
        Arc::clone(&schema),
        vec![("d".into(), 4)],
    )
    .await?;

    let mut rows = rows_from_db_inner(&db).await?;
    rows.sort();
    assert_eq!(
        rows,
        vec![
            ("a".to_string(), 1),
            ("b".to_string(), 2),
            ("c".to_string(), 3),
            ("d".to_string(), 4)
        ]
    );

    Ok(())
}

/// WAL-only restart still works without a WAL state store; replay advances commit clock.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn durability_wal_only_no_state_store() -> Result<(), Box<dyn std::error::Error>> {
    let temp_root = workspace_temp_dir("durability-wal-no-state");
    let root_str = temp_root.to_string_lossy().into_owned();
    let build_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let schema = build_config.schema();
    let executor = Arc::new(TokioExecutor::default());

    let wal_dir = temp_root.join("wal");
    let wal_cfg = wal_cfg_with_backend(&wal_dir, false)?;

    let mut db: DbInner<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(build_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg.clone())
            .open_with_executor(Arc::clone(&executor))
            .await?
            .into_inner();
    db.set_seal_policy(Arc::new(NeverSeal));

    let expected_rows = vec![("ns1".to_string(), 7), ("ns2".to_string(), 8)];
    for (id, value) in &expected_rows {
        let batch = RecordBatch::try_new(
            schema.clone(),
            vec![
                Arc::new(StringArray::from(vec![id.clone()])) as _,
                Arc::new(Int32Array::from(vec![*value])) as _,
            ],
        )?;
        db.ingest(batch).await?;
    }
    drop(db);

    let recover_config = config_with_pk(
        vec![
            Field::new("id", DataType::Utf8, false),
            Field::new("value", DataType::Int32, false),
        ],
        &["id"],
    );
    let recovered: DB<LocalFs, TokioExecutor> =
        DB::<LocalFs, TokioExecutor>::builder(recover_config)
            .on_disk(root_str.clone())?
            .wal_config(wal_cfg)
            .open_with_executor(Arc::clone(&executor))
            .await?;

    let mut rows = rows_from_db(&recovered).await?;
    rows.sort();
    assert_eq!(rows, expected_rows);

    Ok(())
}