timeseries-table-format 0.6.1

Append-only time-series table format with gap/overlap tracking
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
//! Integration tests for log-based metadata core.
//!
//! These tests validate end-to-end behavior of the async log writer and reader:
//! - Happy path commit sequences with TableState reconstruction,
//! - Conflict handling via version guards,
//! - Robust handling of missing/malformed metadata.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use crate::coverage::EntityIdentity;
use crate::metadata::logical_schema::{
    LogicalDataType, LogicalField, LogicalSchema, LogicalTimestampUnit,
};
use crate::metadata::segments::{FileFormat, SegmentEntityLayout, SegmentMeta};
use crate::metadata::{
    index::{IndexKind, IndexSpec, TimeIndexGranularity},
    protocol::TABLE_PROTOCOL_VERSION,
    table::{TableKind, TableMeta},
};
use crate::storage::{StorageError, TableLocation, layout};
use crate::transaction_log::{CommitError, LogAction, TransactionLogStore};
use chrono::{DateTime, TimeZone, Utc};
use tempfile::TempDir;

type TestResult = Result<(), Box<dyn std::error::Error>>;

// =============================================================================
// Test Helpers
// =============================================================================

fn create_test_log_store() -> (TempDir, TransactionLogStore) {
    let tmp = TempDir::new().expect("create temp dir");
    let location = TableLocation::local(tmp.path());
    let store = TransactionLogStore::new(location);
    (tmp, store)
}

fn sample_time_index_spec() -> IndexSpec {
    IndexSpec {
        column: "ts".to_string(),
        entity_columns: vec!["symbol".to_string()],
        kind: IndexKind::Timestamp {
            index_granularity: TimeIndexGranularity::Minutes(1),
            timezone: None,
        },
    }
}

fn sample_table_meta() -> TableMeta {
    let schema = LogicalSchema::new(vec![
        LogicalField {
            name: "ts".to_string(),
            data_type: LogicalDataType::Timestamp {
                unit: LogicalTimestampUnit::Micros,
                timezone: None,
            },
            nullable: false,
        },
        LogicalField {
            name: "symbol".to_string(),
            data_type: LogicalDataType::Utf8,
            nullable: false,
        },
        LogicalField {
            name: "price".to_string(),
            data_type: LogicalDataType::Float64,
            nullable: true,
        },
    ])
    .expect("valid logical schema");

    TableMeta::new_time_series_with_schema(sample_time_index_spec(), schema)
}

fn sample_segment(id: &str, ts_hour: u32) -> SegmentMeta {
    SegmentMeta {
        path: format!("data/{id}.parquet"),
        format: FileFormat::Parquet,
        entity_layout: SegmentEntityLayout::Single(
            EntityIdentity::try_new(vec!["A".into()]).expect("valid sample identity"),
        ),
        index_min: (utc_datetime(2025, 1, 1, ts_hour, 0, 0)).into(),
        index_max: (utc_datetime(2025, 1, 1, ts_hour + 1, 0, 0)).into(),
        row_count: 1000,
        file_size: None,
        coverage_path: None,
    }
}

fn utc_datetime(
    year: i32,
    month: u32,
    day: u32,
    hour: u32,
    minute: u32,
    second: u32,
) -> DateTime<Utc> {
    Utc.with_ymd_and_hms(year, month, day, hour, minute, second)
        .single()
        .expect("valid UTC timestamp")
}

// =============================================================================
// Happy Path Tests
// =============================================================================

/// Test: Fresh directory with no CURRENT or _timeseries_log/ should return version 0.
#[tokio::test]
async fn fresh_directory_returns_version_zero() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let version = store.load_current_version().await?;
    assert_eq!(version, 0);

    Ok(())
}

/// Test: Full happy path - bootstrap table, add segments, verify state reconstruction.
#[tokio::test]
async fn happy_path_commit_and_rebuild_table_state() -> TestResult {
    let (tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let seg1 = sample_segment("seg-001", 0);
    let seg2 = sample_segment("seg-002", 1);

    // Commit 1: Bootstrap with UpdateTableMeta + first segment
    let v1 = store
        .commit_with_expected_version(
            0,
            vec![
                LogAction::UpdateTableMeta(meta.clone()),
                LogAction::AddSegment(seg1.clone()),
            ],
        )
        .await?;
    assert_eq!(v1, 1);

    // Verify commit file exists
    let commit_1_path = tmp.path().join(layout::commit_rel_path(1));
    assert!(
        commit_1_path.exists(),
        "commit file for version 1 should exist"
    );

    // Commit 2: Add second segment
    let v2 = store
        .commit_with_expected_version(v1, vec![LogAction::AddSegment(seg2.clone())])
        .await?;
    assert_eq!(v2, 2);

    // Verify commit file exists
    let commit_2_path = tmp.path().join(layout::commit_rel_path(2));
    assert!(
        commit_2_path.exists(),
        "commit file for version 2 should exist"
    );

    // Rebuild and verify TableState
    let state = store.rebuild_table_state().await?;

    assert_eq!(state.version, 2);
    assert_eq!(state.segments.len(), 2);
    assert!(state.segments.contains_key(&seg1.path));
    assert!(state.segments.contains_key(&seg2.path));

    // Verify table_meta.kind is TableKind::TimeSeries
    match state.table_meta.kind() {
        TableKind::TimeSeries(spec) => {
            assert_eq!(spec.column, "ts");
            assert_eq!(spec.entity_columns, vec!["symbol".to_string()]);
        }
        TableKind::Generic => panic!("expected TimeSeries, got Generic"),
    }

    // Verify logical schema was preserved
    assert!(state.table_meta.logical_schema().is_some());
    let schema = state
        .table_meta
        .logical_schema()
        .expect("logical schema must be present");
    assert_eq!(schema.columns().len(), 3);

    Ok(())
}

/// Test: Multiple sequential commits building up state.
#[tokio::test]
async fn sequential_commits_accumulate_segments() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();

    // Commit 1: Bootstrap
    let v1 = store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta.clone())])
        .await?;
    assert_eq!(v1, 1);

    // Commits 2-5: Add segments one by one
    let mut expected_version = v1;
    for i in 1..=4 {
        let seg = sample_segment(&format!("seg-{i:03}"), i as u32);
        let v = store
            .commit_with_expected_version(expected_version, vec![LogAction::AddSegment(seg)])
            .await?;
        assert_eq!(v, expected_version + 1);
        expected_version = v;
    }

    // Final state should have 4 segments
    let state = store.rebuild_table_state().await?;
    assert_eq!(state.version, 5);
    assert_eq!(state.segments.len(), 4);

    Ok(())
}

/// Test: AddSegment followed by RemoveSegment removes the segment from final state.
#[tokio::test]
async fn remove_segment_removes_from_state() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let seg1 = sample_segment("seg-to-keep", 0);
    let seg2 = sample_segment("seg-to-remove", 1);

    // Commit 1: Bootstrap + add both segments
    let v1 = store
        .commit_with_expected_version(
            0,
            vec![
                LogAction::UpdateTableMeta(meta),
                LogAction::AddSegment(seg1.clone()),
                LogAction::AddSegment(seg2.clone()),
            ],
        )
        .await?;

    // Commit 2: Remove seg2
    let v2 = store
        .commit_with_expected_version(
            v1,
            vec![LogAction::RemoveSegment {
                path: seg2.path.clone(),
            }],
        )
        .await?;

    let state = store.rebuild_table_state().await?;
    assert_eq!(state.version, v2);
    assert_eq!(state.segments.len(), 1);
    assert!(state.segments.contains_key(&seg1.path));
    assert!(!state.segments.contains_key(&seg2.path));

    Ok(())
}

// =============================================================================
// Conflict Tests
// =============================================================================

/// Test: Two "clients" trying to commit with the same expected version.
/// The second commit should fail with CommitError::Conflict.
#[tokio::test]
async fn conflict_when_expected_version_is_stale() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();

    // Both "clients" read expected_version = 0
    let expected_version = store.load_current_version().await?;
    assert_eq!(expected_version, 0);

    // Client 1 commits successfully
    let v1 = store
        .commit_with_expected_version(
            expected_version,
            vec![LogAction::UpdateTableMeta(meta.clone())],
        )
        .await?;
    assert_eq!(v1, 1);

    // Client 2 tries to commit with stale expected_version = 0
    let result = store
        .commit_with_expected_version(
            expected_version,
            vec![LogAction::AddSegment(sample_segment("seg-conflict", 0))],
        )
        .await;

    match result {
        Err(CommitError::Conflict {
            expected, found, ..
        }) => {
            assert_eq!(expected, 0);
            assert_eq!(found, 1);
        }
        other => panic!("expected Conflict error, got: {other:?}"),
    }

    // Verify CURRENT still reflects version 1 (not corrupted by failed commit)
    let current = store.load_current_version().await?;
    assert_eq!(current, 1);

    Ok(())
}

/// Test: Simulate conflict at version 2+ (not just initial commit).
#[tokio::test]
async fn conflict_on_subsequent_version() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();

    // Commit version 1
    store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;

    // Commit version 2
    store
        .commit_with_expected_version(1, vec![LogAction::AddSegment(sample_segment("seg-1", 0))])
        .await?;

    // Try to commit with expected=1 (stale, should be 2)
    let result = store
        .commit_with_expected_version(1, vec![LogAction::AddSegment(sample_segment("seg-2", 1))])
        .await;

    match result {
        Err(CommitError::Conflict {
            expected, found, ..
        }) => {
            assert_eq!(expected, 1);
            assert_eq!(found, 2);
        }
        other => panic!("expected Conflict error, got: {other:?}"),
    }

    Ok(())
}

// =============================================================================
// Robustness Tests - Corrupt/Missing State
// =============================================================================

/// Test: Corrupt CURRENT file preserves its integer parsing failure.
#[tokio::test]
async fn corrupt_current_file_returns_parse_error() -> TestResult {
    let (tmp, store) = create_test_log_store();

    // Create corrupt CURRENT file
    let log_dir = tmp.path().join(layout::log_rel_dir());
    tokio::fs::create_dir_all(&log_dir).await?;
    let current_path = tmp.path().join(layout::current_rel_path());
    tokio::fs::write(&current_path, "not-a-number").await?;

    let result = store.load_current_version().await;
    assert!(
        matches!(result, Err(CommitError::CurrentVersionParse { .. })),
        "expected CurrentVersionParse, got: {result:?}"
    );

    Ok(())
}

/// Test: Empty CURRENT file returns a typed pointer error.
#[tokio::test]
async fn empty_current_file_returns_empty_pointer_error() -> TestResult {
    let (tmp, store) = create_test_log_store();

    let log_dir = tmp.path().join(layout::log_rel_dir());
    tokio::fs::create_dir_all(&log_dir).await?;
    let current_path = tmp.path().join(layout::current_rel_path());
    tokio::fs::write(&current_path, "").await?;

    let result = store.load_current_version().await;
    assert!(
        matches!(result, Err(CommitError::EmptyCurrentPointer { .. })),
        "expected EmptyCurrentPointer, got: {result:?}"
    );

    Ok(())
}

/// Test: Corrupt commit file preserves its JSON decoding failure.
#[tokio::test]
async fn corrupt_commit_file_returns_deserialization_error() -> TestResult {
    let (tmp, store) = create_test_log_store();

    let meta = sample_table_meta();

    // Create a valid commit first
    store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;

    // Corrupt the commit file
    let commit_path = tmp.path().join(layout::commit_rel_path(1));
    tokio::fs::write(&commit_path, "{ invalid json }}}").await?;

    // load_commit should fail with the typed JSON source.
    let result = store.load_commit(1).await;
    assert!(
        matches!(result, Err(CommitError::CommitDeserialization { .. })),
        "expected CommitDeserialization, got: {result:?}"
    );

    // rebuild_table_state should also fail
    let result = store.rebuild_table_state().await;
    assert!(
        matches!(result, Err(CommitError::CommitDeserialization { .. })),
        "expected CommitDeserialization, got: {result:?}"
    );

    Ok(())
}

/// Test: Missing commit file returns Storage(NotFound).
#[tokio::test]
async fn missing_commit_file_returns_storage_not_found() -> TestResult {
    let (tmp, store) = create_test_log_store();

    let meta = sample_table_meta();

    // Create commit 1
    store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;

    // Delete the commit file
    let commit_path = tmp.path().join(layout::commit_rel_path(1));
    tokio::fs::remove_file(&commit_path).await?;

    // load_commit should fail with Storage(NotFound)
    let result = store.load_commit(1).await;
    match result {
        Err(CommitError::Storage {
            source: StorageError::NotFound { .. },
        }) => {}
        other => panic!("expected Storage(NotFound), got: {other:?}"),
    }

    Ok(())
}

/// Test: Leftover .tmp files in _timeseries_log/ are ignored by the reader.
#[tokio::test]
async fn leftover_tmp_files_are_ignored() -> TestResult {
    let (tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let seg = sample_segment("seg-1", 0);

    // Commit version 1
    store
        .commit_with_expected_version(
            0,
            vec![
                LogAction::UpdateTableMeta(meta.clone()),
                LogAction::AddSegment(seg.clone()),
            ],
        )
        .await?;

    // Create leftover .tmp files that might be from crashed writes
    let log_dir = tmp.path().join(layout::log_rel_dir());
    tokio::fs::write(log_dir.join("0000000002.json.tmp"), b"garbage").await?;
    tokio::fs::write(log_dir.join(".tmp_random_file"), b"more garbage").await?;
    tokio::fs::write(log_dir.join("temp_commit.tmp"), b"even more garbage").await?;

    // rebuild_table_state should succeed and ignore .tmp files
    let state = store.rebuild_table_state().await?;
    assert_eq!(state.version, 1);
    assert_eq!(state.segments.len(), 1);

    // Verify .tmp files still exist (weren't cleaned up, just ignored)
    assert!(log_dir.join("0000000002.json.tmp").exists());

    Ok(())
}

/// Test: CURRENT points to version N, but commit file for version < N is missing.
/// This should fail during rebuild_table_state.
#[tokio::test]
async fn missing_intermediate_commit_fails_rebuild() -> TestResult {
    let (tmp, store) = create_test_log_store();

    let meta = sample_table_meta();

    // Create commits 1 and 2
    store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta.clone())])
        .await?;
    store
        .commit_with_expected_version(1, vec![LogAction::AddSegment(sample_segment("seg-1", 0))])
        .await?;

    // Delete commit 1 (intermediate)
    let commit_1_path = tmp.path().join(layout::commit_rel_path(1));
    tokio::fs::remove_file(&commit_1_path).await?;

    // rebuild_table_state should fail when trying to load commit 1
    let result = store.rebuild_table_state().await;
    match result {
        Err(CommitError::Storage {
            source: StorageError::NotFound { .. },
        }) => {}
        other => panic!("expected Storage(NotFound), got: {other:?}"),
    }

    Ok(())
}

/// Test: rebuilding an empty table returns an uninitialized-state error.
#[tokio::test]
async fn rebuild_on_empty_table_returns_uninitialized_state() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let result = store.rebuild_table_state().await;
    assert!(
        matches!(result, Err(CommitError::UninitializedTableState { .. })),
        "expected UninitializedTableState for empty table, got: {result:?}"
    );

    Ok(())
}

/// Test: Commits without UpdateTableMeta return a typed metadata error.
#[tokio::test]
async fn rebuild_without_table_meta_returns_missing_metadata() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    // Commit only AddSegment, no UpdateTableMeta
    store
        .commit_with_expected_version(0, vec![LogAction::AddSegment(sample_segment("seg-1", 0))])
        .await?;

    let result = store.rebuild_table_state().await;
    assert!(
        matches!(result, Err(CommitError::MissingTableMetadata { .. })),
        "expected MissingTableMetadata, got: {result:?}"
    );

    Ok(())
}

// =============================================================================
// Edge Cases
// =============================================================================

/// Test: UpdateTableMeta can be applied multiple times; last one wins.
#[tokio::test]
async fn update_table_meta_last_one_wins() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta1 = TableMeta::new_time_series(IndexSpec {
        column: "ts".to_string(),
        entity_columns: vec![],
        kind: IndexKind::Timestamp {
            index_granularity: TimeIndexGranularity::Minutes(1),
            timezone: None,
        },
    });

    let meta2 = TableMeta::new_time_series(IndexSpec {
        column: "event_time".to_string(), // Changed!
        entity_columns: vec!["user_id".to_string()],
        kind: IndexKind::Timestamp {
            index_granularity: TimeIndexGranularity::Hours(1),
            timezone: Some("UTC".to_string()),
        },
    });

    // Commit 1: First TableMeta
    store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta1)])
        .await?;

    // Commit 2: Updated TableMeta
    store
        .commit_with_expected_version(1, vec![LogAction::UpdateTableMeta(meta2.clone())])
        .await?;

    let state = store.rebuild_table_state().await?;

    // meta2 should win
    match state.table_meta.kind() {
        TableKind::TimeSeries(spec) => {
            assert_eq!(spec.column, "event_time");
            assert_eq!(spec.entity_columns, vec!["user_id".to_string()]);
            assert_eq!(
                spec.kind,
                IndexKind::Timestamp {
                    index_granularity: TimeIndexGranularity::Hours(1),
                    timezone: Some("UTC".to_string())
                }
            );
        }
        _ => panic!("expected TimeSeries"),
    }
    // Protocol version is constant; this test focuses on "last one wins" for
    // the index spec and related fields. We still sanity-check the version value.
    assert_eq!(state.table_meta.protocol_version(), TABLE_PROTOCOL_VERSION);

    Ok(())
}

/// Test: replay rejects a second live segment with the same path.
#[tokio::test]
async fn duplicate_live_segment_path_is_rejected() -> TestResult {
    let (_tmp, store) = create_test_log_store();
    let meta = sample_table_meta();
    let seg = sample_segment("seg-001", 0);
    let mut duplicate = sample_segment("seg-002", 1);
    duplicate.path = seg.path.clone();

    store
        .commit_with_expected_version(
            0,
            vec![
                LogAction::UpdateTableMeta(meta),
                LogAction::AddSegment(seg.clone()),
            ],
        )
        .await?;
    store
        .commit_with_expected_version(1, vec![LogAction::AddSegment(duplicate)])
        .await?;

    let err = store
        .rebuild_table_state()
        .await
        .expect_err("duplicate live path must be corrupt");
    assert!(matches!(
        err,
        CommitError::DuplicateLiveSegmentPath { ref path, .. } if path == &seg.path
    ));

    Ok(())
}

/// Test: RemoveSegment on non-existent segment is a no-op (doesn't error).
#[tokio::test]
async fn remove_nonexistent_segment_is_noop() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let seg = sample_segment("seg-exists", 0);

    // Commit with one segment
    store
        .commit_with_expected_version(
            0,
            vec![
                LogAction::UpdateTableMeta(meta),
                LogAction::AddSegment(seg.clone()),
            ],
        )
        .await?;

    // Remove a segment that doesn't exist
    store
        .commit_with_expected_version(
            1,
            vec![LogAction::RemoveSegment {
                path: "data/does-not-exist.parquet".to_string(),
            }],
        )
        .await?;

    // Should succeed, original segment still there
    let state = store.rebuild_table_state().await?;
    assert_eq!(state.segments.len(), 1);
    assert!(state.segments.contains_key(&seg.path));

    Ok(())
}

/// Test: UpdateTableCoverage actions are replayed into TableState.
#[tokio::test]
async fn table_coverage_pointer_is_replayed() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let coverage_kind = sample_time_index_spec().kind;
    let coverage_path = "coverage/0000000002.bitmap".to_string();

    let v1 = store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;

    let v2 = store
        .commit_with_expected_version(
            v1,
            vec![LogAction::UpdateTableCoverage {
                index_kind: coverage_kind.clone(),
                coverage_path: coverage_path.clone(),
            }],
        )
        .await?;

    let state = store.rebuild_table_state().await?;
    assert_eq!(state.version, v2);

    let pointer = state
        .table_coverage
        .as_ref()
        .expect("table coverage pointer should be present");
    assert_eq!(pointer.index_kind, coverage_kind);
    assert_eq!(pointer.coverage_path, coverage_path);
    assert_eq!(pointer.version, v2);

    Ok(())
}

/// Test: Multiple UpdateTableCoverage commits – last one wins.
#[tokio::test]
async fn table_coverage_last_one_wins() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let coverage_kind = sample_time_index_spec().kind;
    let coverage_path_v1 = "coverage/0000000002.bitmap".to_string();
    let coverage_path_v2 = "coverage/0000000003.bitmap".to_string();

    let v1 = store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;

    let v2 = store
        .commit_with_expected_version(
            v1,
            vec![LogAction::UpdateTableCoverage {
                index_kind: coverage_kind.clone(),
                coverage_path: coverage_path_v1.clone(),
            }],
        )
        .await?;

    let v3 = store
        .commit_with_expected_version(
            v2,
            vec![LogAction::UpdateTableCoverage {
                index_kind: coverage_kind.clone(),
                coverage_path: coverage_path_v2.clone(),
            }],
        )
        .await?;

    let state = store.rebuild_table_state().await?;
    assert_eq!(state.version, v3);

    let pointer = state
        .table_coverage
        .as_ref()
        .expect("table coverage pointer should be present");
    assert_eq!(pointer.index_kind, coverage_kind);
    assert_eq!(pointer.coverage_path, coverage_path_v2);
    assert_eq!(pointer.version, v3);

    Ok(())
}

/// Test: Absence of UpdateTableCoverage leaves TableState.table_coverage as None.
#[tokio::test]
async fn table_coverage_is_none_when_not_committed() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let seg = sample_segment("seg-without-coverage", 0);

    let v1 = store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;
    store
        .commit_with_expected_version(v1, vec![LogAction::AddSegment(seg)])
        .await?;

    let state = store.rebuild_table_state().await?;

    assert_eq!(state.version, 2);
    assert!(state.table_coverage.is_none());

    Ok(())
}

/// Test: Segments with coverage_path and a snapshot pointer are replayed.
#[tokio::test]
async fn table_coverage_rebuilds_with_segment_coverage_paths() -> TestResult {
    let (_tmp, store) = create_test_log_store();

    let meta = sample_table_meta();
    let coverage_kind = sample_time_index_spec().kind;
    let segment_cov_path = "coverage/seg-001.roar".to_string();
    let snapshot_cov_path = "coverage/table/0000000002.roar".to_string();

    let mut seg = sample_segment("seg-001", 0);
    seg.coverage_path = Some(segment_cov_path.clone());

    let v1 = store
        .commit_with_expected_version(0, vec![LogAction::UpdateTableMeta(meta)])
        .await?;
    let v2 = store
        .commit_with_expected_version(v1, vec![LogAction::AddSegment(seg.clone())])
        .await?;
    let v3 = store
        .commit_with_expected_version(
            v2,
            vec![LogAction::UpdateTableCoverage {
                index_kind: coverage_kind.clone(),
                coverage_path: snapshot_cov_path.clone(),
            }],
        )
        .await?;

    let state = store.rebuild_table_state().await?;
    assert_eq!(state.version, v3);

    let rebuilt_seg = state
        .segments
        .get(&seg.path)
        .expect("segment present after rebuild");
    assert_eq!(
        rebuilt_seg.coverage_path.as_deref(),
        Some(segment_cov_path.as_str())
    );

    let pointer = state
        .table_coverage
        .as_ref()
        .expect("table coverage pointer should be present");
    assert_eq!(pointer.index_kind, coverage_kind);
    assert_eq!(pointer.coverage_path, snapshot_cov_path);
    assert_eq!(pointer.version, v3);

    Ok(())
}