qs-data-preprocess 0.3.1

Historical market data storage and preprocessing CLI
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
//! Parquet-based storage backend for tick and bar data.
//!
//! Uses Hive-style directory partitioning:
//!   {root}/ticks/exchange={ex}/symbol={sym}/{date}.parquet
//!   {root}/bars/exchange={ex}/symbol={sym}/timeframe={tf}/{date}.parquet

use std::collections::HashMap;
use std::ffi::OsString;
use std::fs::{self, File, OpenOptions};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use chrono::NaiveDateTime;
use polars::prelude::*;

use crate::convert::{
    bars_to_dataframe, dataframe_to_bars, dataframe_to_ticks, ndt_to_date_string,
    ticks_to_dataframe,
};
use crate::error::{DataError, Result};
use crate::models::{Bar, BarQueryOpts, QueryOpts, StatRow, Tick};
use crate::scanner::{ParquetScanBounds, ParquetTickScan};

/// Parquet-based storage backend for tick and bar data.
pub struct ParquetStore {
    root: PathBuf,
}

impl ParquetStore {
    /// Open a Parquet data store rooted at the given directory, creating it if needed.
    pub fn open(root: impl AsRef<Path>) -> Result<Self> {
        let root = root.as_ref().to_path_buf();
        fs::create_dir_all(&root)?;
        Ok(Self { root })
    }

    // ── Import ──────────────────────────────────────────────────

    /// Import ticks, deduplicating against existing data per date partition.
    /// Returns the number of rows actually inserted (after dedup).
    pub fn insert_ticks(&self, ticks: &[Tick]) -> Result<usize> {
        if ticks.is_empty() {
            return Ok(0);
        }

        // Group ticks by (exchange, symbol, date)
        let mut groups: HashMap<(String, String, String), Vec<&Tick>> = HashMap::new();
        for tick in ticks {
            let date = ndt_to_date_string(&tick.ts);
            let key = (tick.exchange.clone(), tick.symbol.clone(), date);
            groups.entry(key).or_default().push(tick);
        }

        let mut total_inserted = 0usize;

        for ((exchange, symbol, date), group_ticks) in &groups {
            let dir = self.tick_dir(exchange, symbol);
            fs::create_dir_all(&dir)?;
            let file_path = dir.join(format!("{date}.parquet"));

            let owned: Vec<Tick> = group_ticks.iter().map(|t| (*t).clone()).collect();
            let new_df = ticks_to_dataframe(&owned)?;

            if file_path.exists() {
                let existing_df = read_parquet_file(&file_path)?;
                let existing_count = existing_df.height();
                let combined = concat_and_dedup_ticks(existing_df, new_df)?;
                total_inserted += combined.height().saturating_sub(existing_count);
                write_parquet_file(&file_path, &mut combined.clone())?;
            } else {
                let deduped = dedup_ticks(new_df)?;
                total_inserted += deduped.height();
                write_parquet_file(&file_path, &mut deduped.clone())?;
            }
        }

        Ok(total_inserted)
    }

    /// Import bars, deduplicating against existing data per date partition.
    /// Returns the number of rows actually inserted (after dedup).
    pub fn insert_bars(&self, bars: &[Bar]) -> Result<usize> {
        if bars.is_empty() {
            return Ok(0);
        }

        // Group bars by (exchange, symbol, timeframe, date)
        let mut groups: HashMap<(String, String, String, String), Vec<&Bar>> = HashMap::new();
        for bar in bars {
            let date = ndt_to_date_string(&bar.ts);
            let key = (
                bar.exchange.clone(),
                bar.symbol.clone(),
                bar.timeframe.as_str().to_string(),
                date,
            );
            groups.entry(key).or_default().push(bar);
        }

        let mut total_inserted = 0usize;

        for ((exchange, symbol, timeframe, date), group_bars) in &groups {
            let dir = self.bar_dir(exchange, symbol, timeframe);
            fs::create_dir_all(&dir)?;
            let file_path = dir.join(format!("{date}.parquet"));

            let owned: Vec<Bar> = group_bars.iter().map(|b| (*b).clone()).collect();
            let new_df = bars_to_dataframe(&owned)?;

            if file_path.exists() {
                let existing_df = read_parquet_file(&file_path)?;
                let existing_count = existing_df.height();
                let combined = concat_and_dedup_bars(existing_df, new_df)?;
                total_inserted += combined.height().saturating_sub(existing_count);
                write_parquet_file(&file_path, &mut combined.clone())?;
            } else {
                let deduped = dedup_bars(new_df)?;
                total_inserted += deduped.height();
                write_parquet_file(&file_path, &mut deduped.clone())?;
            }
        }

        Ok(total_inserted)
    }

    // ── Query ───────────────────────────────────────────────────

    /// Query ticks for a given exchange+symbol, optionally filtered by date range.
    /// Returns (ticks, total_count_matching_filters).
    pub fn query_ticks(&self, opts: &QueryOpts) -> Result<(Vec<Tick>, u64)> {
        self.query_ticks_cancellable(opts, || false)
    }

    /// Cancellable tick query.
    ///
    /// Cancellation is checked while traversing directory entries, before and
    /// after every Parquet file, and between DataFrame processing stages. The
    /// low-level Polars collect/read for one file remains atomic because Polars
    /// does not expose an interruption hook for that operation.
    pub fn query_ticks_cancellable<F>(
        &self,
        opts: &QueryOpts,
        mut is_cancelled: F,
    ) -> Result<(Vec<Tick>, u64)>
    where
        F: FnMut() -> bool,
    {
        ensure_not_cancelled(&mut is_cancelled)?;
        let dir = self.tick_dir(&opts.exchange, &opts.symbol);
        if !dir.exists() {
            return Ok((Vec::new(), 0));
        }

        let files = list_date_files_cancellable(&dir, opts.from, opts.to, &mut is_cancelled)?;
        if files.is_empty() {
            return Ok((Vec::new(), 0));
        }

        let mut all_dfs: Vec<DataFrame> = Vec::with_capacity(files.len());
        for file in &files {
            ensure_not_cancelled(&mut is_cancelled)?;
            let df = read_parquet_file(file)?;
            ensure_not_cancelled(&mut is_cancelled)?;
            all_dfs.push(df);
        }
        let mut combined = concat_dataframes(all_dfs)?;
        ensure_not_cancelled(&mut is_cancelled)?;

        combined = apply_ts_filter(combined, opts.from, opts.to)?;
        ensure_not_cancelled(&mut is_cancelled)?;
        combined = combined.sort(["ts"], SortMultipleOptions::default())?;
        ensure_not_cancelled(&mut is_cancelled)?;

        let total = combined.height() as u64;
        combined = apply_pagination(combined, opts.limit, opts.tail, opts.descending)?;
        ensure_not_cancelled(&mut is_cancelled)?;

        let ticks = dataframe_to_ticks(&combined)?;
        ensure_not_cancelled(&mut is_cancelled)?;
        Ok((ticks, total))
    }

    /// Return the latest tick with a valid quote strictly before `before`.
    pub fn latest_valid_tick_before(
        &self,
        exchange: &str,
        symbol: &str,
        before: NaiveDateTime,
    ) -> Result<Option<Tick>> {
        self.latest_valid_tick_before_cancellable(exchange, symbol, before, || false)
    }

    /// Cancellable strict-before lookup for the latest tick with a valid quote.
    ///
    /// Date partitions and their rows are searched newest-to-oldest.
    /// Ticks at `before` are excluded, and ticks with missing, non-finite, non-positive, or crossed bid/ask prices are skipped.
    pub fn latest_valid_tick_before_cancellable<F>(
        &self,
        exchange: &str,
        symbol: &str,
        before: NaiveDateTime,
        mut is_cancelled: F,
    ) -> Result<Option<Tick>>
    where
        F: FnMut() -> bool,
    {
        ensure_not_cancelled(&mut is_cancelled)?;
        let scan = ParquetTickScan::describe_cancellable(
            &self.root,
            exchange,
            symbol,
            ParquetScanBounds::new(None, Some(before)),
            &mut is_cancelled,
        )?;
        let latest = scan
            .latest_valid_tick_before_cancellable(before, &mut is_cancelled)?
            .map(|row| row.row);
        ensure_not_cancelled(&mut is_cancelled)?;
        Ok(latest)
    }

    /// Query bars for a given exchange+symbol+timeframe, optionally filtered by date range.
    /// Returns (bars, total_count_matching_filters).
    pub fn query_bars(&self, opts: &BarQueryOpts) -> Result<(Vec<Bar>, u64)> {
        self.query_bars_cancellable(opts, || false)
    }

    /// Cancellable bar query with the same cooperative boundaries as
    /// [`Self::query_ticks_cancellable`].
    pub fn query_bars_cancellable<F>(
        &self,
        opts: &BarQueryOpts,
        mut is_cancelled: F,
    ) -> Result<(Vec<Bar>, u64)>
    where
        F: FnMut() -> bool,
    {
        ensure_not_cancelled(&mut is_cancelled)?;
        let dir = self.bar_dir(&opts.exchange, &opts.symbol, &opts.timeframe);
        if !dir.exists() {
            return Ok((Vec::new(), 0));
        }

        let files = list_date_files_cancellable(&dir, opts.from, opts.to, &mut is_cancelled)?;
        if files.is_empty() {
            return Ok((Vec::new(), 0));
        }

        let mut all_dfs: Vec<DataFrame> = Vec::with_capacity(files.len());
        for file in &files {
            ensure_not_cancelled(&mut is_cancelled)?;
            let df = read_parquet_file(file)?;
            ensure_not_cancelled(&mut is_cancelled)?;
            all_dfs.push(df);
        }
        let mut combined = concat_dataframes(all_dfs)?;
        ensure_not_cancelled(&mut is_cancelled)?;

        combined = apply_ts_filter(combined, opts.from, opts.to)?;
        ensure_not_cancelled(&mut is_cancelled)?;
        combined = combined.sort(["ts"], SortMultipleOptions::default())?;
        ensure_not_cancelled(&mut is_cancelled)?;

        let total = combined.height() as u64;
        combined = apply_pagination(combined, opts.limit, opts.tail, opts.descending)?;
        ensure_not_cancelled(&mut is_cancelled)?;

        let bars = dataframe_to_bars(&combined)?;
        ensure_not_cancelled(&mut is_cancelled)?;
        Ok((bars, total))
    }

    // ── Delete ──────────────────────────────────────────────────

    /// Delete ticks matching exchange+symbol, optionally within a date range.
    pub fn delete_ticks(
        &self,
        exchange: &str,
        symbol: &str,
        from: Option<NaiveDateTime>,
        to: Option<NaiveDateTime>,
    ) -> Result<usize> {
        let dir = self.tick_dir(exchange, symbol);
        if !dir.exists() {
            return Ok(0);
        }
        delete_from_partition(&dir, from, to)
    }

    /// Delete bars matching exchange+symbol+timeframe, optionally within a date range.
    pub fn delete_bars(
        &self,
        exchange: &str,
        symbol: &str,
        timeframe: &str,
        from: Option<NaiveDateTime>,
        to: Option<NaiveDateTime>,
    ) -> Result<usize> {
        let dir = self.bar_dir(exchange, symbol, timeframe);
        if !dir.exists() {
            return Ok(0);
        }
        delete_from_partition(&dir, from, to)
    }

    /// Delete ALL data (ticks + bars) for an exchange+symbol pair.
    pub fn delete_symbol(&self, exchange: &str, symbol: &str) -> Result<(usize, usize)> {
        let tick_count = self.count_rows_in_dir(&self.tick_dir(exchange, symbol));
        let bar_count = self.count_all_bars_for_symbol(exchange, symbol);

        // Remove tick directory
        let tick_dir = self.tick_dir(exchange, symbol);
        if tick_dir.exists() {
            fs::remove_dir_all(&tick_dir)?;
        }

        // Remove bar directories for all timeframes
        let bar_sym_dir = self
            .root
            .join("bars")
            .join(format!("exchange={exchange}"))
            .join(format!("symbol={symbol}"));
        if bar_sym_dir.exists() {
            fs::remove_dir_all(&bar_sym_dir)?;
        }

        Ok((tick_count, bar_count))
    }

    /// Delete ALL data for an entire exchange.
    pub fn delete_exchange(&self, exchange: &str) -> Result<(usize, usize)> {
        let tick_ex_dir = self.root.join("ticks").join(format!("exchange={exchange}"));
        let bar_ex_dir = self.root.join("bars").join(format!("exchange={exchange}"));

        let tick_count = self.count_rows_recursive(&tick_ex_dir);
        let bar_count = self.count_rows_recursive(&bar_ex_dir);

        if tick_ex_dir.exists() {
            fs::remove_dir_all(&tick_ex_dir)?;
        }
        if bar_ex_dir.exists() {
            fs::remove_dir_all(&bar_ex_dir)?;
        }

        Ok((tick_count, bar_count))
    }

    // ── Stats ───────────────────────────────────────────────────

    /// Summary statistics across all data, optionally filtered by exchange and/or symbol.
    pub fn stats(&self, exchange: Option<&str>, symbol: Option<&str>) -> Result<Vec<StatRow>> {
        let mut rows = Vec::new();

        // Collect tick stats
        self.collect_tick_stats(&mut rows, exchange, symbol)?;

        // Collect bar stats
        self.collect_bar_stats(&mut rows, exchange, symbol)?;

        // Sort by exchange, symbol, data_type
        rows.sort_by(|a, b| {
            a.exchange
                .cmp(&b.exchange)
                .then(a.symbol.cmp(&b.symbol))
                .then(a.data_type.cmp(&b.data_type))
        });

        Ok(rows)
    }

    /// Total size of all Parquet files under the data root (bytes).
    pub fn total_size(&self) -> Option<u64> {
        let mut total = 0u64;
        for entry in walkdir(&self.root) {
            if entry.extension().is_some_and(|e| e == "parquet")
                && let Ok(meta) = fs::metadata(&entry)
            {
                total += meta.len();
            }
        }
        if total == 0 { None } else { Some(total) }
    }

    // ── Private helpers ─────────────────────────────────────────

    pub(crate) fn root_path(&self) -> &Path {
        &self.root
    }

    /// Build tick directory path for a given exchange+symbol.
    fn tick_dir(&self, exchange: &str, symbol: &str) -> PathBuf {
        self.root
            .join("ticks")
            .join(format!("exchange={exchange}"))
            .join(format!("symbol={symbol}"))
    }

    /// Build bar directory path for a given exchange+symbol+timeframe.
    fn bar_dir(&self, exchange: &str, symbol: &str, timeframe: &str) -> PathBuf {
        self.root
            .join("bars")
            .join(format!("exchange={exchange}"))
            .join(format!("symbol={symbol}"))
            .join(format!("timeframe={timeframe}"))
    }

    /// Count total rows across all parquet files in a directory.
    fn count_rows_in_dir(&self, dir: &Path) -> usize {
        if !dir.exists() {
            return 0;
        }
        let mut count = 0;
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().is_some_and(|e| e == "parquet")
                    && let Ok(df) = read_parquet_file(&path)
                {
                    count += df.height();
                }
            }
        }
        count
    }

    /// Count total rows recursively across all parquet files under a directory.
    fn count_rows_recursive(&self, dir: &Path) -> usize {
        if !dir.exists() {
            return 0;
        }
        let mut count = 0;
        for path in walkdir(dir) {
            if path.extension().is_some_and(|e| e == "parquet")
                && let Ok(df) = read_parquet_file(&path)
            {
                count += df.height();
            }
        }
        count
    }

    /// Count all bar rows for a given exchange+symbol across all timeframes.
    fn count_all_bars_for_symbol(&self, exchange: &str, symbol: &str) -> usize {
        let bar_sym_dir = self
            .root
            .join("bars")
            .join(format!("exchange={exchange}"))
            .join(format!("symbol={symbol}"));
        self.count_rows_recursive(&bar_sym_dir)
    }

    /// Collect tick stats from the directory tree.
    fn collect_tick_stats(
        &self,
        rows: &mut Vec<StatRow>,
        exchange_filter: Option<&str>,
        symbol_filter: Option<&str>,
    ) -> Result<()> {
        let ticks_dir = self.root.join("ticks");
        if !ticks_dir.exists() {
            return Ok(());
        }

        for (exchange, symbol, dir) in self.iter_exchange_symbol_dirs(&ticks_dir)? {
            if let Some(ef) = exchange_filter
                && exchange != ef
            {
                continue;
            }
            if let Some(sf) = symbol_filter
                && symbol != sf
            {
                continue;
            }

            let (count, ts_min, ts_max) = self.aggregate_parquet_stats(&dir)?;
            if count > 0 {
                rows.push(StatRow {
                    exchange,
                    symbol,
                    data_type: "tick".to_string(),
                    count,
                    ts_min: ts_min.unwrap_or_default(),
                    ts_max: ts_max.unwrap_or_default(),
                });
            }
        }

        Ok(())
    }

    /// Collect bar stats from the directory tree.
    fn collect_bar_stats(
        &self,
        rows: &mut Vec<StatRow>,
        exchange_filter: Option<&str>,
        symbol_filter: Option<&str>,
    ) -> Result<()> {
        let bars_dir = self.root.join("bars");
        if !bars_dir.exists() {
            return Ok(());
        }

        for (exchange, symbol, timeframe, dir) in self.iter_exchange_symbol_tf_dirs(&bars_dir)? {
            if let Some(ef) = exchange_filter
                && exchange != ef
            {
                continue;
            }
            if let Some(sf) = symbol_filter
                && symbol != sf
            {
                continue;
            }

            let (count, ts_min, ts_max) = self.aggregate_parquet_stats(&dir)?;
            if count > 0 {
                rows.push(StatRow {
                    exchange,
                    symbol,
                    data_type: format!("bar ({timeframe})"),
                    count,
                    ts_min: ts_min.unwrap_or_default(),
                    ts_max: ts_max.unwrap_or_default(),
                });
            }
        }

        Ok(())
    }

    /// Iterate over exchange/symbol directories under a top-level dir.
    fn iter_exchange_symbol_dirs(&self, base: &Path) -> Result<Vec<(String, String, PathBuf)>> {
        let mut result = Vec::new();
        if !base.exists() {
            return Ok(result);
        }

        for ex_entry in fs::read_dir(base)?.flatten() {
            let ex_path = ex_entry.path();
            if !ex_path.is_dir() {
                continue;
            }
            let exchange =
                parse_partition_value(ex_path.file_name().unwrap().to_str().unwrap_or(""));
            if exchange.is_empty() {
                continue;
            }

            for sym_entry in fs::read_dir(&ex_path)?.flatten() {
                let sym_path = sym_entry.path();
                if !sym_path.is_dir() {
                    continue;
                }
                let symbol =
                    parse_partition_value(sym_path.file_name().unwrap().to_str().unwrap_or(""));
                if symbol.is_empty() {
                    continue;
                }
                result.push((exchange.clone(), symbol, sym_path));
            }
        }

        Ok(result)
    }

    /// Iterate over exchange/symbol/timeframe directories under a top-level dir.
    fn iter_exchange_symbol_tf_dirs(
        &self,
        base: &Path,
    ) -> Result<Vec<(String, String, String, PathBuf)>> {
        let mut result = Vec::new();
        if !base.exists() {
            return Ok(result);
        }

        for ex_entry in fs::read_dir(base)?.flatten() {
            let ex_path = ex_entry.path();
            if !ex_path.is_dir() {
                continue;
            }
            let exchange =
                parse_partition_value(ex_path.file_name().unwrap().to_str().unwrap_or(""));
            if exchange.is_empty() {
                continue;
            }

            for sym_entry in fs::read_dir(&ex_path)?.flatten() {
                let sym_path = sym_entry.path();
                if !sym_path.is_dir() {
                    continue;
                }
                let symbol =
                    parse_partition_value(sym_path.file_name().unwrap().to_str().unwrap_or(""));
                if symbol.is_empty() {
                    continue;
                }

                for tf_entry in fs::read_dir(&sym_path)?.flatten() {
                    let tf_path = tf_entry.path();
                    if !tf_path.is_dir() {
                        continue;
                    }
                    let timeframe =
                        parse_partition_value(tf_path.file_name().unwrap().to_str().unwrap_or(""));
                    if timeframe.is_empty() {
                        continue;
                    }
                    result.push((exchange.clone(), symbol.clone(), timeframe, tf_path));
                }
            }
        }

        Ok(result)
    }

    /// Read all parquet files in a directory and aggregate row count + min/max ts.
    fn aggregate_parquet_stats(
        &self,
        dir: &Path,
    ) -> Result<(u64, Option<NaiveDateTime>, Option<NaiveDateTime>)> {
        let mut total_count = 0u64;
        let mut global_min: Option<i64> = None;
        let mut global_max: Option<i64> = None;

        if !dir.exists() {
            return Ok((0, None, None));
        }

        for entry in fs::read_dir(dir)?.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "parquet") {
                let df = read_parquet_file(&path)?;
                total_count += df.height() as u64;

                if df.height() > 0 {
                    let ts_col = df.column("ts").ok().and_then(|c| c.datetime().ok());
                    if let Some(ts) = ts_col {
                        if let Some(min_val) = ts.min() {
                            global_min =
                                Some(global_min.map_or(min_val, |cur: i64| cur.min(min_val)));
                        }
                        if let Some(max_val) = ts.max() {
                            global_max =
                                Some(global_max.map_or(max_val, |cur: i64| cur.max(max_val)));
                        }
                    }
                }
            }
        }

        let ts_min = global_min.map(micros_to_ndt);
        let ts_max = global_max.map(micros_to_ndt);

        Ok((total_count, ts_min, ts_max))
    }
}

// ── Free functions ──────────────────────────────────────────────

/// Parse a Hive partition value from a directory name like "exchange=ctrader".
fn parse_partition_value(dir_name: &str) -> String {
    dir_name
        .split_once('=')
        .map(|(_, v)| v.to_string())
        .unwrap_or_default()
}

fn ensure_not_cancelled(is_cancelled: &mut dyn FnMut() -> bool) -> Result<()> {
    if is_cancelled() {
        Err(DataError::Cancelled)
    } else {
        Ok(())
    }
}

/// List parquet files in a directory, optionally filtered by date range in filename.
fn list_date_files(
    dir: &Path,
    from: Option<NaiveDateTime>,
    to: Option<NaiveDateTime>,
) -> Result<Vec<PathBuf>> {
    list_date_files_cancellable(dir, from, to, &mut || false)
}

fn list_date_files_cancellable(
    dir: &Path,
    from: Option<NaiveDateTime>,
    to: Option<NaiveDateTime>,
    is_cancelled: &mut dyn FnMut() -> bool,
) -> Result<Vec<PathBuf>> {
    ensure_not_cancelled(is_cancelled)?;
    let mut files = Vec::new();
    let from_date = from.map(|d| d.format("%Y-%m-%d").to_string());
    let to_date = to.map(|d| d.format("%Y-%m-%d").to_string());

    for entry in fs::read_dir(dir)? {
        ensure_not_cancelled(is_cancelled)?;
        let path = entry?.path();
        if path.extension().is_some_and(|e| e == "parquet") {
            let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");

            // Filename-level date pruning
            let dominated_by_from = from_date.as_ref().is_some_and(|fd| stem < fd.as_str());
            let past_to = to_date.as_ref().is_some_and(|td| stem > td.as_str());

            if !dominated_by_from && !past_to {
                files.push(path);
            }
        }
    }

    ensure_not_cancelled(is_cancelled)?;
    files.sort();
    Ok(files)
}

/// Read a single Parquet file into a DataFrame.
fn read_parquet_file(path: &Path) -> Result<DataFrame> {
    let file = std::fs::File::open(path)?;
    let df = ParquetReader::new(file).finish()?;
    Ok(df)
}

static NEXT_TEMP_FILE_ID: AtomicU64 = AtomicU64::new(0);

/// Write a DataFrame to a temporary file and atomically replace the partition.
fn write_parquet_file(path: &Path, df: &mut DataFrame) -> Result<()> {
    let (temp_path, mut file) = create_partition_temp_file(path)?;
    let write_result = (|| -> Result<()> {
        ParquetWriter::new(&mut file)
            .with_compression(ParquetCompression::Zstd(None))
            .finish(df)?;
        file.sync_all()?;
        Ok(())
    })();
    drop(file);

    if let Err(error) = write_result {
        fs::remove_file(&temp_path).ok();
        return Err(error);
    }
    if let Err(error) = atomic_replace(&temp_path, path) {
        fs::remove_file(&temp_path).ok();
        return Err(error.into());
    }
    Ok(())
}

fn create_partition_temp_file(path: &Path) -> Result<(PathBuf, File)> {
    let parent = path.parent().ok_or_else(|| {
        DataError::Other(format!("partition path has no parent: {}", path.display()))
    })?;
    let file_name = path.file_name().ok_or_else(|| {
        DataError::Other(format!(
            "partition path has no file name: {}",
            path.display()
        ))
    })?;

    loop {
        let id = NEXT_TEMP_FILE_ID.fetch_add(1, Ordering::Relaxed);
        let mut temp_name = OsString::from(".");
        temp_name.push(file_name);
        temp_name.push(format!(".{}.{}.tmp", std::process::id(), id));
        let temp_path = parent.join(temp_name);
        match OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp_path)
        {
            Ok(file) => return Ok((temp_path, file)),
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(error.into()),
        }
    }
}

#[cfg(not(windows))]
fn atomic_replace(from: &Path, to: &Path) -> std::io::Result<()> {
    fs::rename(from, to)
}

#[cfg(windows)]
fn atomic_replace(from: &Path, to: &Path) -> std::io::Result<()> {
    use std::os::windows::ffi::OsStrExt;

    const MOVEFILE_REPLACE_EXISTING: u32 = 0x1;
    const MOVEFILE_WRITE_THROUGH: u32 = 0x8;

    #[link(name = "kernel32")]
    unsafe extern "system" {
        fn MoveFileExW(
            existing_file_name: *const u16,
            new_file_name: *const u16,
            flags: u32,
        ) -> i32;
    }

    let from = from
        .as_os_str()
        .encode_wide()
        .chain(Some(0))
        .collect::<Vec<_>>();
    let to = to
        .as_os_str()
        .encode_wide()
        .chain(Some(0))
        .collect::<Vec<_>>();
    let replaced = unsafe {
        MoveFileExW(
            from.as_ptr(),
            to.as_ptr(),
            MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH,
        )
    };
    if replaced == 0 {
        Err(std::io::Error::last_os_error())
    } else {
        Ok(())
    }
}

/// Concat two tick DataFrames, dedup on (exchange, symbol, ts), sort by ts.
fn concat_and_dedup_ticks(existing: DataFrame, new: DataFrame) -> Result<DataFrame> {
    let combined = concat_dataframes(vec![existing, new])?;
    dedup_ticks(combined)
}

/// Dedup a tick DataFrame on (exchange, symbol, ts) keeping first, sort by ts.
fn dedup_ticks(df: DataFrame) -> Result<DataFrame> {
    let cols: Vec<String> = vec!["exchange".into(), "symbol".into(), "ts".into()];
    let deduped = df
        .unique_stable(Some(&cols), UniqueKeepStrategy::First, None)?
        .sort(["ts"], SortMultipleOptions::default())?;
    Ok(deduped)
}

/// Concat two bar DataFrames, dedup on (exchange, symbol, timeframe, ts), sort by ts.
fn concat_and_dedup_bars(existing: DataFrame, new: DataFrame) -> Result<DataFrame> {
    let combined = concat_dataframes(vec![existing, new])?;
    dedup_bars(combined)
}

/// Dedup a bar DataFrame on (exchange, symbol, timeframe, ts) keeping first, sort by ts.
fn dedup_bars(df: DataFrame) -> Result<DataFrame> {
    let cols: Vec<String> = vec![
        "exchange".into(),
        "symbol".into(),
        "timeframe".into(),
        "ts".into(),
    ];
    let deduped = df
        .unique_stable(Some(&cols), UniqueKeepStrategy::First, None)?
        .sort(["ts"], SortMultipleOptions::default())?;
    Ok(deduped)
}

/// Vertically concatenate multiple DataFrames.
fn concat_dataframes(dfs: Vec<DataFrame>) -> Result<DataFrame> {
    if dfs.is_empty() {
        return Err(DataError::Other("no dataframes to concat".into()));
    }
    if dfs.len() == 1 {
        return Ok(dfs.into_iter().next().unwrap());
    }
    let lazy_frames: Vec<LazyFrame> = dfs.into_iter().map(|df| df.lazy()).collect();
    let combined = polars::prelude::concat(lazy_frames, Default::default())?.collect()?;
    Ok(combined)
}

/// Apply timestamp range filter to a DataFrame with a "ts" datetime column.
fn apply_ts_filter(
    df: DataFrame,
    from: Option<NaiveDateTime>,
    to: Option<NaiveDateTime>,
) -> Result<DataFrame> {
    if from.is_none() && to.is_none() {
        return Ok(df);
    }

    let mut lf = df.lazy();

    if let Some(f) = from {
        let from_micros = f.and_utc().timestamp_micros();
        lf = lf.filter(
            col("ts")
                .gt_eq(lit(from_micros).cast(DataType::Datetime(TimeUnit::Microseconds, None))),
        );
    }
    if let Some(t) = to {
        let to_micros = t.and_utc().timestamp_micros();
        lf = lf.filter(
            col("ts").lt_eq(lit(to_micros).cast(DataType::Datetime(TimeUnit::Microseconds, None))),
        );
    }

    Ok(lf.collect()?)
}

/// Apply limit, tail, and descending pagination to a sorted DataFrame.
fn apply_pagination(
    df: DataFrame,
    limit: usize,
    tail: bool,
    descending: bool,
) -> Result<DataFrame> {
    // limit == 0 means "no limit" — return all rows.
    let result = if tail && limit > 0 {
        // Take last N rows, then optionally reverse for descending
        let n = limit.min(df.height());
        let tailed = df.tail(Some(n));
        if descending {
            tailed.sort(
                ["ts"],
                SortMultipleOptions::default().with_order_descending(true),
            )?
        } else {
            tailed
        }
    } else if descending {
        let sorted = df.sort(
            ["ts"],
            SortMultipleOptions::default().with_order_descending(true),
        )?;
        if limit > 0 {
            sorted.head(Some(limit))
        } else {
            sorted
        }
    } else if limit > 0 {
        df.head(Some(limit))
    } else {
        df
    };
    Ok(result)
}

/// Delete rows from a date-partitioned directory, optionally within a date range.
fn delete_from_partition(
    dir: &Path,
    from: Option<NaiveDateTime>,
    to: Option<NaiveDateTime>,
) -> Result<usize> {
    if from.is_none() && to.is_none() {
        // Delete everything in the directory
        let count = count_all_rows_in_dir(dir);
        // Remove all parquet files but keep the directory
        for entry in fs::read_dir(dir)?.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "parquet") {
                fs::remove_file(&path)?;
            }
        }
        return Ok(count);
    }

    let files = list_date_files(dir, from, to)?;
    let mut total_deleted = 0usize;

    for file_path in &files {
        let df = read_parquet_file(file_path)?;
        let original_count = df.height();

        // Filter to keep rows OUTSIDE the delete range
        let filtered = apply_ts_filter_inverted(df, from, to)?;

        if filtered.height() == 0 {
            // All rows deleted — remove the file
            fs::remove_file(file_path)?;
            total_deleted += original_count;
        } else if filtered.height() < original_count {
            // Partial deletion — rewrite the file
            total_deleted += original_count - filtered.height();
            write_parquet_file(file_path, &mut filtered.clone())?;
        }
        // else: no rows matched the range in this file
    }

    Ok(total_deleted)
}

/// Filter to keep rows OUTSIDE a timestamp range (inverse of apply_ts_filter).
fn apply_ts_filter_inverted(
    df: DataFrame,
    from: Option<NaiveDateTime>,
    to: Option<NaiveDateTime>,
) -> Result<DataFrame> {
    let mut lf = df.lazy();

    match (from, to) {
        (Some(f), Some(t)) => {
            let from_micros = f.and_utc().timestamp_micros();
            let to_micros = t.and_utc().timestamp_micros();
            let from_lit = lit(from_micros).cast(DataType::Datetime(TimeUnit::Microseconds, None));
            let to_lit = lit(to_micros).cast(DataType::Datetime(TimeUnit::Microseconds, None));
            // Keep rows where ts < from OR ts > to
            lf = lf.filter(col("ts").lt(from_lit).or(col("ts").gt(to_lit)));
        }
        (Some(f), None) => {
            let from_micros = f.and_utc().timestamp_micros();
            let from_lit = lit(from_micros).cast(DataType::Datetime(TimeUnit::Microseconds, None));
            lf = lf.filter(col("ts").lt(from_lit));
        }
        (None, Some(t)) => {
            let to_micros = t.and_utc().timestamp_micros();
            let to_lit = lit(to_micros).cast(DataType::Datetime(TimeUnit::Microseconds, None));
            lf = lf.filter(col("ts").gt(to_lit));
        }
        (None, None) => {}
    }

    Ok(lf.collect()?)
}

/// Count all rows across parquet files in a directory (non-recursive).
fn count_all_rows_in_dir(dir: &Path) -> usize {
    let mut count = 0;
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "parquet")
                && let Ok(df) = read_parquet_file(&path)
            {
                count += df.height();
            }
        }
    }
    count
}

/// Recursively walk a directory and collect all file paths.
fn walkdir(dir: &Path) -> Vec<PathBuf> {
    let mut result = Vec::new();
    if !dir.exists() {
        return result;
    }
    if let Ok(entries) = fs::read_dir(dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                result.extend(walkdir(&path));
            } else {
                result.push(path);
            }
        }
    }
    result
}

/// Convert microsecond epoch to NaiveDateTime.
fn micros_to_ndt(micros: i64) -> NaiveDateTime {
    let secs = micros / 1_000_000;
    let nsecs = ((micros % 1_000_000) * 1_000) as u32;
    chrono::DateTime::from_timestamp(secs, nsecs)
        .map(|dt| dt.naive_utc())
        .unwrap_or_default()
}