timslite 0.1.0

High-performance mmap-backed time-series storage engine with queues, journal, C ABI, and Python bindings.
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
//! Configuration types for timslite.
//!
//! `StoreConfig` combines Store runtime settings with defaults for newly
//! created datasets. Existing datasets reopen from their own meta files.

use std::time::Duration;

use crate::compress::COMPRESS_TYPE_ZSTD;
use crate::error::{Result, TmslError};

fn validate_nonzero_size(field: &str, value: u64) -> Result<()> {
    if value == 0 {
        return Err(TmslError::InvalidData(format!("{field} must be > 0")));
    }
    Ok(())
}

pub(crate) fn validate_compress_level(compress_level: u8) -> Result<()> {
    if compress_level > 9 {
        return Err(TmslError::InvalidData(format!(
            "compress_level must be <= 9, got {compress_level}"
        )));
    }
    Ok(())
}

pub(crate) fn validate_index_continuous(index_continuous: u8) -> Result<()> {
    if index_continuous > 1 {
        return Err(TmslError::InvalidData(format!(
            "index_continuous must be 0 or 1, got {index_continuous}"
        )));
    }
    Ok(())
}

pub(crate) fn validate_retention_window(retention_window: u64) -> Result<()> {
    if retention_window > i64::MAX as u64 {
        return Err(TmslError::InvalidData(format!(
            "retention_window must be <= i64::MAX, got {retention_window}"
        )));
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub(crate) fn validate_dataset_config_values(
    data_segment_size: u64,
    index_segment_size: u64,
    compress_level: u8,
    compress_type: u8,
    index_continuous: u8,
    initial_data_segment_size: u64,
    initial_index_segment_size: u64,
    retention_window: u64,
) -> Result<()> {
    validate_nonzero_size("data_segment_size", data_segment_size)?;
    validate_nonzero_size("index_segment_size", index_segment_size)?;
    validate_nonzero_size("initial_data_segment_size", initial_data_segment_size)?;
    validate_nonzero_size("initial_index_segment_size", initial_index_segment_size)?;
    if initial_data_segment_size > data_segment_size {
        return Err(TmslError::InvalidData(format!(
            "initial_data_segment_size must be <= data_segment_size, got {initial_data_segment_size} > {data_segment_size}"
        )));
    }
    if initial_index_segment_size > index_segment_size {
        return Err(TmslError::InvalidData(format!(
            "initial_index_segment_size must be <= index_segment_size, got {initial_index_segment_size} > {index_segment_size}"
        )));
    }
    validate_compress_level(compress_level)?;
    crate::compress::validate_compress_type(compress_type)?;
    validate_index_continuous(index_continuous)?;
    validate_retention_window(retention_window)?;
    Ok(())
}

/// Store-level configuration.
///
/// Existing datasets do not compare against these defaults when reopened.
///
/// # Defaults
/// - `flush_interval`: 15 seconds
/// - `idle_timeout`: 30 minutes (1800s)
/// - `data_segment_size`: 64 MiB
/// - `index_segment_size`: 4 MiB
/// - `initial_data_segment_size`: 256 KiB
/// - `initial_index_segment_size`: 4 KiB
/// - `compress_level`: 6
/// - `compress_type`: 0 (zstd)
/// - `cache_max_memory`: 256 MiB (0 = disabled)
/// - `cache_idle_timeout`: 30 minutes (1800s)
/// - `retention_check_hour`: 0 (daily at UTC 00:00)
/// - `enable_background_thread`: true
/// - `enable_journal`: true
/// - `read_only`: None (auto: writable if the Store lock can be acquired)
#[derive(Clone, Debug)]
pub struct StoreConfig {
    /// Interval between background flush cycles (mmap sync only).
    pub(crate) flush_interval: Duration,
    /// Time of inactivity before segments are idle-closed.
    pub(crate) idle_timeout: Duration,
    /// Default data segment file size for newly created datasets.
    pub(crate) data_segment_size: u64,
    /// Default index segment file size for newly created datasets.
    pub(crate) index_segment_size: u64,
    /// Default initial data segment file size for newly created datasets.
    pub(crate) initial_data_segment_size: u64,
    /// Default initial index segment file size for newly created datasets.
    pub(crate) initial_index_segment_size: u64,
    /// Default compression level for newly created datasets (0-9).
    pub(crate) compress_level: u8,
    /// Default compression algorithm for newly created datasets (0=zstd, 1=deflate).
    pub(crate) compress_type: u8,
    /// Maximum memory for the read block cache (bytes, 0 = disabled).
    pub(crate) cache_max_memory: usize,
    /// Idle timeout for cache entries (eviction by background thread).
    pub(crate) cache_idle_timeout: Duration,
    /// UTC hour (0-23) at which the daily retention reclamation runs.
    pub(crate) retention_check_hour: u8,
    /// Whether to launch a background thread. When false, callers must invoke
    /// `Store::tick_background_tasks()` periodically to drive flush/idle/cache/retention.
    pub(crate) enable_background_thread: bool,
    /// Whether to enable the built-in `.journal/logs` change log.
    pub(crate) enable_journal: bool,
    /// Store open mode. None = auto, Some(false) = require writable,
    /// Some(true) = force read-only.
    pub(crate) read_only: Option<bool>,
}

impl Default for StoreConfig {
    fn default() -> Self {
        Self {
            flush_interval: Duration::from_secs(15),
            idle_timeout: Duration::from_secs(1800), // 30 min
            data_segment_size: 64 * 1024 * 1024,     // 64 MiB
            index_segment_size: 4 * 1024 * 1024,     // 4 MiB
            initial_data_segment_size: 256 * 1024,   // 256 KiB
            initial_index_segment_size: 4 * 1024,    // 4 KiB
            compress_level: 6,
            compress_type: COMPRESS_TYPE_ZSTD,
            cache_max_memory: 256 * 1024 * 1024, // 256 MiB
            cache_idle_timeout: Duration::from_secs(1800), // 30 min
            retention_check_hour: 0,             // UTC 00:00
            enable_background_thread: true,      // default: auto thread
            enable_journal: true,                // default: change log enabled
            read_only: None,                     // default: auto lock detection
        }
    }
}

impl StoreConfig {
    /// Create a new builder.
    pub fn builder() -> StoreConfigBuilder {
        StoreConfigBuilder::default()
    }

    pub fn flush_interval(&self) -> Duration {
        self.flush_interval
    }

    pub fn idle_timeout(&self) -> Duration {
        self.idle_timeout
    }

    pub fn data_segment_size(&self) -> u64 {
        self.data_segment_size
    }

    pub fn index_segment_size(&self) -> u64 {
        self.index_segment_size
    }

    pub fn initial_data_segment_size(&self) -> u64 {
        self.initial_data_segment_size
    }

    pub fn initial_index_segment_size(&self) -> u64 {
        self.initial_index_segment_size
    }

    pub fn compress_level(&self) -> u8 {
        self.compress_level
    }

    pub fn compress_type(&self) -> u8 {
        self.compress_type
    }

    pub fn cache_max_memory(&self) -> usize {
        self.cache_max_memory
    }

    pub fn cache_idle_timeout(&self) -> Duration {
        self.cache_idle_timeout
    }

    pub fn retention_check_hour(&self) -> u8 {
        self.retention_check_hour
    }

    pub fn enable_background_thread(&self) -> bool {
        self.enable_background_thread
    }

    pub fn enable_journal(&self) -> bool {
        self.enable_journal
    }

    pub fn read_only(&self) -> Option<bool> {
        self.read_only
    }

    pub(crate) fn validate(&self) -> Result<()> {
        validate_dataset_config_values(
            self.data_segment_size,
            self.index_segment_size,
            self.compress_level,
            self.compress_type,
            0,
            self.initial_data_segment_size,
            self.initial_index_segment_size,
            0,
        )?;
        if self.retention_check_hour > 23 {
            return Err(TmslError::InvalidData(format!(
                "retention_check_hour must be <= 23, got {}",
                self.retention_check_hour
            )));
        }
        Ok(())
    }
}

/// Builder for `StoreConfig`.
#[derive(Clone, Debug, Default)]
pub struct StoreConfigBuilder {
    flush_interval: Option<Duration>,
    idle_timeout: Option<Duration>,
    data_segment_size: Option<u64>,
    index_segment_size: Option<u64>,
    initial_data_segment_size: Option<u64>,
    initial_index_segment_size: Option<u64>,
    compress_level: Option<u8>,
    compress_type: Option<u8>,
    cache_max_memory: Option<usize>,
    cache_idle_timeout: Option<Duration>,
    retention_check_hour: Option<u8>,
    enable_background_thread: Option<bool>,
    enable_journal: Option<bool>,
    read_only: Option<Option<bool>>,
}

impl StoreConfigBuilder {
    /// Set the flush interval (mmap sync only, no seal/compress).
    pub fn flush_interval(mut self, interval: Duration) -> Self {
        self.flush_interval = Some(interval);
        self
    }

    /// Set the idle timeout for segment auto-close.
    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
        self.idle_timeout = Some(timeout);
        self
    }

    /// Set the data segment file size.
    pub fn data_segment_size(mut self, size: u64) -> Self {
        self.data_segment_size = Some(size);
        self
    }

    /// Set the index segment file size (max/expansion limit).
    pub fn index_segment_size(mut self, size: u64) -> Self {
        self.index_segment_size = Some(size);
        self
    }

    /// Set the initial data segment file size (expanded up to data_segment_size).
    pub fn initial_data_segment_size(mut self, size: u64) -> Self {
        self.initial_data_segment_size = Some(size);
        self
    }

    /// Set the initial index segment file size (expanded up to index_segment_size).
    pub fn initial_index_segment_size(mut self, size: u64) -> Self {
        self.initial_index_segment_size = Some(size);
        self
    }

    /// Set the compression level (0-9, interpreted by the selected algorithm).
    pub fn compress_level(mut self, level: u8) -> Self {
        self.compress_level = Some(level.min(9));
        self
    }

    /// Set the compression algorithm (0=zstd, 1=deflate).
    pub fn compress_type(mut self, compress_type: u8) -> Self {
        self.compress_type = Some(compress_type);
        self
    }

    /// Set the maximum memory for the read block cache (bytes, 0 = disabled).
    pub fn cache_max_memory(mut self, size: usize) -> Self {
        self.cache_max_memory = Some(size);
        self
    }

    /// Set the idle timeout for cache entries.
    pub fn cache_idle_timeout(mut self, timeout: Duration) -> Self {
        self.cache_idle_timeout = Some(timeout);
        self
    }

    /// Set the daily retention reclamation UTC hour (0-23, default 0 = UTC 00:00).
    pub fn retention_check_hour(mut self, hour: u8) -> Self {
        self.retention_check_hour = Some(hour.clamp(0, 23));
        self
    }

    /// Whether to launch a background thread (default true).
    ///
    /// When `false`, callers must invoke `Store::tick_background_tasks()` periodically
    /// to drive flush, idle-close, cache eviction, and retention reclaim.
    pub fn enable_background_thread(mut self, enable: bool) -> Self {
        self.enable_background_thread = Some(enable);
        self
    }

    /// Whether to enable the built-in `.journal/logs` change log (default true).
    pub fn enable_journal(mut self, enable: bool) -> Self {
        self.enable_journal = Some(enable);
        self
    }

    /// Set the Store read-only mode.
    ///
    /// - `None`: auto-detect. Open writable when the Store lock is free,
    ///   otherwise open read-only.
    /// - `Some(false)`: require writable Store lock.
    /// - `Some(true)`: force read-only without checking or taking the Store lock.
    pub fn read_only(mut self, read_only: Option<bool>) -> Self {
        self.read_only = Some(read_only);
        self
    }

    /// Build the `StoreConfig`.
    pub fn build(self) -> StoreConfig {
        let defaults = StoreConfig::default();
        StoreConfig {
            flush_interval: self.flush_interval.unwrap_or(defaults.flush_interval),
            idle_timeout: self.idle_timeout.unwrap_or(defaults.idle_timeout),
            data_segment_size: self.data_segment_size.unwrap_or(defaults.data_segment_size),
            index_segment_size: self
                .index_segment_size
                .unwrap_or(defaults.index_segment_size),
            initial_data_segment_size: self
                .initial_data_segment_size
                .unwrap_or(defaults.initial_data_segment_size),
            initial_index_segment_size: self
                .initial_index_segment_size
                .unwrap_or(defaults.initial_index_segment_size),
            compress_level: self.compress_level.unwrap_or(defaults.compress_level),
            compress_type: self.compress_type.unwrap_or(defaults.compress_type),
            cache_max_memory: self.cache_max_memory.unwrap_or(defaults.cache_max_memory),
            cache_idle_timeout: self
                .cache_idle_timeout
                .unwrap_or(defaults.cache_idle_timeout),
            retention_check_hour: self
                .retention_check_hour
                .unwrap_or(defaults.retention_check_hour),
            enable_background_thread: self
                .enable_background_thread
                .unwrap_or(defaults.enable_background_thread),
            enable_journal: self.enable_journal.unwrap_or(defaults.enable_journal),
            read_only: self.read_only.unwrap_or(defaults.read_only),
        }
    }
}

/// Dataset-level creation/open configuration.
#[derive(Clone, Debug)]
pub struct DataSetConfig {
    pub(crate) data_segment_size: u64,
    pub(crate) index_segment_size: u64,
    pub(crate) compress_level: u8,
    pub(crate) compress_type: u8,
    pub(crate) index_continuous: u8,
    pub(crate) initial_data_segment_size: u64,
    pub(crate) initial_index_segment_size: u64,
    /// Data validity period in same unit as timestamps. 0 = no limit.
    pub(crate) retention_window: u64,
    /// Whether this dataset records journal entries when the Store journal is enabled.
    pub(crate) enable_journal: bool,
    /// Dataset creation time (Unix milliseconds).
    pub(crate) create_time: i64,
}

#[allow(dead_code)]
impl DataSetConfig {
    pub fn from_store(config: &StoreConfig) -> Self {
        Self {
            data_segment_size: config.data_segment_size,
            index_segment_size: config.index_segment_size,
            compress_level: config.compress_level,
            compress_type: config.compress_type,
            index_continuous: 0,
            initial_data_segment_size: config.initial_data_segment_size,
            initial_index_segment_size: config.initial_index_segment_size,
            retention_window: 0,
            enable_journal: true,
            create_time: 0,
        }
    }

    /// Create a new builder.
    pub fn builder() -> DataSetConfigBuilder {
        DataSetConfigBuilder::default()
    }

    pub fn data_segment_size(&self) -> u64 {
        self.data_segment_size
    }

    pub fn index_segment_size(&self) -> u64 {
        self.index_segment_size
    }

    pub fn compress_level(&self) -> u8 {
        self.compress_level
    }

    pub fn compress_type(&self) -> u8 {
        self.compress_type
    }

    pub fn index_continuous(&self) -> u8 {
        self.index_continuous
    }

    pub fn initial_data_segment_size(&self) -> u64 {
        self.initial_data_segment_size
    }

    pub fn initial_index_segment_size(&self) -> u64 {
        self.initial_index_segment_size
    }

    pub fn retention_window(&self) -> u64 {
        self.retention_window
    }

    pub fn enable_journal(&self) -> bool {
        self.enable_journal
    }

    pub fn create_time(&self) -> i64 {
        self.create_time
    }

    pub(crate) fn validate(&self) -> Result<()> {
        validate_dataset_config_values(
            self.data_segment_size,
            self.index_segment_size,
            self.compress_level,
            self.compress_type,
            self.index_continuous,
            self.initial_data_segment_size,
            self.initial_index_segment_size,
            self.retention_window,
        )
    }
}

/// Builder for `DataSetConfig`.
///
/// Use `DataSetConfigBuilder::from_store(store_config)` to pre-fill with store-level defaults,
/// then override specific fields. Unset fields inherit store defaults; `index_continuous` defaults to 0.
///
/// # Example
/// ```ignore
/// let config = StoreConfig::default();
/// let mut store = Store::open("/data/timslite", config)?;
///
/// // Use store defaults for everything
/// store.create_dataset_with_config("sensor", "temp", None)?;
///
/// // Override specific fields
/// store.create_dataset_with_config("sensor", "temp", Some(
///     DataSetConfigBuilder::from_store(&config)
///         .compress_level(9)
///         .index_continuous(1)
/// ))?;
/// ```
#[derive(Clone, Debug, Default)]
pub struct DataSetConfigBuilder {
    data_segment_size: Option<u64>,
    index_segment_size: Option<u64>,
    compress_level: Option<u8>,
    compress_type: Option<u8>,
    index_continuous: Option<u8>,
    initial_data_segment_size: Option<u64>,
    initial_index_segment_size: Option<u64>,
    retention_window: Option<u64>,
    enable_journal: Option<bool>,
}

impl DataSetConfigBuilder {
    /// Create a builder pre-filled with store-level defaults.
    /// Unset fields will fall back to the store config; `index_continuous` defaults to 0.
    pub fn from_store(store: &StoreConfig) -> Self {
        Self {
            data_segment_size: Some(store.data_segment_size),
            index_segment_size: Some(store.index_segment_size),
            compress_level: Some(store.compress_level),
            compress_type: Some(store.compress_type),
            index_continuous: Some(0),
            initial_data_segment_size: Some(store.initial_data_segment_size),
            initial_index_segment_size: Some(store.initial_index_segment_size),
            retention_window: Some(0),
            enable_journal: Some(true),
        }
    }

    /// Set the data segment file size.
    pub fn data_segment_size(mut self, size: u64) -> Self {
        self.data_segment_size = Some(size);
        self
    }

    /// Set the index segment file size.
    pub fn index_segment_size(mut self, size: u64) -> Self {
        self.index_segment_size = Some(size);
        self
    }

    /// Set the compression level (0-9, interpreted by the selected algorithm).
    pub fn compress_level(mut self, level: u8) -> Self {
        self.compress_level = Some(level.min(9));
        self
    }

    /// Set the compression algorithm (0=zstd, 1=deflate).
    pub fn compress_type(mut self, compress_type: u8) -> Self {
        self.compress_type = Some(compress_type);
        self
    }

    /// Sets the index_continuous flag (0=non-continuous, 1=continuous storage).
    pub fn index_continuous(mut self, value: u8) -> Self {
        self.index_continuous = Some(value.clamp(0, 1));
        self
    }

    /// Set the initial data segment file size.
    pub fn initial_data_segment_size(mut self, size: u64) -> Self {
        self.initial_data_segment_size = Some(size);
        self
    }

    /// Set the initial index segment file size.
    pub fn initial_index_segment_size(mut self, size: u64) -> Self {
        self.initial_index_segment_size = Some(size);
        self
    }

    /// Set the data retention period in timestamp units (0 = no limit).
    pub fn retention_window(mut self, units: u64) -> Self {
        self.retention_window = Some(units);
        self
    }

    /// Set whether this dataset records journal entries when the Store journal is enabled.
    pub fn enable_journal(mut self, enable: bool) -> Self {
        self.enable_journal = Some(enable);
        self
    }

    /// Build the `DataSetConfig`.
    pub fn build(self) -> Result<DataSetConfig> {
        let defaults = DataSetConfig::from_store(&StoreConfig::default());
        let retention_window = self.retention_window.unwrap_or(0);
        validate_retention_window(retention_window)?;
        let config = DataSetConfig {
            data_segment_size: self.data_segment_size.unwrap_or(defaults.data_segment_size),
            index_segment_size: self
                .index_segment_size
                .unwrap_or(defaults.index_segment_size),
            compress_level: self.compress_level.unwrap_or(defaults.compress_level),
            compress_type: self.compress_type.unwrap_or(defaults.compress_type),
            index_continuous: self.index_continuous.unwrap_or(0),
            initial_data_segment_size: self
                .initial_data_segment_size
                .unwrap_or(defaults.initial_data_segment_size),
            initial_index_segment_size: self
                .initial_index_segment_size
                .unwrap_or(defaults.initial_index_segment_size),
            retention_window,
            enable_journal: self.enable_journal.unwrap_or(true),
            create_time: 0, // Set at dataset creation
        };
        config.validate()?;
        Ok(config)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let cfg = StoreConfig::default();
        assert_eq!(cfg.flush_interval, Duration::from_secs(15));
        assert_eq!(cfg.idle_timeout, Duration::from_secs(1800));
        assert_eq!(cfg.data_segment_size, 64 * 1024 * 1024);
        assert_eq!(cfg.index_segment_size, 4 * 1024 * 1024);
        assert_eq!(cfg.initial_data_segment_size, 256 * 1024);
        assert_eq!(cfg.initial_index_segment_size, 4 * 1024);
        assert_eq!(cfg.compress_level, 6);
        assert_eq!(cfg.compress_type, crate::compress::COMPRESS_TYPE_ZSTD);
        assert_eq!(cfg.cache_max_memory, 256 * 1024 * 1024);
        assert_eq!(cfg.cache_idle_timeout, Duration::from_secs(1800));
        assert_eq!(cfg.retention_check_hour, 0);
        assert!(cfg.enable_background_thread);
        assert!(cfg.enable_journal);
    }

    #[test]
    fn test_builder_all_fields() {
        let cfg = StoreConfig::builder()
            .flush_interval(Duration::from_secs(1200))
            .idle_timeout(Duration::from_secs(3600))
            .data_segment_size(128 * 1024 * 1024)
            .index_segment_size(8 * 1024 * 1024)
            .initial_data_segment_size(512 * 1024)
            .initial_index_segment_size(8 * 1024)
            .compress_level(9)
            .cache_max_memory(128 * 1024 * 1024)
            .cache_idle_timeout(Duration::from_secs(600))
            .retention_check_hour(2)
            .enable_journal(false)
            .build();

        assert_eq!(cfg.flush_interval, Duration::from_secs(1200));
        assert_eq!(cfg.idle_timeout, Duration::from_secs(3600));
        assert_eq!(cfg.data_segment_size, 128 * 1024 * 1024);
        assert_eq!(cfg.index_segment_size, 8 * 1024 * 1024);
        assert_eq!(cfg.initial_data_segment_size, 512 * 1024);
        assert_eq!(cfg.initial_index_segment_size, 8 * 1024);
        assert_eq!(cfg.compress_level, 9);
        assert_eq!(cfg.cache_max_memory, 128 * 1024 * 1024);
        assert_eq!(cfg.cache_idle_timeout, Duration::from_secs(600));
        assert_eq!(cfg.retention_check_hour, 2);
        assert!(!cfg.enable_journal);
    }

    #[test]
    fn test_builder_partial() {
        let cfg = StoreConfig::builder()
            .flush_interval(Duration::from_secs(300))
            .build();

        let defaults = StoreConfig::default();
        assert_eq!(cfg.flush_interval, Duration::from_secs(300));
        assert_eq!(cfg.idle_timeout, defaults.idle_timeout);
        assert_eq!(cfg.retention_check_hour, defaults.retention_check_hour);
    }

    #[test]
    fn test_builder_compress_level_cap() {
        let cfg = StoreConfig::builder().compress_level(15).build();
        assert_eq!(cfg.compress_level, 9); // capped at 9
    }

    #[test]
    fn test_builder_retention_check_hour_clamp() {
        let cfg = StoreConfig::builder().retention_check_hour(99).build();
        assert_eq!(cfg.retention_check_hour, 23);
        let cfg2 = StoreConfig::builder().retention_check_hour(12).build();
        assert_eq!(cfg2.retention_check_hour, 12);
    }

    #[test]
    fn test_builder_disable_background_thread() {
        let cfg = StoreConfig::builder()
            .enable_background_thread(false)
            .build();
        assert!(!cfg.enable_background_thread);
        // default is true
        let default = StoreConfig::default();
        assert!(default.enable_background_thread);
    }

    #[test]
    fn test_builder_disable_journal() {
        let cfg = StoreConfig::builder().enable_journal(false).build();
        assert!(!cfg.enable_journal);
        assert!(StoreConfig::default().enable_journal);
    }

    #[test]
    fn test_dataset_config_from_store() {
        let store = StoreConfig::builder()
            .data_segment_size(32 * 1024 * 1024)
            .compress_level(3)
            .build();
        let dataset = DataSetConfig::from_store(&store);
        assert_eq!(dataset.data_segment_size, 32 * 1024 * 1024);
        assert_eq!(dataset.compress_level, 3);
        assert_eq!(dataset.retention_window, 0);
        assert!(dataset.enable_journal);
    }

    #[test]
    fn test_dataset_config_builder_from_store() {
        let store = StoreConfig::builder()
            .data_segment_size(32 * 1024 * 1024)
            .index_segment_size(8 * 1024 * 1024)
            .compress_level(3)
            .initial_data_segment_size(512 * 1024)
            .initial_index_segment_size(8 * 1024)
            .build();

        let config = DataSetConfigBuilder::from_store(&store).build().unwrap();
        assert_eq!(config.data_segment_size, 32 * 1024 * 1024);
        assert_eq!(config.index_segment_size, 8 * 1024 * 1024);
        assert_eq!(config.compress_level, 3);
        assert_eq!(config.index_continuous, 0);
        assert_eq!(config.initial_data_segment_size, 512 * 1024);
        assert_eq!(config.initial_index_segment_size, 8 * 1024);
        assert_eq!(config.retention_window, 0);
        assert!(config.enable_journal);
    }

    #[test]
    fn test_dataset_config_builder_from_store_with_overrides() {
        let store = StoreConfig::builder()
            .data_segment_size(64 * 1024 * 1024)
            .compress_level(6)
            .build();

        let config = DataSetConfigBuilder::from_store(&store)
            .compress_level(9)
            .index_continuous(1)
            .retention_window(30 * 86400)
            .enable_journal(false)
            .build()
            .unwrap();

        // Override takes effect
        assert_eq!(config.compress_level, 9);
        assert_eq!(config.index_continuous, 1);
        assert_eq!(config.retention_window, 30 * 86400);
        assert!(!config.enable_journal);
        // Store default is inherited
        assert_eq!(config.data_segment_size, 64 * 1024 * 1024);
    }

    #[test]
    fn test_dataset_config_builder_retention_window() {
        let config = DataSetConfigBuilder::default()
            .retention_window(30)
            .build()
            .unwrap();

        assert_eq!(config.retention_window, 30);
    }

    #[test]
    fn test_dataset_config_builder_rejects_retention_above_i64_max() {
        let result = DataSetConfigBuilder::default()
            .retention_window(i64::MAX as u64 + 1)
            .build();

        assert!(result.is_err());
    }
}