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
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
use std::{fs, sync::Arc, time::Duration};

use arrow_array::{RecordBatch, StringArray};
use arrow_schema::{DataType, Field, Schema};
use fusio::{
    DynFs,
    executor::{Executor, tokio::TokioExecutor},
    fs::FsCas,
    mem::fs::InMemoryFs,
    path::Path,
};
use futures::{
    StreamExt, TryStreamExt,
    channel::{mpsc, oneshot as futures_oneshot},
};
use tokio::sync::{Mutex, oneshot};
use typed_arrow_dyn::{DynCell, DynRow};

use super::common::workspace_temp_dir;
use crate::{
    db::{DB, DbInner, Expr},
    inmem::policy::BatchesThreshold,
    mode::DynModeConfig,
    ondisk::sstable::{SsTableConfig, SsTableDescriptor, SsTableId},
    schema::SchemaBuilder,
    test::build_batch,
    wal::{
        WalAck, WalCommand, WalConfig as RuntimeWalConfig, WalExt, WalHandle, WalResult,
        WalSnapshot, WalSyncPolicy, frame, metrics::WalMetrics, state::FsWalStateStore, writer,
    },
};

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn ingest_waits_for_wal_durable_ack() {
    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("v", DataType::Int32, false),
    ]));
    let extractor = crate::extractor::projection_for_field(schema.clone(), 0).expect("extractor");
    let config = DynModeConfig::new(schema.clone(), extractor).expect("config");

    let executor = Arc::new(TokioExecutor::default());
    let (sender, mut receiver) = mpsc::channel(1);
    let queue_depth = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let ack_slot = Arc::new(Mutex::new(None));
    let (ack_ready_tx, ack_ready_rx) = oneshot::channel();
    let (release_ack_tx, release_ack_rx) = oneshot::channel();

    let ack_slot_clone = Arc::clone(&ack_slot);
    let join = executor.spawn(async move {
        let mut release_ack_rx = Some(release_ack_rx);
        while let Some(msg) = receiver.next().await {
            match msg {
                writer::WriterMsg::Enqueue {
                    command, ack_tx, ..
                } => match command {
                    WalCommand::TxnAppend { .. } => {
                        let ack = WalAck {
                            first_seq: frame::INITIAL_FRAME_SEQ,
                            last_seq: frame::INITIAL_FRAME_SEQ,
                            bytes_flushed: 0,
                            elapsed: Duration::from_millis(0),
                        };
                        let _ = ack_tx.send(Ok(ack));
                    }
                    WalCommand::TxnCommit { .. } => {
                        {
                            let mut slot = ack_slot_clone.lock().await;
                            *slot = Some(ack_tx);
                        }
                        let _ = ack_ready_tx.send(());
                        if let Some(rx) = release_ack_rx.take() {
                            let _ = rx.await;
                        }
                        let ack = WalAck {
                            first_seq: frame::INITIAL_FRAME_SEQ + 1,
                            last_seq: frame::INITIAL_FRAME_SEQ + 1,
                            bytes_flushed: 0,
                            elapsed: Duration::from_millis(0),
                        };
                        let mut slot = ack_slot_clone.lock().await;
                        if let Some(sender) = slot.take() {
                            let _ = sender.send(Ok(ack));
                        }
                        break;
                    }
                    _ => {
                        let ack = WalAck {
                            first_seq: frame::INITIAL_FRAME_SEQ,
                            last_seq: frame::INITIAL_FRAME_SEQ,
                            bytes_flushed: 0,
                            elapsed: Duration::from_millis(0),
                        };
                        let _ = ack_tx.send(Ok(ack));
                    }
                },
                writer::WriterMsg::Rotate { ack_tx } => {
                    let _ = ack_tx.send(Ok(()));
                }
                writer::WriterMsg::Snapshot { ack_tx } => {
                    let snapshot = WalSnapshot {
                        sealed_segments: Vec::new(),
                        active_segment: None,
                    };
                    let _ = ack_tx.send(Ok(snapshot));
                }
            }
        }
        Ok(())
    });

    let rows = vec![DynRow(vec![
        Some(DynCell::Str("k".into())),
        Some(DynCell::I32(1)),
    ])];
    let batch: RecordBatch = build_batch(schema.clone(), rows).expect("batch");

    let mut db: DbInner<InMemoryFs, TokioExecutor> = DB::new(config, Arc::clone(&executor))
        .await
        .expect("db")
        .into_inner();
    let metrics = Arc::new(TokioExecutor::rw_lock(WalMetrics::default()));
    let handle =
        WalHandle::test_from_parts(sender, queue_depth, join, frame::INITIAL_FRAME_SEQ, metrics);
    db.set_wal_handle(Some(handle));

    let mut ingest_future = Box::pin(db.ingest(batch));
    tokio::select! {
        _ = ack_ready_rx => {}
        res = &mut ingest_future => panic!("ingest finished early: {:?}", res),
    }

    release_ack_tx.send(()).expect("release ack");
    ingest_future.await.expect("ingest after ack");

    let pred = Expr::is_not_null("id");
    let snapshot = db.begin_snapshot().await.expect("snapshot");
    let plan = snapshot
        .plan_scan(&db, &pred, None, None)
        .await
        .expect("plan");
    let stream = db.execute_scan(plan).await.expect("execute");
    let rows: Vec<_> = stream
        .try_collect::<Vec<_>>()
        .await
        .expect("collect")
        .into_iter()
        .flat_map(|batch| {
            batch
                .column(0)
                .as_any()
                .downcast_ref::<StringArray>()
                .expect("id col")
                .iter()
                .flatten()
                .map(|s| s.to_string())
                .collect::<Vec<_>>()
        })
        .collect();
    assert_eq!(rows, vec!["k".to_string()]);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn wal_live_frame_floor_tracks_multi_frame_append() {
    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("v", DataType::Int32, false),
    ]));
    let extractor = crate::extractor::projection_for_field(schema.clone(), 0).expect("extractor");
    let config = DynModeConfig::new(schema.clone(), extractor).expect("config");

    let executor = Arc::new(TokioExecutor::default());
    let (sender, mut receiver) = mpsc::channel(4);
    let queue_depth = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let join = executor.spawn(async move {
        let mut next_seq = frame::INITIAL_FRAME_SEQ;
        while let Some(msg) = receiver.next().await {
            match msg {
                writer::WriterMsg::Enqueue {
                    command, ack_tx, ..
                } => {
                    let (first_seq, last_seq, advance) = match command {
                        WalCommand::TxnAppend { .. } => (next_seq, next_seq.saturating_add(1), 2),
                        WalCommand::TxnCommit { .. } => (next_seq, next_seq, 1),
                        _ => (next_seq, next_seq, 1),
                    };
                    next_seq = next_seq.saturating_add(advance);
                    let ack = WalAck {
                        first_seq,
                        last_seq,
                        bytes_flushed: 0,
                        elapsed: Duration::from_millis(0),
                    };
                    let _ = ack_tx.send(Ok(ack));
                }
                writer::WriterMsg::Rotate { ack_tx } => {
                    let _ = ack_tx.send(Ok(()));
                }
                writer::WriterMsg::Snapshot { ack_tx } => {
                    let snapshot = WalSnapshot {
                        sealed_segments: Vec::new(),
                        active_segment: None,
                    };
                    let _ = ack_tx.send(Ok(snapshot));
                }
            }
        }
        Ok(())
    });

    let rows = vec![DynRow(vec![
        Some(DynCell::Str("k".into())),
        Some(DynCell::I32(1)),
    ])];
    let batch: RecordBatch = build_batch(schema.clone(), rows).expect("batch");

    let mut db: DbInner<InMemoryFs, TokioExecutor> = DB::new(config, Arc::clone(&executor))
        .await
        .expect("db")
        .into_inner();
    let metrics = Arc::new(TokioExecutor::rw_lock(WalMetrics::default()));
    let handle =
        WalHandle::test_from_parts(sender, queue_depth, join, frame::INITIAL_FRAME_SEQ, metrics);
    db.set_wal_handle(Some(handle));
    assert!(db.wal_handle().is_some(), "wal handle should be installed");

    db.ingest_with_tombstones(batch, vec![false])
        .await
        .expect("ingest");

    let observed_range = db
        .mutable_wal_range_snapshot()
        .or_else(|| {
            db.seal_state_lock()
                .immutable_wal_ranges
                .first()
                .copied()
                .flatten()
        })
        .expect("wal range populated after ingest");
    assert_eq!(observed_range.first, frame::INITIAL_FRAME_SEQ);
    assert_eq!(observed_range.last, frame::INITIAL_FRAME_SEQ + 2);
    assert_eq!(db.wal_live_frame_floor(), Some(frame::INITIAL_FRAME_SEQ));

    if db.mutable_wal_range_snapshot().is_some()
        && let Some(sealed) = db.seal_mutable()
    {
        let wal_range = db.take_mutable_wal_range();
        db.add_immutable(sealed, wal_range);
    }

    assert!(db.mutable_wal_range_snapshot().is_none());
    assert_eq!(db.wal_live_frame_floor(), Some(frame::INITIAL_FRAME_SEQ));

    {
        let mut seal = db.seal_state_lock();
        seal.immutables.clear();
        seal.immutable_wal_ranges.clear();
    }
    assert_eq!(db.wal_live_frame_floor(), None);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn wal_live_frame_floor_tracks_multi_frame_append_via_insert() {
    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("v", DataType::Int32, false),
    ]));
    let extractor = crate::extractor::projection_for_field(schema.clone(), 0).expect("extractor");
    let config = DynModeConfig::new(schema.clone(), extractor).expect("config");

    let executor = Arc::new(TokioExecutor::default());
    let (sender, mut receiver) = mpsc::channel(4);
    let queue_depth = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let join = executor.spawn(async move {
        let mut next_seq = frame::INITIAL_FRAME_SEQ;
        while let Some(msg) = receiver.next().await {
            match msg {
                writer::WriterMsg::Enqueue {
                    command, ack_tx, ..
                } => {
                    let (first_seq, last_seq, advance) = match command {
                        WalCommand::TxnAppend { .. } => (next_seq, next_seq.saturating_add(1), 2),
                        WalCommand::TxnCommit { .. } => (next_seq, next_seq, 1),
                        _ => (next_seq, next_seq, 1),
                    };
                    next_seq = next_seq.saturating_add(advance);
                    let ack = WalAck {
                        first_seq,
                        last_seq,
                        bytes_flushed: 0,
                        elapsed: Duration::from_millis(0),
                    };
                    let _ = ack_tx.send(Ok(ack));
                }
                writer::WriterMsg::Rotate { ack_tx } => {
                    let _ = ack_tx.send(Ok(()));
                }
                writer::WriterMsg::Snapshot { ack_tx } => {
                    let snapshot = WalSnapshot {
                        sealed_segments: Vec::new(),
                        active_segment: None,
                    };
                    let _ = ack_tx.send(Ok(snapshot));
                }
            }
        }
        Ok(())
    });

    let rows = vec![DynRow(vec![
        Some(DynCell::Str("k".into())),
        Some(DynCell::I32(1)),
    ])];
    let batch: RecordBatch = build_batch(schema.clone(), rows).expect("batch");

    let mut db: DbInner<InMemoryFs, TokioExecutor> = DB::new(config, Arc::clone(&executor))
        .await
        .expect("db")
        .into_inner();
    let metrics = Arc::new(TokioExecutor::rw_lock(WalMetrics::default()));
    let handle =
        WalHandle::test_from_parts(sender, queue_depth, join, frame::INITIAL_FRAME_SEQ, metrics);
    db.set_wal_handle(Some(handle));
    assert!(db.wal_handle().is_some(), "wal handle should be installed");

    db.ingest(batch.clone()).await.expect("ingest");

    let observed_range = db
        .mutable_wal_range_snapshot()
        .or_else(|| {
            db.seal_state_lock()
                .immutable_wal_ranges
                .first()
                .copied()
                .flatten()
        })
        .expect("wal range populated after ingest");
    assert_eq!(observed_range.first, frame::INITIAL_FRAME_SEQ);
    assert_eq!(observed_range.last, frame::INITIAL_FRAME_SEQ + 2);
    assert_eq!(db.wal_live_frame_floor(), Some(frame::INITIAL_FRAME_SEQ));

    if db.mutable_wal_range_snapshot().is_some()
        && let Some(sealed) = db.seal_mutable()
    {
        let wal_range = db.take_mutable_wal_range();
        db.add_immutable(sealed, wal_range);
    }

    assert!(db.mutable_wal_range_snapshot().is_none());
    assert_eq!(db.wal_live_frame_floor(), Some(frame::INITIAL_FRAME_SEQ));

    {
        let mut seal = db.seal_state_lock();
        seal.immutables.clear();
        seal.immutable_wal_ranges.clear();
    }
    assert_eq!(db.wal_live_frame_floor(), None);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dyn_insert_enqueues_commit_before_append_ack() {
    use tokio::time;

    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("v", DataType::Int32, false),
    ]));
    let extractor = crate::extractor::projection_for_field(schema.clone(), 0).expect("extractor");
    let config = DynModeConfig::new(schema.clone(), extractor).expect("config");

    let executor = Arc::new(TokioExecutor::default());
    let (sender, mut receiver) = mpsc::channel(4);
    let queue_depth = Arc::new(std::sync::atomic::AtomicUsize::new(0));

    let (append_seen_tx, append_seen_rx) = oneshot::channel();
    let (commit_seen_tx, commit_seen_rx) = oneshot::channel();
    let (release_append_ack_tx, release_append_ack_rx) = oneshot::channel();
    let (release_commit_ack_tx, release_commit_ack_rx) = oneshot::channel();

    let join = executor.spawn(async move {
        let mut next_seq = frame::INITIAL_FRAME_SEQ;
        let mut pending_append_ack: Option<futures_oneshot::Sender<WalResult<WalAck>>> = None;
        let mut release_append_ack_rx = Some(release_append_ack_rx);
        let mut release_commit_ack_rx = Some(release_commit_ack_rx);
        let mut append_seen_tx = Some(append_seen_tx);
        let mut commit_seen_tx = Some(commit_seen_tx);
        while let Some(msg) = receiver.next().await {
            match msg {
                writer::WriterMsg::Enqueue {
                    command, ack_tx, ..
                } => match command {
                    WalCommand::TxnAppend { .. } => {
                        pending_append_ack = Some(ack_tx);
                        if let Some(tx) = append_seen_tx.take() {
                            let _ = tx.send(());
                        }
                    }
                    WalCommand::TxnCommit { .. } => {
                        if let Some(tx) = commit_seen_tx.take() {
                            let _ = tx.send(());
                        }
                        if let Some(rx) = release_append_ack_rx.take() {
                            let _ = rx.await;
                        }
                        if let Some(append_ack_tx) = pending_append_ack.take() {
                            let ack = WalAck {
                                first_seq: next_seq,
                                last_seq: next_seq,
                                bytes_flushed: 0,
                                elapsed: Duration::from_millis(0),
                            };
                            let _ = append_ack_tx.send(Ok(ack));
                            next_seq = next_seq.saturating_add(1);
                        }
                        if let Some(rx) = release_commit_ack_rx.take() {
                            let _ = rx.await;
                        }
                        let ack = WalAck {
                            first_seq: next_seq,
                            last_seq: next_seq,
                            bytes_flushed: 0,
                            elapsed: Duration::from_millis(0),
                        };
                        let _ = ack_tx.send(Ok(ack));
                        next_seq = next_seq.saturating_add(1);
                    }
                    _ => {}
                },
                writer::WriterMsg::Rotate { ack_tx } => {
                    let _ = ack_tx.send(Ok(()));
                }
                writer::WriterMsg::Snapshot { ack_tx } => {
                    let snapshot = WalSnapshot {
                        sealed_segments: Vec::new(),
                        active_segment: None,
                    };
                    let _ = ack_tx.send(Ok(snapshot));
                }
            }
        }
        Ok(())
    });

    let rows = vec![DynRow(vec![
        Some(DynCell::Str("k".into())),
        Some(DynCell::I32(1)),
    ])];
    let batch: RecordBatch = build_batch(schema.clone(), rows).expect("batch");

    let mut db: DbInner<InMemoryFs, TokioExecutor> = DB::new(config, Arc::clone(&executor))
        .await
        .expect("db")
        .into_inner();
    let metrics = Arc::new(TokioExecutor::rw_lock(WalMetrics::default()));
    let handle =
        WalHandle::test_from_parts(sender, queue_depth, join, frame::INITIAL_FRAME_SEQ, metrics);
    db.set_wal_handle(Some(handle));

    let mut ingest_future = Box::pin(db.ingest(batch));
    tokio::select! {
        _ = append_seen_rx => {}
        res = &mut ingest_future => panic!("ingest finished early: {:?}", res),
    }
    tokio::select! {
        res = commit_seen_rx => {
            res.expect("commit notification");
        }
        _ = time::sleep(Duration::from_millis(50)) => {
            panic!("commit not enqueued before append ack release");
        }
        res = &mut ingest_future => panic!("ingest finished before commit ack gating: {:?}", res),
    }

    release_append_ack_tx.send(()).expect("release append ack");
    release_commit_ack_tx.send(()).expect("release commit ack");

    ingest_future.await.expect("ingest complete");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn flush_records_manifest_metadata() -> Result<(), Box<dyn std::error::Error>> {
    let temp_root = workspace_temp_dir("wal-manifest-metadata");
    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("value", DataType::Int32, false),
    ]));
    let mode_config = SchemaBuilder::from_schema(schema)
        .primary_key("id")
        .with_metadata()
        .build()
        .expect("key field");
    let schema = Arc::clone(&mode_config.schema);
    let executor = Arc::new(TokioExecutor::default());
    let namespace = temp_root
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("wal-manifest-metadata");
    let mut db: DbInner<InMemoryFs, TokioExecutor> =
        DB::<InMemoryFs, TokioExecutor>::builder(mode_config)
            .in_memory(namespace.to_string())?
            .open_with_executor(Arc::clone(&executor))
            .await?
            .into_inner();

    let wal_local_fs = Arc::new(fusio::disk::LocalFs {});
    let wal_dyn_fs: Arc<dyn DynFs> = wal_local_fs.clone();
    let wal_cas: Arc<dyn FsCas> = wal_local_fs.clone();
    let wal_dir = temp_root.join("wal");
    fs::create_dir_all(&wal_dir)?;
    let wal_path = Path::from_filesystem_path(&wal_dir)?;

    let wal_cfg = RuntimeWalConfig {
        dir: wal_path,
        segment_backend: wal_dyn_fs,
        state_store: Some(Arc::new(FsWalStateStore::new(wal_cas))),
        segment_max_bytes: 1,
        flush_interval: Duration::from_millis(1),
        sync: WalSyncPolicy::Disabled,
        ..RuntimeWalConfig::default()
    };

    db.enable_wal(wal_cfg.clone()).await?;
    db.set_seal_policy(Arc::new(BatchesThreshold { batches: 1 }));

    let rows = vec![
        vec![Some(DynCell::Str("alpha".into())), Some(DynCell::I32(7))],
        vec![Some(DynCell::Str("beta".into())), Some(DynCell::I32(9))],
    ];
    let batch = build_batch(schema.clone(), rows)?;
    db.ingest(batch).await?;
    assert!(db.num_immutable_segments() >= 1);

    let sst_dir = temp_root.join("sst");
    fs::create_dir_all(&sst_dir)?;
    let sst_root = Path::from_filesystem_path(&sst_dir)?;
    let sst_fs: Arc<dyn DynFs> = Arc::new(fusio::disk::LocalFs {});
    let sst_cfg = Arc::new(SsTableConfig::new(schema.clone(), sst_fs, sst_root));
    let descriptor = SsTableDescriptor::new(SsTableId::new(555), 0);
    db.flush_immutables_with_descriptor(Arc::clone(&sst_cfg), descriptor.clone())
        .await?;

    let snapshot = db.manifest.snapshot_latest(db.manifest_table).await?;
    let latest = snapshot
        .latest_version
        .expect("latest version should exist after flush");
    assert!(
        !latest.wal_segments().is_empty(),
        "manifest should track wal segments for the version"
    );
    assert!(
        latest.wal_floor().is_some(),
        "wal floor should be derived from recorded segments"
    );
    let recorded = &latest.ssts()[0][0];
    let stats = recorded.stats().expect("sst stats should be recorded");
    assert_eq!(stats.rows, 2);
    assert!(stats.min_key.is_some() && stats.max_key.is_some());
    assert!(stats.min_commit_ts.is_some() && stats.max_commit_ts.is_some());
    let watermark = latest
        .tombstone_watermark()
        .expect("tombstone watermark should be populated");
    assert_eq!(
        watermark,
        stats
            .max_commit_ts
            .expect("max commit timestamp should be recorded")
            .get()
    );

    if let Some(handle) = db.wal().cloned() {
        let metrics = handle.metrics();
        let guard = metrics.read().await;
        assert!(guard.wal_floor_advancements >= 1);
    }

    db.disable_wal().await?;
    fs::remove_dir_all(&temp_root)?;
    Ok(())
}

/// Test to verify WAL logging events are emitted correctly.
///
/// Writes logs to a file, then reads and verifies expected events are present.
/// Uses a file because global subscribers can't be easily captured to memory
/// when spawned tasks are involved.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn wal_logging_verification() -> Result<(), Box<dyn std::error::Error>> {
    use tracing_subscriber::{EnvFilter, fmt, layer::SubscriberExt, util::SubscriberInitExt};

    let temp_root = workspace_temp_dir("wal_logging_verification");
    fs::create_dir_all(&temp_root)?;
    let log_file_path = temp_root.join("test.log");

    // Create a file for log output
    let log_file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .truncate(true)
        .open(&log_file_path)?;

    // Try to set global subscriber (may fail if already set by another test)
    let _ = tracing_subscriber::registry()
        .with(
            fmt::layer()
                .with_ansi(false)
                .with_writer(std::sync::Mutex::new(log_file)),
        )
        .with(EnvFilter::new("tonbo=debug"))
        .try_init();

    let schema = Arc::new(Schema::new(vec![
        Field::new("id", DataType::Utf8, false),
        Field::new("v", DataType::Int32, false),
    ]));
    let extractor = crate::extractor::projection_for_field(schema.clone(), 0)?;
    let mode_config = DynModeConfig::new(schema.clone(), extractor)?;

    let executor = Arc::new(TokioExecutor::default());
    let namespace = "wal-logging-verification";

    let mut db: DbInner<InMemoryFs, TokioExecutor> =
        DB::<InMemoryFs, TokioExecutor>::builder(mode_config)
            .in_memory(namespace.to_string())?
            .open_with_executor(Arc::clone(&executor))
            .await?
            .into_inner();

    let wal_local_fs = Arc::new(fusio::disk::LocalFs {});
    let wal_dyn_fs: Arc<dyn DynFs> = wal_local_fs.clone();
    let wal_cas: Arc<dyn FsCas> = wal_local_fs.clone();
    let wal_dir = temp_root.join("wal");
    fs::create_dir_all(&wal_dir)?;
    let wal_path = Path::from_filesystem_path(&wal_dir)?;

    let wal_cfg = RuntimeWalConfig {
        dir: wal_path,
        segment_backend: wal_dyn_fs,
        state_store: Some(Arc::new(FsWalStateStore::new(wal_cas))),
        segment_max_bytes: 1024,
        flush_interval: Duration::from_millis(1),
        sync: WalSyncPolicy::Disabled,
        ..RuntimeWalConfig::default()
    };

    db.enable_wal(wal_cfg).await?;

    // Give the async writer task time to initialize and log
    tokio::time::sleep(Duration::from_millis(100)).await;

    db.disable_wal().await?;

    // Read the log file and verify events
    let log_contents = fs::read_to_string(&log_file_path).unwrap_or_default();

    // Note: If subscriber was already set by another test, this file may be empty.
    // In that case, we skip assertions but don't fail the test.
    if !log_contents.is_empty() {
        assert!(
            log_contents.contains("wal_writer_spawned"),
            "log should contain wal_writer_spawned event, got: {}",
            log_contents
        );
        assert!(
            log_contents.contains("wal_enabled"),
            "log should contain wal_enabled event"
        );
        assert!(
            log_contents.contains("wal_writer_bootstrap"),
            "log should contain wal_writer_bootstrap event"
        );
        assert!(
            log_contents.contains("wal_writer_shutdown"),
            "log should contain wal_writer_shutdown event"
        );
    }

    fs::remove_dir_all(&temp_root)?;
    Ok(())
}