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
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
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
//! Store: facade that manages all datasets and background tasks.

use std::collections::{HashMap, HashSet};
use std::fs;
use std::fs::{File, OpenOptions};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;

use crate::bg::BackgroundTasks;
use crate::bg::TickResult;
use crate::cache::BlockCache;
use crate::config::{DataSetConfigBuilder, StoreConfig};
use crate::dataset::{
    DataSet, DataSetInspectResult, DataSetJournalSink, DataSetKey, DataSetLifecycleSink,
    DataSetRuntimeContext, SegmentFlushQueue,
};
use crate::error::{Result, TmslError};
use crate::index::segment::IndexEntry;
use crate::journal::{
    meta_values_from_file, validate_create_drop_record_inputs, JournalIndexInfo, JournalManager,
    JournalQueue, JOURNAL_DATASET_NAME, JOURNAL_DATASET_TYPE,
};
use crate::meta::META_VALUES_LEN_V1;
use crate::queue::{DatasetQueue, DatasetQueueConsumer, QueueConsumerConfig};
use crate::util::{is_path_safe_component, PATH_COMPONENT_MAX_LEN};

const MAX_IDENTIFIER_FILE: &str = "max_identifier";
const DATASET_IDENTIFIER_FILE: &str = "identifier";
const STORE_LOCK_FILE: &str = ".lock";

enum StoreLockAttempt {
    Acquired(File),
    Locked,
}

fn validate_dataset_component(label: &str, value: &str) -> Result<()> {
    if is_path_safe_component(value) {
        Ok(())
    } else {
        Err(TmslError::InvalidData(format!(
            "{label} must match ^[0-9A-Za-z_-]+$ and be at most {PATH_COMPONENT_MAX_LEN} bytes"
        )))
    }
}

fn validate_dataset_path_components(name: &str, dataset_type: &str) -> Result<()> {
    validate_dataset_component("dataset name", name)?;
    validate_dataset_component("dataset type", dataset_type)
}

fn parse_identifier_value(label: &str, content: &str, allow_zero: bool) -> Result<u64> {
    let value = content.trim();
    if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
        return Err(TmslError::InvalidData(format!(
            "{label} must be a decimal u64 string"
        )));
    }
    let identifier = value.parse::<u64>().map_err(|_| {
        TmslError::InvalidData(format!("{label} exceeds maximum u64 identifier value"))
    })?;
    if !allow_zero && identifier == 0 {
        return Err(TmslError::InvalidData(format!("{label} must be > 0")));
    }
    Ok(identifier)
}

fn read_identifier_file(path: &Path, label: &str, allow_zero: bool) -> Result<u64> {
    let content = std::fs::read_to_string(path)?;
    parse_identifier_value(label, &content, allow_zero)
}

fn read_max_identifier(data_dir: &Path) -> Result<u64> {
    let path = data_dir.join(MAX_IDENTIFIER_FILE);
    match std::fs::read_to_string(&path) {
        Ok(content) => parse_identifier_value(MAX_IDENTIFIER_FILE, &content, true),
        Err(err) if err.kind() == ErrorKind::NotFound => Ok(0),
        Err(err) => Err(err.into()),
    }
}

fn write_identifier_file(path: &Path, identifier: u64) -> Result<()> {
    std::fs::write(path, identifier.to_string())?;
    Ok(())
}

fn dataset_identifier_path(dataset_dir: &Path) -> PathBuf {
    dataset_dir.join(DATASET_IDENTIFIER_FILE)
}

fn read_dataset_identifier(dataset_dir: &Path) -> Result<u64> {
    let path = dataset_identifier_path(dataset_dir);
    match read_identifier_file(&path, DATASET_IDENTIFIER_FILE, false) {
        Err(TmslError::Io(err)) if err.kind() == ErrorKind::NotFound => Err(TmslError::NotFound(
            format!("dataset identifier not found at {:?}", path),
        )),
        other => other,
    }
}

/// Opaque handle for FFI consumers.
#[derive(Clone, Copy)]
pub struct DataSetHandle(pub u64);

#[derive(Clone)]
struct DataSetHandleEntry {
    key: DataSetKey,
    generation: u64,
}

fn try_acquire_store_lock(data_dir: &Path) -> Result<StoreLockAttempt> {
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(data_dir.join(STORE_LOCK_FILE))?;
    match file.try_lock() {
        Ok(()) => Ok(StoreLockAttempt::Acquired(file)),
        Err(fs::TryLockError::WouldBlock) => Ok(StoreLockAttempt::Locked),
        Err(fs::TryLockError::Error(err)) => Err(err.into()),
    }
}

struct StoreDatasetLifecycle {
    datasets: Arc<RwLock<HashMap<DataSetKey, Arc<DataSet>>>>,
    generations: Mutex<HashMap<DataSetKey, u64>>,
}

impl StoreDatasetLifecycle {
    fn new(datasets: Arc<RwLock<HashMap<DataSetKey, Arc<DataSet>>>>) -> Self {
        Self {
            datasets,
            generations: Mutex::new(HashMap::new()),
        }
    }

    fn generation(&self, key: &DataSetKey) -> Result<u64> {
        let guard = self
            .generations
            .lock()
            .map_err(|_| TmslError::InvalidData("dataset generation mutex poisoned".into()))?;
        Ok(*guard.get(key).unwrap_or(&0))
    }

    fn invalidate(&self, key: &DataSetKey) {
        if let Ok(mut datasets) = self.datasets.write() {
            datasets.remove(key);
        }
        if let Ok(mut generations) = self.generations.lock() {
            let generation = generations.entry(key.clone()).or_insert(0);
            *generation = generation.saturating_add(1);
        }
    }
}

impl DataSetLifecycleSink for StoreDatasetLifecycle {
    fn dataset_closed(&self, key: &DataSetKey) {
        self.invalidate(key);
    }
}

/// The Store: top-level facade for managing datasets.
pub struct Store {
    data_dir: PathBuf,
    datasets: Arc<RwLock<HashMap<DataSetKey, Arc<DataSet>>>>,
    lifecycle: Arc<StoreDatasetLifecycle>,
    config: StoreConfig,
    block_cache: Arc<BlockCache>,
    journal: Arc<JournalManager>,
    bg_tasks: Option<BackgroundTasks>,
    max_identifier: u64,
    identifier_to_key: HashMap<u64, DataSetKey>,
    next_handle_id: u64,
    handles: HashMap<u64, DataSetHandleEntry>,
    read_only_handles: HashSet<u64>,
    read_only: bool,
    store_lock: Option<File>,
}

impl Store {
    fn dataset_runtime_context(
        block_cache: &Arc<BlockCache>,
        journal: &Arc<JournalManager>,
        flush_queue: Option<&SegmentFlushQueue>,
        lifecycle: &Arc<StoreDatasetLifecycle>,
        enable_journal: bool,
        read_only: bool,
    ) -> Result<DataSetRuntimeContext> {
        let journal_sink: Option<Arc<dyn DataSetJournalSink>> =
            if !read_only && enable_journal && journal.is_enabled() {
                let sink: Arc<dyn DataSetJournalSink> = journal.clone();
                Some(sink)
            } else {
                None
            };
        let flush_queue = if read_only {
            None
        } else {
            Some(Arc::clone(flush_queue.ok_or_else(|| {
                TmslError::InvalidData("bg_tasks not initialised".into())
            })?))
        };
        let lifecycle_sink: Arc<dyn DataSetLifecycleSink> = lifecycle.clone();
        let context =
            DataSetRuntimeContext::new(Some(Arc::clone(block_cache)), journal_sink, flush_queue)
                .with_lifecycle(lifecycle_sink);
        Ok(if read_only {
            context.with_read_only()
        } else {
            context
        })
    }

    fn ensure_writable(&self, action: &str) -> Result<()> {
        if self.read_only {
            return Err(TmslError::InvalidData(format!(
                "read-only store cannot {action}"
            )));
        }
        Ok(())
    }

    fn dataset_dir(&self, key: &DataSetKey) -> PathBuf {
        self.data_dir.join(&key.name).join(&key.dataset_type)
    }

    fn handle_for_key(&mut self, key: DataSetKey) -> Result<DataSetHandle> {
        let id = self.next_handle_id;
        self.next_handle_id += 1;
        let generation = self.lifecycle.generation(&key)?;
        self.handles
            .insert(id, DataSetHandleEntry { key, generation });
        Ok(DataSetHandle(id))
    }

    fn handle_entry(&self, handle: DataSetHandle) -> Result<DataSetHandleEntry> {
        let entry = self
            .handles
            .get(&handle.0)
            .ok_or_else(|| TmslError::NotFound("dataset handle not found".into()))?
            .clone();
        let generation = self.lifecycle.generation(&entry.key)?;
        if generation != entry.generation {
            return Err(TmslError::NotFound("dataset handle is closed".into()));
        }
        Ok(entry)
    }

    fn validate_identifier_within_max(&self, identifier: u64, key: &DataSetKey) -> Result<()> {
        if identifier > self.max_identifier {
            return Err(TmslError::InvalidData(format!(
                "dataset {:?} identifier {identifier} exceeds authoritative max_identifier {}",
                key, self.max_identifier
            )));
        }
        Ok(())
    }

    fn scan_dataset_dirs(&self) -> Result<Vec<(DataSetKey, PathBuf)>> {
        let mut out = Vec::new();
        for entry in std::fs::read_dir(&self.data_dir)? {
            let path = entry?.path();
            if !path.is_dir() {
                continue;
            }
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if name == JOURNAL_DATASET_NAME || !is_path_safe_component(name) {
                continue;
            }
            for type_entry in std::fs::read_dir(&path)? {
                let type_path = type_entry?.path();
                if !type_path.is_dir() {
                    continue;
                }
                let Some(type_name) = type_path.file_name().and_then(|n| n.to_str()) else {
                    continue;
                };
                if !is_path_safe_component(type_name) {
                    continue;
                }
                out.push((
                    DataSetKey {
                        name: name.to_string(),
                        dataset_type: type_name.to_string(),
                    },
                    type_path,
                ));
            }
        }
        out.sort_by(|(a, _), (b, _)| {
            a.name
                .cmp(&b.name)
                .then_with(|| a.dataset_type.cmp(&b.dataset_type))
        });
        Ok(out)
    }

    fn find_key_by_identifier(&mut self, identifier: u64) -> Result<DataSetKey> {
        if identifier == 0 {
            return Err(TmslError::InvalidData(
                "dataset identifier must be > 0".into(),
            ));
        }
        if let Some(key) = self.identifier_to_key.get(&identifier).cloned() {
            return Ok(key);
        }

        let mut found: Option<DataSetKey> = None;
        for (key, dir) in self.scan_dataset_dirs()? {
            if !dir.join("meta").exists() || !dataset_identifier_path(&dir).exists() {
                continue;
            }
            let current = read_dataset_identifier(&dir)?;
            self.validate_identifier_within_max(current, &key)?;
            if current != identifier {
                continue;
            }
            if let Some(existing) = found.as_ref() {
                if existing != &key {
                    return Err(TmslError::InvalidData(format!(
                        "duplicate dataset identifier {identifier}: {:?} and {:?}",
                        existing, key
                    )));
                }
            }
            found = Some(key);
        }

        let key =
            found.ok_or_else(|| TmslError::NotFound(format!("dataset identifier {identifier}")))?;
        self.identifier_to_key.insert(identifier, key.clone());
        Ok(key)
    }

    /// Open a store at the given directory.
    pub fn open<P: AsRef<Path>>(data_dir: P, config: StoreConfig) -> Result<Self> {
        config.validate()?;
        let data_dir = data_dir.as_ref().to_path_buf();
        let (read_only, store_lock) = match config.read_only {
            Some(true) => (true, None),
            Some(false) => {
                std::fs::create_dir_all(&data_dir)?;
                match try_acquire_store_lock(&data_dir)? {
                    StoreLockAttempt::Acquired(file) => (false, Some(file)),
                    StoreLockAttempt::Locked => {
                        return Err(TmslError::InvalidData(
                            "store is already locked for writing".into(),
                        ));
                    }
                }
            }
            None => {
                std::fs::create_dir_all(&data_dir)?;
                match try_acquire_store_lock(&data_dir)? {
                    StoreLockAttempt::Acquired(file) => (false, Some(file)),
                    StoreLockAttempt::Locked => (true, None),
                }
            }
        };
        let block_cache = Arc::new(BlockCache::new(config.cache_max_memory));
        let flush_queue = DataSetRuntimeContext::new_flush_queue();
        let journal = Arc::new(if read_only {
            JournalManager::open_read_only(&data_dir, &config)?
        } else {
            JournalManager::open_or_create(&data_dir, &config, Some(Arc::clone(&flush_queue)))?
        });
        let max_identifier = read_max_identifier(&data_dir)?;
        let identifier_to_key: HashMap<u64, DataSetKey> = HashMap::new();
        let datasets = Arc::new(RwLock::new(HashMap::new()));
        let lifecycle = Arc::new(StoreDatasetLifecycle::new(Arc::clone(&datasets)));

        let mut store = Self {
            data_dir,
            datasets: Arc::clone(&datasets),
            lifecycle,
            config: config.clone(),
            block_cache: Arc::clone(&block_cache),
            journal: Arc::clone(&journal),
            bg_tasks: None,
            max_identifier,
            identifier_to_key,
            next_handle_id: 0,
            handles: HashMap::new(),
            read_only_handles: HashSet::new(),
            read_only,
            store_lock,
        };

        // Start background tasks (or just the executor)
        if read_only {
            log::info!("[store] opened in read-only mode, background tasks disabled");
        } else if config.enable_background_thread {
            store.bg_tasks = Some(BackgroundTasks::start(
                datasets,
                Arc::clone(&flush_queue),
                Arc::clone(&journal),
                block_cache,
                config.flush_interval,
                config.idle_timeout,
                config.cache_idle_timeout,
                config.retention_check_hour,
            ));
        } else {
            store.bg_tasks = Some(BackgroundTasks::new(
                datasets,
                Arc::clone(&flush_queue),
                Arc::clone(&journal),
                block_cache,
                config.flush_interval,
                config.idle_timeout,
                config.cache_idle_timeout,
                config.retention_check_hour,
            ));
            log::info!("[store] background thread disabled, manual tick required");
        }

        Ok(store)
    }

    /// Create a new dataset using a builder with store-level defaults.
    ///
    /// When `config_builder` is `None`, all parameters inherit store defaults
    /// and `index_continuous` defaults to 0.
    pub fn create_dataset_with_config(
        &mut self,
        name: &str,
        dataset_type: &str,
        config_builder: Option<DataSetConfigBuilder>,
    ) -> Result<DataSetHandle> {
        self.ensure_writable("create dataset")?;
        if name == JOURNAL_DATASET_NAME && dataset_type == JOURNAL_DATASET_TYPE {
            return Err(TmslError::InvalidData("journal dataset is reserved".into()));
        }
        validate_dataset_path_components(name, dataset_type)?;

        let key = DataSetKey {
            name: name.to_string(),
            dataset_type: dataset_type.to_string(),
        };

        let dir = self.dataset_dir(&key);

        // Check if already open or already present on disk.
        {
            let guard = self.datasets.read().unwrap();
            if guard.contains_key(&key) {
                return Err(TmslError::AlreadyExists(format!(
                    "dataset {}/{} is already open",
                    name, dataset_type
                )));
            }
        }
        if dir.join("meta").exists() {
            return Err(TmslError::AlreadyExists(format!(
                "dataset already exists at {:?}",
                dir
            )));
        }

        let config = config_builder
            .unwrap_or_else(|| DataSetConfigBuilder::from_store(&self.config))
            .build()?;
        let effective_journal = self.journal.is_enabled() && config.enable_journal;
        let identifier = self
            .max_identifier
            .checked_add(1)
            .ok_or_else(|| TmslError::InvalidData("dataset identifier overflow".into()))?;
        if effective_journal {
            validate_create_drop_record_inputs(identifier, &key, META_VALUES_LEN_V1)?;
        }
        write_identifier_file(&self.data_dir.join(MAX_IDENTIFIER_FILE), identifier)?;
        self.max_identifier = identifier;

        // Create new dataset
        let ds = DataSet::create_with_compression(
            key.clone(),
            dir.clone(),
            config.data_segment_size,
            config.index_segment_size,
            config.compress_level,
            config.compress_type,
            config.index_continuous,
            config.initial_data_segment_size,
            config.initial_index_segment_size,
            config.retention_window,
            config.enable_journal,
        )?;
        write_identifier_file(&dataset_identifier_path(&dir), identifier)?;
        ds.set_identifier(identifier)?;
        ds.set_runtime_context(Self::dataset_runtime_context(
            &self.block_cache,
            &self.journal,
            self.bg_tasks.as_ref().map(|bg| bg.flush_queue()),
            &self.lifecycle,
            config.enable_journal,
            self.read_only,
        )?)?;

        let ds = Arc::new(ds);
        {
            let mut guard = self.datasets.write().unwrap();
            guard.insert(key.clone(), ds);
        }
        self.identifier_to_key.insert(identifier, key.clone());

        let metadata =
            meta_values_from_file(&self.data_dir.join(name).join(dataset_type).join("meta"))?;
        if effective_journal {
            self.journal.append_create(identifier, &key, &metadata)?;
        }

        self.handle_for_key(key)
    }

    /// Create a new dataset (explicit, errors if already exists).
    ///
    /// Backward-compatible wrapper around `create_dataset_with_config`.
    pub fn create_dataset(
        &mut self,
        name: &str,
        dataset_type: &str,
        data_segment_size: u64,
        index_segment_size: u64,
        compress_level: u8,
        index_continuous: u8,
        retention_window: u64,
    ) -> Result<DataSetHandle> {
        self.create_dataset_with_config(
            name,
            dataset_type,
            Some(
                DataSetConfigBuilder::from_store(&self.config)
                    .data_segment_size(data_segment_size)
                    .index_segment_size(index_segment_size)
                    .compress_level(compress_level)
                    .index_continuous(index_continuous)
                    .retention_window(retention_window),
            ),
        )
    }

    /// Open an existing dataset (errors if not found).
    pub fn open_dataset(&mut self, name: &str, dataset_type: &str) -> Result<DataSetHandle> {
        if name == JOURNAL_DATASET_NAME && dataset_type == JOURNAL_DATASET_TYPE {
            return Err(TmslError::NotFound(
                "journal is not exposed as a dataset handle".into(),
            ));
        }
        validate_dataset_path_components(name, dataset_type)?;

        let key = DataSetKey {
            name: name.to_string(),
            dataset_type: dataset_type.to_string(),
        };

        // Check if already open
        let already_open = {
            let guard = self.datasets.read().unwrap();
            guard.contains_key(&key)
        };
        if already_open {
            return self.handle_for_key(key.clone());
        }

        // Open existing dataset
        let dir = self.dataset_dir(&key);
        let identifier = read_dataset_identifier(&dir)?;
        self.validate_identifier_within_max(identifier, &key)?;
        if let Some(existing) = self.identifier_to_key.get(&identifier) {
            if existing != &key {
                return Err(TmslError::InvalidData(format!(
                    "duplicate dataset identifier {identifier}: {:?} and {:?}",
                    existing, key
                )));
            }
        }
        let ds = if self.read_only {
            DataSet::open_read_only(key.clone(), dir)?
        } else {
            DataSet::open(key.clone(), dir)?
        };
        ds.set_identifier(identifier)?;
        ds.set_runtime_context(Self::dataset_runtime_context(
            &self.block_cache,
            &self.journal,
            self.bg_tasks.as_ref().map(|bg| bg.flush_queue()),
            &self.lifecycle,
            ds.enable_journal(),
            self.read_only,
        )?)?;

        let ds = Arc::new(ds);
        {
            let mut guard = self.datasets.write().unwrap();
            guard.insert(key.clone(), ds);
        }
        self.identifier_to_key.insert(identifier, key.clone());
        self.handle_for_key(key)
    }

    /// Open an existing dataset by its Store-assigned numeric identifier.
    pub fn open_dataset_by_identifier(&mut self, identifier: u64) -> Result<DataSetHandle> {
        let key = self.find_key_by_identifier(identifier)?;
        self.open_dataset(&key.name, &key.dataset_type)
    }

    /// Return the Store-assigned numeric identifier for a dataset handle.
    pub fn dataset_identifier(&self, handle: DataSetHandle) -> Result<u64> {
        if self.read_only_handles.contains(&handle.0) {
            return Err(TmslError::InvalidData(
                "read-only internal dataset has no public identifier".into(),
            ));
        }
        let ds_arc = self.get_dataset(&handle)?;
        let identifier = ds_arc.identifier();
        if identifier == 0 {
            return Err(TmslError::InvalidData(
                "dataset has no public identifier".into(),
            ));
        }
        Ok(identifier)
    }

    /// Close a dataset by handle.
    pub fn close_dataset(&mut self, handle: DataSetHandle) -> Result<()> {
        if self.read_only_handles.remove(&handle.0) {
            self.handles.remove(&handle.0);
            return Ok(());
        }
        if let Some(entry) = self.handles.remove(&handle.0) {
            if self.handles.values().any(|existing| {
                existing.key == entry.key && existing.generation == entry.generation
            }) {
                return Ok(());
            }
            let ds_arc = {
                let mut guard = self.datasets.write().unwrap();
                guard.remove(&entry.key)
            };
            if let Some(ds_arc) = ds_arc {
                ds_arc.close()?;
            }
        }
        Ok(())
    }

    /// Drop (delete) an entire dataset by handle.
    pub fn drop_dataset(&mut self, handle: DataSetHandle) -> Result<()> {
        self.ensure_writable("drop dataset")?;
        if self.read_only_handles.contains(&handle.0) {
            return Err(TmslError::InvalidData(
                "read-only internal dataset cannot be dropped".into(),
            ));
        }
        let entry = self.handle_entry(handle)?;
        self.handles.remove(&handle.0);
        let key = entry.key;

        let ds_arc = {
            let mut guard = self.datasets.write().unwrap();
            guard
                .remove(&key)
                .ok_or_else(|| TmslError::NotFound(format!("dataset {:?} not found", key)))?
        };
        let (base_dir, identifier, metadata, effective_journal) = {
            let identifier = ds_arc.identifier();
            let base_dir = ds_arc.base_dir();
            let metadata = meta_values_from_file(&base_dir.join("meta"))?;
            let effective_journal = self.journal.is_enabled() && ds_arc.enable_journal();
            if effective_journal {
                validate_create_drop_record_inputs(identifier, &key, metadata.len())?;
            }
            ds_arc.close()?;
            (base_dir, identifier, metadata, effective_journal)
        };

        DataSet::drop_dataset(&base_dir)?;
        self.identifier_to_key
            .retain(|_, existing| existing != &key);
        self.handles.retain(|_, existing| existing.key != key);
        if effective_journal {
            self.journal.append_drop(identifier, &key, &metadata)?;
        }
        log::info!("[store] dropped dataset: {}/{}", key.name, key.dataset_type);
        Ok(())
    }

    /// Drop (delete) an entire dataset by name and type.
    pub fn drop_dataset_by_name(&mut self, name: &str, dataset_type: &str) -> Result<()> {
        self.ensure_writable("drop dataset")?;
        if name == JOURNAL_DATASET_NAME && dataset_type == JOURNAL_DATASET_TYPE {
            return Err(TmslError::InvalidData("journal dataset is reserved".into()));
        }
        validate_dataset_path_components(name, dataset_type)?;

        let key = DataSetKey {
            name: name.to_string(),
            dataset_type: dataset_type.to_string(),
        };

        let handle = self.open_dataset(name, dataset_type)?;
        let ds_arc = self.get_dataset(&handle)?;
        let base_dir = ds_arc.base_dir();
        let identifier = ds_arc.identifier();
        let metadata = meta_values_from_file(&base_dir.join("meta"))?;
        let effective_journal = self.journal.is_enabled() && ds_arc.enable_journal();
        if effective_journal {
            validate_create_drop_record_inputs(identifier, &key, metadata.len())?;
        }

        ds_arc.close()?;
        self.handles.retain(|_, existing| existing.key != key);

        DataSet::drop_dataset(&base_dir)?;
        self.identifier_to_key
            .retain(|_, existing| existing != &key);
        if effective_journal {
            self.journal.append_drop(identifier, &key, &metadata)?;
        }
        log::info!("[store] dropped dataset: {}/{}", name, dataset_type);
        Ok(())
    }

    /// Get a dataset handle for internal use.
    pub fn get_dataset(&self, handle: &DataSetHandle) -> Result<Arc<DataSet>> {
        let entry = self.handle_entry(*handle)?;
        let guard = self.datasets.read().unwrap();
        let ds = guard.get(&entry.key).ok_or_else(|| {
            crate::error::TmslError::NotFound(format!("dataset {:?} not found", entry.key))
        })?;
        Ok(Arc::clone(ds))
    }

    pub(crate) fn is_journal_handle(&self, handle: DataSetHandle) -> Result<bool> {
        let entry = self.handle_entry(handle)?;
        Ok(JournalManager::is_journal_key(&entry.key))
    }

    /// Write through the Store so journal and global cache hooks are applied.
    pub fn write_dataset(
        &mut self,
        handle: DataSetHandle,
        timestamp: i64,
        data: &[u8],
    ) -> Result<()> {
        self.ensure_writable("write dataset")?;
        let key = self.handle_entry(handle)?.key;
        if JournalManager::is_journal_key(&key) || self.read_only_handles.contains(&handle.0) {
            return Err(TmslError::InvalidData(
                "read-only internal dataset cannot be written".into(),
            ));
        }
        let ds_arc = {
            let guard = self.datasets.read().unwrap();
            guard
                .get(&key)
                .ok_or_else(|| TmslError::NotFound(format!("dataset {:?} not found", key)))?
                .clone()
        };
        ds_arc.write(timestamp, data)?;
        Ok(())
    }

    /// Append through the Store so journal and global cache hooks are applied.
    pub fn append_dataset(
        &mut self,
        handle: DataSetHandle,
        timestamp: i64,
        data: &[u8],
    ) -> Result<()> {
        self.ensure_writable("append dataset")?;
        let key = self.handle_entry(handle)?.key;
        if JournalManager::is_journal_key(&key) || self.read_only_handles.contains(&handle.0) {
            return Err(TmslError::InvalidData(
                "read-only internal dataset cannot be appended".into(),
            ));
        }
        let ds_arc = {
            let guard = self.datasets.read().unwrap();
            guard
                .get(&key)
                .ok_or_else(|| TmslError::NotFound(format!("dataset {:?} not found", key)))?
                .clone()
        };
        ds_arc.append(timestamp, data)?;
        Ok(())
    }

    /// Delete through the Store so journal and global cache hooks are applied.
    pub fn delete_dataset_record(&mut self, handle: DataSetHandle, timestamp: i64) -> Result<()> {
        self.ensure_writable("delete dataset record")?;
        let key = self.handle_entry(handle)?.key;
        if JournalManager::is_journal_key(&key) || self.read_only_handles.contains(&handle.0) {
            return Err(TmslError::InvalidData(
                "read-only internal dataset cannot be deleted".into(),
            ));
        }
        let ds_arc = {
            let guard = self.datasets.read().unwrap();
            guard
                .get(&key)
                .ok_or_else(|| TmslError::NotFound(format!("dataset {:?} not found", key)))?
                .clone()
        };
        ds_arc.delete(timestamp)?;
        Ok(())
    }

    /// Read through the Store so global cache and read-only internal handles are honored.
    pub fn read_dataset(
        &self,
        handle: DataSetHandle,
        timestamp: i64,
    ) -> Result<Option<(i64, Vec<u8>)>> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.read(timestamp)
    }

    /// Read the latest written timestamp's record through the Store.
    pub fn read_dataset_latest(&self, handle: DataSetHandle) -> Result<Option<(i64, Vec<u8>)>> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.read_latest()
    }

    /// Query through the Store so global cache and read-only internal handles are honored.
    pub fn query_dataset(
        &self,
        handle: DataSetHandle,
        start_ts: i64,
        end_ts: i64,
    ) -> Result<Vec<(i64, Vec<u8>)>> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.query(start_ts, end_ts)
    }

    /// Check if index entry exists for a timestamp.
    pub fn dataset_read_exist(&self, handle: DataSetHandle, timestamp: i64) -> Result<bool> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.read_exist(timestamp)
    }

    /// Check existence of index entries in [start_ts, end_ts].
    pub fn dataset_query_exist(
        &self,
        handle: DataSetHandle,
        start_ts: i64,
        end_ts: i64,
    ) -> Result<Vec<u8>> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.query_exist(start_ts, end_ts)
    }

    /// Read the logical data length for a timestamp.
    pub fn dataset_read_length(
        &self,
        handle: DataSetHandle,
        timestamp: i64,
    ) -> Result<Option<u32>> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.read_length(timestamp)
    }

    /// Query data lengths for timestamps in [start_ts, end_ts].
    pub fn dataset_query_length(
        &self,
        handle: DataSetHandle,
        start_ts: i64,
        end_ts: i64,
    ) -> Result<Vec<(i64, u32)>> {
        let ds_arc = self.get_dataset(&handle)?;
        ds_arc.query_length(start_ts, end_ts)
    }

    /// Return the highest successfully written timestamp for a dataset handle.
    pub fn latest_written_timestamp(&self, handle: DataSetHandle) -> Result<Option<i64>> {
        let ds_arc = self.get_dataset(&handle)?;
        Ok(ds_arc.latest_written_timestamp())
    }

    /// Whether this Store instance resolved to read-only mode at open time.
    pub fn is_read_only(&self) -> bool {
        self.read_only
    }

    /// Get a reference to the global block cache.
    pub fn block_cache(&self) -> &Arc<BlockCache> {
        &self.block_cache
    }

    /// Get a reference to the store config.
    pub fn config(&self) -> &StoreConfig {
        &self.config
    }

    /// Execute one tick of all background tasks synchronously.
    ///
    /// Checks if flush, idle-close, cache eviction, or retention reclaim are
    /// due and runs them immediately.  Returns the number of executed tasks
    /// and the delay until the next one is due.
    ///
    /// Safe to call even when the background thread is enabled; it will
    /// be serialised with the thread via the internal `Mutex`.
    pub fn tick_background_tasks(&self) -> Result<TickResult> {
        if self.read_only {
            return Err(TmslError::InvalidData(
                "read-only store has no background tasks".into(),
            ));
        }
        let bg = self
            .bg_tasks
            .as_ref()
            .ok_or_else(|| TmslError::InvalidData("bg_tasks not initialised".into()))?;
        Ok(bg.tick())
    }

    /// Return the duration until the next background task is due.
    ///
    /// Reads a snapshot of the executor state without running any tasks.
    /// Blocks briefly if another thread is currently executing `tick`.
    pub fn next_background_delay(&self) -> Result<Duration> {
        if self.read_only {
            return Err(TmslError::InvalidData(
                "read-only store has no background tasks".into(),
            ));
        }
        let bg = self
            .bg_tasks
            .as_ref()
            .ok_or_else(|| TmslError::InvalidData("bg_tasks not initialised".into()))?;
        Ok(bg.next_delay())
    }

    // 鈹€鈹€鈹€ Dataset enumeration 鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€鈹€

    /// Get all unique dataset names in the store.
    pub fn get_dataset_names(&self) -> Result<Vec<String>> {
        let mut names: Vec<String> = self
            .scan_dataset_dirs()?
            .into_iter()
            .map(|(k, _)| k.name)
            .collect::<HashSet<_>>()
            .into_iter()
            .collect();
        names.sort();
        Ok(names)
    }

    /// Get all dataset types for a given name.
    pub fn get_dataset_types(&self, name: &str) -> Result<Vec<String>> {
        validate_dataset_component("dataset name", name)?;
        let mut types: Vec<String> = self
            .scan_dataset_dirs()?
            .into_iter()
            .filter(|(k, _)| k.name == name)
            .map(|(k, _)| k.dataset_type)
            .collect();
        types.sort();
        Ok(types)
    }

    /// Get detailed info and state of a dataset.
    ///
    /// Returns `DataSetInspectResult` containing immutable config (`DataSetInfo`)
    /// and mutable state (`DataSetState`).
    pub fn inspect_dataset(&self, name: &str, dataset_type: &str) -> Result<DataSetInspectResult> {
        validate_dataset_path_components(name, dataset_type)?;
        let key = DataSetKey {
            name: name.to_string(),
            dataset_type: dataset_type.to_string(),
        };
        if let Some(ds_arc) = self.datasets.read().unwrap().get(&key).cloned() {
            return ds_arc.inspect();
        }

        let dir = self.dataset_dir(&key);
        let identifier = read_dataset_identifier(&dir)?;
        self.validate_identifier_within_max(identifier, &key)?;
        let ds = if self.read_only {
            DataSet::open_read_only(key.clone(), dir)?
        } else {
            DataSet::open(key.clone(), dir)?
        };
        ds.set_identifier(identifier)?;
        ds.set_runtime_context(Self::dataset_runtime_context(
            &self.block_cache,
            &self.journal,
            self.bg_tasks.as_ref().map(|bg| bg.flush_queue()),
            &self.lifecycle,
            ds.enable_journal(),
            self.read_only,
        )?)?;
        let ds_arc = Arc::new(ds);
        {
            let mut guard = self.datasets.write().unwrap();
            guard.insert(key, Arc::clone(&ds_arc));
        }
        ds_arc.inspect()
    }

    /// Close the store completely.
    pub fn close(mut self) -> Result<()> {
        // 1. Stop background tasks
        if let Some(mut bg) = self.bg_tasks.take() {
            bg.stop();
        }

        // 2. Flush and close all datasets.
        let datasets = {
            let mut guard = self.datasets.write().unwrap();
            guard.drain().map(|(_, ds_arc)| ds_arc).collect::<Vec<_>>()
        };
        for ds_arc in datasets {
            if let Err(e) = ds_arc.close() {
                log::error!("[store] close failed: {}", e);
            }
        }
        self.journal.close()?;

        Ok(())
    }

    /// Open the queue subsystem for a dataset.
    ///
    /// Must be called before any consumer or push operations on the dataset.
    /// Returns a `DatasetQueue` handle that can be cloned and shared.
    pub fn open_queue(&mut self, handle: DataSetHandle) -> Result<DatasetQueue> {
        self.ensure_writable("open queue")?;
        let key = self.handle_entry(handle)?.key;
        if JournalManager::is_journal_key(&key) {
            return Err(TmslError::InvalidData(
                "journal queue must be opened with open_journal_queue".into(),
            ));
        }
        let ds_arc = self
            .datasets
            .read()
            .unwrap()
            .get(&key)
            .ok_or_else(|| TmslError::NotFound(format!("dataset {:?} not found", key)))?
            .clone();

        // Initialize queue on the dataset
        let (inner, notify) = ds_arc.open_queue()?;

        Ok(DatasetQueue {
            dataset: ds_arc,
            inner,
            notify,
            allow_push: true,
        })
    }

    /// Close the queue subsystem for a dataset.
    pub fn close_queue(&mut self, handle: DataSetHandle) -> Result<()> {
        self.ensure_writable("close queue")?;
        let key = self.handle_entry(handle)?.key;
        if JournalManager::is_journal_key(&key) {
            return Err(TmslError::InvalidData(
                "journal queue is managed by JournalManager".into(),
            ));
        }
        let ds_arc = self
            .datasets
            .read()
            .unwrap()
            .get(&key)
            .ok_or_else(|| TmslError::NotFound(format!("dataset {:?} not found", key)))?
            .clone();

        ds_arc.close_queue()
    }

    /// Open or create a consumer group for a dataset queue.
    ///
    /// The queue must have been opened via `open_queue` first.
    /// Multiple consumers in the same group share progress.
    pub fn open_consumer(
        &mut self,
        queue: &DatasetQueue,
        group_name: &str,
    ) -> Result<DatasetQueueConsumer> {
        self.ensure_writable("open consumer")?;
        queue.open_consumer(group_name)
    }

    /// Open or create a consumer group with explicit retry configuration.
    pub fn open_consumer_with_config(
        &mut self,
        queue: &DatasetQueue,
        group_name: &str,
        config: QueueConsumerConfig,
    ) -> Result<DatasetQueueConsumer> {
        self.ensure_writable("open consumer")?;
        queue.open_consumer_with_config(group_name, config)
    }

    /// Drop a consumer group for a dataset queue.
    pub fn drop_consumer(&mut self, queue: &DatasetQueue, group_name: &str) -> Result<()> {
        self.ensure_writable("drop consumer")?;
        queue.drop_consumer(group_name)
    }

    /// Push data into a dataset queue.
    ///
    /// Auto-increments timestamp and notifies waiting consumers.
    pub fn queue_push(&mut self, queue: &DatasetQueue, data: &[u8]) -> Result<i64> {
        self.ensure_writable("push queue")?;
        queue.push(data)
    }

    /// Poll for the next record from a consumer.
    pub fn queue_poll(
        &self,
        consumer: &DatasetQueueConsumer,
        timeout: Duration,
    ) -> Result<Option<(i64, Vec<u8>)>> {
        if self.read_only {
            return Err(TmslError::InvalidData(
                "read-only store cannot poll queue".into(),
            ));
        }
        consumer.poll(timeout)
    }

    /// Ack a previously polled record.
    pub fn queue_ack(&self, consumer: &DatasetQueueConsumer, timestamp: i64) -> Result<()> {
        if self.read_only {
            return Err(TmslError::InvalidData(
                "read-only store cannot ack queue".into(),
            ));
        }
        consumer.ack(timestamp)
    }

    /// Return the latest journal sequence, or None when the journal is empty.
    pub fn journal_latest_sequence(&self) -> Result<Option<i64>> {
        self.journal.latest_sequence()
    }

    /// Read one encoded journal record by sequence.
    pub fn journal_read(&self, sequence: i64) -> Result<Option<(i64, Vec<u8>)>> {
        self.journal.read(sequence)
    }

    /// Query encoded journal records by inclusive sequence range.
    pub fn journal_query(
        &self,
        start_sequence: i64,
        end_sequence: i64,
    ) -> Result<Vec<(i64, Vec<u8>)>> {
        self.journal.query(start_sequence, end_sequence)
    }

    /// Read the source dataset record referenced by a journal write/delete/append record.
    pub fn read_journal_source_record(
        &mut self,
        dataset_identifier: u64,
        index_info: JournalIndexInfo,
    ) -> Result<(i64, Vec<u8>)> {
        let handle = self.open_dataset_by_identifier(dataset_identifier)?;
        let ds_arc = self.get_dataset(&handle)?;
        let entry = IndexEntry::new(
            index_info.timestamp,
            index_info.block_offset,
            index_info.in_block_offset,
        );
        ds_arc.read_entry_at_index(&entry)
    }

    /// Open the built-in journal queue.
    pub fn open_journal_queue(&mut self) -> Result<JournalQueue> {
        self.ensure_writable("open journal queue")?;
        self.journal.open_queue()
    }
}

impl Drop for Store {
    fn drop(&mut self) {
        // Best-effort cleanup if close() wasn't called
        if let Some(mut bg) = self.bg_tasks.take() {
            bg.stop();
        }
        let _ = self.journal.flush();
    }
}