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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
use crate::{
error::{AllSourceError, Result},
infrastructure::persistence::{cold_tier::ArchiveTarget, storage::ParquetStorage},
};
use chrono::{DateTime, Utc};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs, path::PathBuf, sync::Arc, time::Duration};
/// Manages Parquet file compaction for optimal storage and query performance.
///
/// Step 4 of the sustainable data strategy moved compaction from a
/// global-stream pass to a per-tenant pass. Each invocation iterates
/// the tenants discovered under `<storage_dir>/<tenant>/...` and
/// emits a `snapshot.<tenant>.<from>-<to>.parquet` per qualifying
/// chunk. Snapshot files are written atomically (tmp + rename) and
/// their constituent raw files are removed only after the rename
/// succeeds — so a mid-compaction crash leaves data intact.
pub struct CompactionManager {
/// Directory where Parquet files are stored
storage_dir: PathBuf,
/// Configuration
config: CompactionConfig,
/// Statistics
stats: Arc<RwLock<CompactionStats>>,
/// Last compaction time
last_compaction: Arc<RwLock<Option<DateTime<Utc>>>>,
/// Tenant the previous sweep stopped after.
///
/// A sweep has a time budget and visits tenants in a stable order, so
/// without a cursor the tenants sorting last never get reached while
/// there is a backlog — and the worst offender is not usually the one
/// that sorts first. Each sweep resumes after this one.
sweep_cursor: Arc<RwLock<Option<String>>>,
}
/// Filename prefix that marks a file as already-compacted output.
///
/// A snapshot is a candidate again while it is still smaller than
/// `small_file_threshold`, so a pass that can only reach part of a tenant
/// merges its own earlier output upward instead of leaving a snapshot per
/// pass behind. Excluding them unconditionally traded one fragmentation
/// rate for a slower one: the tenant in gh#321 takes ~7 new files an hour,
/// which is a snapshot an hour, forever.
const SNAPSHOT_PREFIX: &str = "snapshot.";
#[derive(Debug, Clone)]
pub struct CompactionConfig {
/// Minimum number of files to trigger compaction
pub min_files_to_compact: usize,
/// Target size for compacted files (in bytes)
pub target_file_size: usize,
/// Maximum size for a single compacted file (in bytes)
pub max_file_size: usize,
/// Minimum file size to consider for compaction (small files)
pub small_file_threshold: usize,
/// Compressed input bytes one snapshot may be built from.
///
/// A group's events are all resident at once, and decoding this archive
/// shape costs roughly 16× its on-disk size, so this is the term that
/// bounds a compaction pass's peak memory. A tenant whose candidates
/// exceed it is compacted into several snapshots instead of one.
pub max_input_bytes_per_snapshot: u64,
/// Input files one snapshot may be built from, bounding footer opens and
/// path bookkeeping independently of how small the files are.
pub max_input_files_per_snapshot: usize,
/// Wall-clock budget for one compaction sweep. Checked between groups,
/// so a sweep overruns by at most one group.
///
/// A backlog is resumed on the next tick rather than drained in one
/// pass: the first sweep over an uncompacted tenant has as many groups
/// as the tenant has, and an unbounded sweep would hold CPU and disk
/// for as long as that takes.
pub max_pass_seconds: u64,
/// Time interval between automatic compactions (in seconds)
pub compaction_interval_seconds: u64,
/// Enable automatic background compaction
pub auto_compact: bool,
/// Compaction strategy
pub strategy: CompactionStrategy,
/// Per-tenant retention TTLs (Step 5 of the sustainable data
/// strategy). Applied during the same compaction pass — events
/// older than `now - ttl` for that tenant are dropped from the
/// snapshot output and the originals are removed. Default
/// honors the bead: tenant `system` keeps 30 days; everyone
/// else keeps forever.
pub retention: RetentionConfig,
/// Optional cold-tier archive. When set, events that would be
/// dropped by retention are archived to this target BEFORE the
/// originals are deleted. A failed archive aborts the
/// compaction pass — originals stay on disk and the next run
/// retries. Default `None` preserves the pre-cold-tier behavior:
/// retention deletes outright. See
/// `infrastructure::persistence::cold_tier`.
pub archive: Option<Arc<dyn ArchiveTarget>>,
}
/// Per-tenant retention configuration. Look up a TTL via
/// `ttl_for(tenant_id)`; `None` means "keep forever" for that
/// tenant.
///
/// The default rule (from the bead): the CP heartbeat tenant
/// (`system`) defaults to 30 days. The CP emits ~69k heartbeat
/// events/day; without retention this grows unbounded for data
/// that has no audit value past the dashboard window. Other
/// tenants default to no TTL — user data stays put unless the
/// owner opts in.
///
/// Per-tenant overrides win over `default_ttl`; "no entry" falls
/// back to `default_ttl`.
#[derive(Debug, Clone)]
pub struct RetentionConfig {
/// Default TTL when no per-tenant override exists. `None` = keep forever.
pub default_ttl: Option<Duration>,
/// Per-tenant overrides. `Some(None)` would mean "explicitly no
/// TTL"; the API uses `Option<Duration>` directly so an entry
/// can record an explicit "keep forever" decision distinct
/// from "no entry".
pub per_tenant_ttl: HashMap<String, Option<Duration>>,
}
impl Default for RetentionConfig {
fn default() -> Self {
let mut per_tenant_ttl = HashMap::new();
per_tenant_ttl.insert("system".to_string(), Some(Duration::from_hours(30 * 24)));
Self {
default_ttl: None,
per_tenant_ttl,
}
}
}
impl RetentionConfig {
/// Effective TTL for `tenant_id`. Returns `None` if the tenant
/// has no TTL (keep forever).
///
/// Lookup order:
/// 1. Per-tenant entry → that value (whether Some or explicit None).
/// 2. No entry → fall back to `default_ttl`.
pub fn ttl_for(&self, tenant_id: &str) -> Option<Duration> {
match self.per_tenant_ttl.get(tenant_id) {
Some(v) => *v,
None => self.default_ttl,
}
}
/// Override the TTL for a specific tenant. Use `None` to mean
/// "keep forever for this tenant".
pub fn set(&mut self, tenant_id: &str, ttl: Option<Duration>) {
self.per_tenant_ttl.insert(tenant_id.to_string(), ttl);
}
}
impl Default for CompactionConfig {
fn default() -> Self {
Self {
min_files_to_compact: 3,
target_file_size: 128 * 1024 * 1024, // 128 MB
max_file_size: 256 * 1024 * 1024, // 256 MB
small_file_threshold: 10 * 1024 * 1024, // 10 MB
max_input_bytes_per_snapshot: 32 * 1024 * 1024, // 32 MiB ≈ 512 MiB resident
max_input_files_per_snapshot: 2000,
max_pass_seconds: 240,
compaction_interval_seconds: 3600, // 1 hour
auto_compact: true,
strategy: CompactionStrategy::SizeBased,
retention: RetentionConfig::default(),
archive: None,
}
}
}
impl CompactionConfig {
/// Build a config from the relevant env vars:
/// - `ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS`: per-pass cadence
/// (default 3600).
/// - `ALLSOURCE_RETENTION_SYSTEM_DAYS`: TTL for the `system`
/// tenant in days (default 30).
/// - `ALLSOURCE_COMPACTION_INPUT_BYTES`: compressed input bytes per
/// snapshot, which bounds a pass's peak memory (default 32 MiB).
///
/// Unparseable values log a warning and fall back to defaults
/// — boot doesn't fail.
pub fn from_env() -> Self {
let config = Self::from_env_vars(
std::env::var("ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS").ok(),
std::env::var("ALLSOURCE_RETENTION_SYSTEM_DAYS").ok(),
)
.with_input_bytes(std::env::var("ALLSOURCE_COMPACTION_INPUT_BYTES").ok());
config.with_cold_storage_url(std::env::var("ALLSOURCE_COLD_STORAGE_URL").ok())
}
/// Override `max_input_bytes_per_snapshot`. Zero is rejected: it would
/// make every file its own group and rewrite the tenant file-for-file.
pub fn with_input_bytes(mut self, bytes_var: Option<String>) -> Self {
if let Some(s) = bytes_var.filter(|s| !s.trim().is_empty()) {
match s.trim().parse::<u64>() {
Ok(v) if v > 0 => self.max_input_bytes_per_snapshot = v,
Ok(_) => tracing::warn!(
"ALLSOURCE_COMPACTION_INPUT_BYTES=0 is not a usable bound; keeping {}",
self.max_input_bytes_per_snapshot
),
Err(e) => tracing::warn!(
"ALLSOURCE_COMPACTION_INPUT_BYTES={s:?} could not be parsed as u64: {e}; \
keeping {}",
self.max_input_bytes_per_snapshot
),
}
}
self
}
/// Attach a cold-tier archive from `ALLSOURCE_COLD_STORAGE_URL`
/// (`s3://bucket/prefix`). Unset or empty leaves `archive` as `None`,
/// which is the default: retention deletes without archiving.
///
/// A URL that is set but unusable is a hard error, not a warning. Every
/// other env var here falls back to a default because a wrong interval
/// costs a slow pass; this one decides whether events are copied somewhere
/// before compaction deletes the originals, so degrading to "no archive"
/// would turn an operator's typo into silent data loss.
#[allow(unused_variables, unused_mut)]
pub fn with_cold_storage_url(mut self, url: Option<String>) -> Self {
let Some(url) = url.filter(|u| !u.trim().is_empty()) else {
return self;
};
#[cfg(feature = "cold-tier-s3")]
{
match super::cold_tier_s3::S3Archive::from_url(url.trim()) {
Ok(archive) => {
tracing::info!(
target = %super::cold_tier::ArchiveTarget::description(&archive),
"cold-tier archive enabled"
);
self.archive = Some(std::sync::Arc::new(archive));
}
Err(e) => panic!("ALLSOURCE_COLD_STORAGE_URL={url:?} is set but unusable: {e}"),
}
}
#[cfg(not(feature = "cold-tier-s3"))]
panic!(
"ALLSOURCE_COLD_STORAGE_URL={url:?} is set but this binary was built without the \
`cold-tier-s3` feature, so nothing would be archived before retention deletes it. \
Rebuild with --features cold-tier-s3, or unset the variable."
);
#[cfg(feature = "cold-tier-s3")]
self
}
/// Testable variant of `from_env`. Production calls `from_env`;
/// tests pass explicit values.
pub fn from_env_vars(
interval_var: Option<String>,
system_retention_days_var: Option<String>,
) -> Self {
let mut config = Self::default();
if let Some(s) = interval_var.filter(|s| !s.is_empty()) {
match s.parse::<u64>() {
Ok(v) => config.compaction_interval_seconds = v,
Err(e) => {
tracing::warn!(
"ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS={s:?} could not be parsed as \
u64: {e}; defaulting to {}s",
config.compaction_interval_seconds
);
}
}
}
if let Some(s) = system_retention_days_var.filter(|s| !s.is_empty()) {
match s.parse::<u64>() {
// Zero days means keep forever, not "expire everything now".
// The literal reading would have this variable delete the
// tenant's entire history, which is not what an operator
// reaching for a smaller number is asking for, and there is
// no other way to express "no TTL" through the environment:
// leaving the variable unset falls back to the 30-day
// default rather than disabling it.
Ok(0) => {
tracing::info!(
"ALLSOURCE_RETENTION_SYSTEM_DAYS=0: retention disabled for tenant=system"
);
config.retention.set("system", None);
}
Ok(days) => {
config
.retention
.set("system", Some(Duration::from_secs(days * 24 * 3600)));
}
Err(e) => {
tracing::warn!(
"ALLSOURCE_RETENTION_SYSTEM_DAYS={s:?} could not be parsed as u64: \
{e}; defaulting to 30 days for tenant=system"
);
}
}
}
config
}
/// Backwards-compatible single-arg variant for existing
/// callers that only set the snapshot interval.
pub fn from_env_var(interval_var: Option<String>) -> Self {
Self::from_env_vars(interval_var, None)
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CompactionStrategy {
/// Compact based on file size (default)
SizeBased,
/// Compact based on file age
TimeBased,
/// Compact all files into one
FullCompaction,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct CompactionStats {
pub total_compactions: u64,
pub total_files_compacted: u64,
pub total_bytes_before: u64,
pub total_bytes_after: u64,
pub total_events_compacted: u64,
pub last_compaction_duration_ms: u64,
pub space_saved_bytes: u64,
}
/// Information about a Parquet file candidate for compaction
#[derive(Debug, Clone)]
struct FileInfo {
path: PathBuf,
size: u64,
created: DateTime<Utc>,
}
impl CompactionManager {
/// Create a new compaction manager
pub fn new(storage_dir: impl Into<PathBuf>, config: CompactionConfig) -> Self {
let storage_dir = storage_dir.into();
tracing::info!(
"✅ Compaction manager initialized at: {}",
storage_dir.display()
);
Self {
storage_dir,
config,
stats: Arc::new(RwLock::new(CompactionStats::default())),
last_compaction: Arc::new(RwLock::new(None)),
sweep_cursor: Arc::new(RwLock::new(None)),
}
}
/// List all Parquet files in the storage directory
fn list_parquet_files(&self) -> Result<Vec<FileInfo>> {
let entries = fs::read_dir(&self.storage_dir).map_err(|e| {
AllSourceError::StorageError(format!("Failed to read storage directory: {e}"))
})?;
let mut files = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| {
AllSourceError::StorageError(format!("Failed to read directory entry: {e}"))
})?;
let path = entry.path();
if let Some(ext) = path.extension()
&& ext == "parquet"
{
let metadata = entry.metadata().map_err(|e| {
AllSourceError::StorageError(format!("Failed to read file metadata: {e}"))
})?;
let size = metadata.len();
let created = metadata
.created()
.ok()
.and_then(|t| {
t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| {
DateTime::from_timestamp(d.as_secs() as i64, 0).unwrap_or_else(Utc::now)
})
})
.unwrap_or_else(Utc::now);
files.push(FileInfo {
path,
size,
created,
});
}
}
// Sort by creation time (oldest first)
files.sort_by_key(|f| f.created);
Ok(files)
}
/// Identify files that should be compacted based on strategy
fn select_files_for_compaction(&self, files: &[FileInfo]) -> Vec<FileInfo> {
match self.config.strategy {
CompactionStrategy::SizeBased => self.select_small_files(files),
CompactionStrategy::TimeBased => self.select_old_files(files),
CompactionStrategy::FullCompaction => files.to_vec(),
}
}
/// Select small files for compaction
fn select_small_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
let small_files: Vec<FileInfo> = files
.iter()
.filter(|f| f.size < self.config.small_file_threshold as u64)
.cloned()
.collect();
// Only compact if we have enough small files
if small_files.len() >= self.config.min_files_to_compact {
small_files
} else {
Vec::new()
}
}
/// Select old files for time-based compaction
fn select_old_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
let now = Utc::now();
let age_threshold = chrono::Duration::hours(24); // Files older than 24 hours
let old_files: Vec<FileInfo> = files
.iter()
.filter(|f| now - f.created > age_threshold)
.cloned()
.collect();
if old_files.len() >= self.config.min_files_to_compact {
old_files
} else {
Vec::new()
}
}
/// Check if compaction should run
#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub fn should_compact(&self) -> bool {
if !self.config.auto_compact {
return false;
}
let last = self.last_compaction.read();
match *last {
None => true, // Never compacted
Some(last_time) => {
let elapsed = (Utc::now() - last_time).num_seconds();
elapsed >= self.config.compaction_interval_seconds as i64
}
}
}
/// Perform compaction across every discovered tenant.
///
/// Iterates the tenants under `<storage_dir>/<tenant>/...`, calls
/// `compact_tenant` for each, and aggregates the results. Step 4
/// of the sustainable data strategy: per-tenant compaction
/// instead of global, keyed off the per-tenant directory tree
/// Step 1 introduced.
///
/// Errors compacting one tenant are logged but don't abort the
/// pass — other tenants still get compacted. The aggregate
/// result reflects what actually completed.
///
/// The sweep stops starting work once `max_pass_seconds` is spent and
/// resumes on the next tick. Tenants are visited in a stable order, so a
/// sweep that runs out of budget always leaves the same tail — the
/// per-pass bound is on time, and progress comes from the files each
/// group removes.
#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub fn compact(&self) -> Result<CompactionResult> {
self.compact_until(None)
}
/// Where the next sweep will start, or `None` before the first one.
///
/// Diagnostic: a cursor that never moves off one tenant means that
/// tenant's backlog is larger than a single pass's budget.
pub fn sweep_cursor(&self) -> Option<String> {
self.sweep_cursor.read().clone()
}
/// [`Self::compact`] with an explicit deadline in place of the one
/// `max_pass_seconds` derives.
pub fn compact_until(&self, deadline: Option<std::time::Instant>) -> Result<CompactionResult> {
let start_time = std::time::Instant::now();
tracing::info!("🔄 Starting per-tenant compaction sweep...");
let tenants = self.discover_tenants()?;
if tenants.is_empty() {
tracing::debug!("No tenants found under {}", self.storage_dir.display());
// Still a sweep that happened. Leaving `last_compaction` unset
// would have `should_compact` answer yes on every tick, so an
// empty store would be swept continuously.
*self.last_compaction.write() = Some(Utc::now());
return Ok(CompactionResult::default());
}
let tenants = self.rotate_to_cursor(tenants);
let deadline = deadline.unwrap_or_else(|| {
start_time + Duration::from_secs(self.config.max_pass_seconds.max(1))
});
let mut aggregate = CompactionResult::default();
let mut unvisited = 0usize;
// The first tenant this sweep did not finish. The next sweep starts
// there, so a tenant paused half way is resumed rather than waiting
// a full rotation, and a tenant never reached is reached next.
let mut resume_at: Option<&String> = None;
for tenant in &tenants {
if std::time::Instant::now() >= deadline {
unvisited += 1;
resume_at = resume_at.or(Some(tenant));
continue;
}
match self.sweep_tenant(tenant, Some(deadline)) {
Ok((r, complete)) => {
aggregate.files_compacted += r.files_compacted;
aggregate.bytes_before += r.bytes_before;
aggregate.bytes_after += r.bytes_after;
aggregate.events_compacted += r.events_compacted;
if !complete {
resume_at = resume_at.or(Some(tenant));
}
}
Err(e) => {
tracing::error!(
tenant_id = %tenant,
"compact_tenant failed: {e}"
);
}
}
}
// Everything finished: start the next sweep where this one did, so a
// steady state keeps visiting tenants in one stable order.
*self.sweep_cursor.write() = resume_at.or(tenants.first()).cloned();
if unvisited > 0 {
tracing::info!(
unvisited_tenants = unvisited,
resume_at = ?resume_at,
budget_secs = self.config.max_pass_seconds,
"compaction sweep hit its time budget; resuming next tick"
);
}
aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
if aggregate.files_compacted > 0 {
let mut stats = self.stats.write();
stats.total_compactions += 1;
stats.total_files_compacted += aggregate.files_compacted as u64;
stats.total_bytes_before += aggregate.bytes_before;
stats.total_bytes_after += aggregate.bytes_after;
stats.total_events_compacted += aggregate.events_compacted as u64;
stats.last_compaction_duration_ms = aggregate.duration_ms;
stats.space_saved_bytes += aggregate.bytes_before.saturating_sub(aggregate.bytes_after);
}
*self.last_compaction.write() = Some(Utc::now());
tracing::info!(
"✅ Compaction sweep complete: {} files → 1 snapshot per tenant, \
{:.2} MB → {:.2} MB, {} events, {} tenants in {}ms",
aggregate.files_compacted,
aggregate.bytes_before as f64 / (1024.0 * 1024.0),
aggregate.bytes_after as f64 / (1024.0 * 1024.0),
aggregate.events_compacted,
tenants.len(),
aggregate.duration_ms
);
Ok(aggregate)
}
/// Compact one tenant's event files into snapshot files under that
/// tenant's partition.
///
/// Per-tenant pipeline:
/// 1. List `<storage>/<tenant>/...*.parquet`, keeping an existing
/// `snapshot.*` only while it is still under
/// `small_file_threshold` so partial passes merge upward.
/// 2. Apply the configured strategy (size / time / full) to
/// pick candidates.
/// 3. Split the candidates into groups bounded by
/// `max_input_bytes_per_snapshot` and
/// `max_input_files_per_snapshot`, and compact each group on its
/// own. One group's events are resident at a time, so a tenant's
/// size sets how many snapshots a pass writes, never how much
/// memory it needs.
///
/// Each group is independently crash-safe: its snapshot is renamed
/// into place before any of its own inputs is deleted, and a crash
/// between groups leaves the earlier groups compacted and the later
/// ones untouched.
pub fn compact_tenant(&self, tenant_id: &str) -> Result<CompactionResult> {
self.compact_tenant_until(tenant_id, None)
}
/// `compact_tenant` with a sweep deadline. Checked between groups, so the
/// tenant's remaining groups are left for the next tick rather than
/// abandoned mid-group — a group either publishes its snapshot and
/// deletes its inputs or does neither.
pub fn compact_tenant_until(
&self,
tenant_id: &str,
deadline: Option<std::time::Instant>,
) -> Result<CompactionResult> {
self.sweep_tenant(tenant_id, deadline)
.map(|(result, _complete)| result)
}
/// `compact_tenant_until`, also reporting whether every group ran.
///
/// The sweep needs that answer to place its cursor: a tenant paused on
/// the budget has to be the next sweep's first call.
fn sweep_tenant(
&self,
tenant_id: &str,
deadline: Option<std::time::Instant>,
) -> Result<(CompactionResult, bool)> {
let start_time = std::time::Instant::now();
let storage = ParquetStorage::new(&self.storage_dir)?;
let all_files = storage.list_parquet_files_for_tenant(tenant_id)?;
let threshold = self.config.small_file_threshold as u64;
let raw_files: Vec<FileInfo> = all_files
.into_iter()
.filter_map(|p| {
let metadata = fs::metadata(&p).ok()?;
let size = metadata.len();
let is_snapshot = p
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|n| n.starts_with(SNAPSHOT_PREFIX));
// A snapshot that already reached the threshold is finished
// output: re-reading it would rewrite the whole tenant every
// pass for no reduction in file count.
if is_snapshot && size >= threshold {
return None;
}
let created = metadata
.created()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.and_then(|d| DateTime::from_timestamp(d.as_secs() as i64, 0))
.unwrap_or_else(Utc::now);
Some(FileInfo {
path: p,
size,
created,
})
})
.collect();
let mut candidates = self.select_files_for_compaction(&raw_files);
if candidates.is_empty() {
tracing::debug!(
tenant_id = tenant_id,
strategy = ?self.config.strategy,
"no files meet compaction criteria"
);
return Ok((CompactionResult::default(), true));
}
// Oldest first, so each group covers a contiguous time range and the
// snapshots a pass writes do not interleave.
candidates.sort_by_key(|f| f.created);
let total_bytes: u64 = candidates.iter().map(|f| f.size).sum();
let groups = self.split_into_bounded_groups(candidates);
tracing::info!(
tenant_id = tenant_id,
groups = groups.len(),
mib = total_bytes as f64 / (1024.0 * 1024.0),
"compacting tenant"
);
let total_groups = groups.len();
let mut aggregate = CompactionResult::default();
let mut done = 0usize;
// A group that fails does not stop the others. One unreadable file
// otherwise blocks its whole tenant from ever compacting, and the
// groups that have nothing wrong with them are what reduce the file
// count. The failure is still returned, so a caller cannot read a
// partial sweep as a clean one.
let mut first_error = None;
let mut complete = true;
for group in groups {
if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
tracing::info!(
tenant_id = tenant_id,
groups_done = done,
groups_total = total_groups,
"tenant compaction paused on the sweep budget"
);
complete = false;
break;
}
match self.compact_group(tenant_id, &storage, &group) {
Ok(result) => {
aggregate.files_compacted += result.files_compacted;
aggregate.bytes_before += result.bytes_before;
aggregate.bytes_after += result.bytes_after;
aggregate.events_compacted += result.events_compacted;
done += 1;
}
Err(error) => {
tracing::error!(
tenant_id = tenant_id,
files = group.len(),
"compaction group failed: {error}"
);
if first_error.is_none() {
first_error = Some(error);
}
}
}
}
if let Some(error) = first_error {
return Err(error);
}
aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
Ok((aggregate, complete))
}
/// Split candidates into groups no larger than the configured input
/// bounds. A single file over the byte bound is its own group — refusing
/// it would leave it uncompactable forever.
fn split_into_bounded_groups(&self, candidates: Vec<FileInfo>) -> Vec<Vec<FileInfo>> {
let max_bytes = self.config.max_input_bytes_per_snapshot.max(1);
let max_files = self.config.max_input_files_per_snapshot.max(1);
let mut groups: Vec<Vec<FileInfo>> = Vec::new();
let mut current: Vec<FileInfo> = Vec::new();
let mut current_bytes = 0u64;
for file in candidates {
let would_exceed = !current.is_empty()
&& (current_bytes + file.size > max_bytes || current.len() >= max_files);
if would_exceed {
groups.push(std::mem::take(&mut current));
current_bytes = 0;
}
current_bytes += file.size;
current.push(file);
}
if !current.is_empty() {
groups.push(current);
}
groups
}
/// Compact one bounded group of this tenant's files into a single
/// snapshot. Only this group's events are resident.
fn compact_group(
&self,
tenant_id: &str,
storage: &ParquetStorage,
candidates: &[FileInfo],
) -> Result<CompactionResult> {
let start_time = std::time::Instant::now();
let bytes_before: u64 = candidates.iter().map(|f| f.size).sum();
// Each file is read individually rather than through
// load_events_for_tenant so only the candidate set is picked up —
// concurrent writes that produced new files since enumeration are
// deferred to the next interval (AC #6).
let mut events = Vec::new();
for fi in candidates {
// Recover tenant from path so loaded events keep
// their identity (Step 1's path-as-tenant-source).
let event_tenant = match fi.path.strip_prefix(&self.storage_dir).ok() {
Some(rel) => rel
.components()
.next()
.and_then(|c| match c {
std::path::Component::Normal(t) => Some(t.to_string_lossy().into_owned()),
_ => None,
})
.unwrap_or_else(|| "default".to_string()),
None => "default".to_string(),
};
// Every selected input must be readable before any retention,
// archive, snapshot or deletion step can run. Skipping a failed
// input would later delete it as if its contents were preserved.
let mut loaded = storage
.load_events_from_file_path(&fi.path, &event_tenant)
.map_err(|error| {
AllSourceError::StorageError(format!(
"Compaction refused unreadable candidate {}: {error}",
fi.path.display()
))
})?;
events.append(&mut loaded);
}
if events.is_empty() {
tracing::warn!(
tenant_id = tenant_id,
"candidate files had no readable events; skipping snapshot"
);
return Ok(CompactionResult::default());
}
// Apply retention (Step 5). Drop events older than the
// tenant's TTL before they get rewritten into the
// snapshot. The originals get deleted at the end of the
// happy path either way, so dropped events go away with
// the same crash-safe guarantee as the rest of the
// compaction pipeline (snapshot rename completes BEFORE
// any original is deleted; AC #6).
//
// Cold-tier (sustainability): when an `archive` target is
// configured, dropped events are written to it BEFORE this
// function deletes any original file. A failed archive
// returns `Err`, originals stay on disk, and the next
// compaction pass retries — same crash-safety contract as
// the snapshot path. Without an archive, retention behaves
// exactly as before (delete outright).
let dropped_by_retention = if let Some(ttl) = self.config.retention.ttl_for(tenant_id) {
let cutoff = Utc::now()
- chrono::Duration::from_std(ttl).unwrap_or_else(|_| chrono::Duration::zero());
let before = events.len();
// Partition: drained = events past TTL, kept = events to keep.
// Using drain_filter would be simpler but it's unstable;
// partition + reassign keeps events: Vec<Event> with the
// kept slice in original order.
let (drained, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut events)
.into_iter()
.partition(|e| e.timestamp < cutoff);
events = kept;
let dropped = before - events.len();
if dropped > 0 {
tracing::info!(
retention_tenant = tenant_id,
dropped = dropped,
kept = events.len(),
cutoff = %cutoff.to_rfc3339(),
ttl_secs = ttl.as_secs(),
"retention: dropped events older than TTL"
);
if let Some(archive) = self.config.archive.as_ref() {
let from = drained
.iter()
.map(|e| e.timestamp)
.min()
.expect("dropped > 0 guarantees non-empty drained");
let to = drained
.iter()
.map(|e| e.timestamp)
.max()
.expect("dropped > 0 guarantees non-empty drained");
archive.archive(tenant_id, from, to, &drained)?;
tracing::info!(
retention_tenant = tenant_id,
archived_to = %archive.description(),
archived = drained.len(),
"retention: dropped events archived to cold tier"
);
}
}
dropped
} else {
0
};
// Edge case: every event aged out. Skip the snapshot
// write and just delete originals — the data is gone by
// design. Delete-without-snapshot is safe here because
// every event we'd have written to the snapshot was
// already past its TTL, and the input files live under
// the tenant's partition with nothing else relying on
// them.
if events.is_empty() {
tracing::info!(
tenant_id = tenant_id,
files_dropped = candidates.len(),
events_dropped = dropped_by_retention,
"retention: every event aged out — deleting originals without snapshot"
);
for fi in candidates {
if let Err(e) = fs::remove_file(&fi.path) {
tracing::error!(
file = %fi.path.display(),
"failed to remove fully-aged raw file: {e}"
);
}
}
return Ok(CompactionResult {
files_compacted: candidates.len(),
bytes_before,
bytes_after: 0,
events_compacted: 0,
duration_ms: start_time.elapsed().as_millis() as u64,
});
}
events.sort_by_key(|e| e.timestamp);
let from = events.first().expect("non-empty checked above").timestamp;
let to = events.last().expect("non-empty checked above").timestamp;
// Filename: snapshot.<tenant>.<from>-<to>.<nanos> with
// filesystem-safe ISO-basic timestamps (no colons). The nanosecond
// discriminator keeps two snapshots covering the same range from
// sharing a path: a snapshot can itself be an input, so a colliding
// stem would have the write land on a file the delete below removes.
let unique = Utc::now().timestamp_nanos_opt().unwrap_or_default();
let file_stem = format!(
"snapshot.{tenant_id}.{}-{}.{unique}",
format_iso_basic(from),
format_iso_basic(to)
);
let snapshot_path = storage.write_atomic_parquet(tenant_id, &file_stem, &events)?;
let bytes_after = fs::metadata(&snapshot_path).map_or(0, |m| m.len());
// Delete inputs AFTER the snapshot is durably renamed. AC #6: a
// snapshot-write failure short-circuits via the `?` above, so inputs
// stay on disk and events remain queryable until the next pass.
for fi in candidates {
if fi.path == snapshot_path {
continue;
}
if let Err(e) = fs::remove_file(&fi.path) {
tracing::error!(
file = %fi.path.display(),
"failed to remove pre-snapshot raw file: {e}"
);
}
}
let duration_ms = start_time.elapsed().as_millis() as u64;
tracing::info!(
tenant_id = tenant_id,
files_compacted = candidates.len(),
events = events.len(),
dropped_by_retention = dropped_by_retention,
mib_before = bytes_before as f64 / (1024.0 * 1024.0),
mib_after = bytes_after as f64 / (1024.0 * 1024.0),
duration_ms = duration_ms,
"tenant compaction group complete"
);
Ok(CompactionResult {
files_compacted: candidates.len(),
bytes_before,
bytes_after,
events_compacted: events.len(),
duration_ms,
})
}
/// Reorder `tenants` so the sweep begins at the cursor, wrapping around.
///
/// The cursor names the tenant to start at, not the one last finished: a
/// tenant paused on the time budget has to be the next sweep's first
/// call, or its remaining groups wait a full rotation. A cursor naming a
/// tenant that no longer exists falls back to the start.
fn rotate_to_cursor(&self, tenants: Vec<String>) -> Vec<String> {
let cursor = self.sweep_cursor.read().clone();
let Some(cursor) = cursor else {
return tenants;
};
let Some(position) = tenants.iter().position(|tenant| *tenant == cursor) else {
return tenants;
};
let mut rotated = tenants;
rotated.rotate_left(position);
rotated
}
/// Discover tenant ids by scanning `<storage_dir>/<X>/` for
/// directories. The migration tool's flat-layout files at the
/// root are not picked up — Step 1 #3's migration moves them
/// under `default/`.
fn discover_tenants(&self) -> Result<Vec<String>> {
let Ok(entries) = fs::read_dir(&self.storage_dir) else {
return Ok(Vec::new());
};
let mut tenants: Vec<String> = entries
.filter_map(std::result::Result::ok)
.filter_map(|entry| {
let ft = entry.file_type().ok()?;
if !ft.is_dir() {
return None;
}
let name = entry.file_name().to_string_lossy().into_owned();
// Skip the system metadata subtree (Core's own
// event-sourced repos) and any hidden folders.
if name.starts_with('.') || name == "__system" {
return None;
}
Some(name)
})
.collect();
tenants.sort();
Ok(tenants)
}
/// Get compaction statistics
pub fn stats(&self) -> CompactionStats {
(*self.stats.read()).clone()
}
/// Get configuration
pub fn config(&self) -> &CompactionConfig {
&self.config
}
/// Trigger manual compaction
#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub fn compact_now(&self) -> Result<CompactionResult> {
tracing::info!("Manual compaction triggered");
self.compact()
}
}
/// Result of a compaction operation
#[derive(Debug, Clone, Default, Serialize)]
pub struct CompactionResult {
pub files_compacted: usize,
pub bytes_before: u64,
pub bytes_after: u64,
pub events_compacted: usize,
pub duration_ms: u64,
}
/// Format a UTC timestamp as a filename-safe ISO-8601 basic-form
/// string: `2026-04-27T134567Z` — no colons, no fractional second.
/// Used for the `<from>-<to>` portion of snapshot filenames so
/// they're portable across filesystems. `pub(super)` so the
/// cold-tier archive can reuse the same naming convention.
pub(super) fn format_iso_basic(t: DateTime<Utc>) -> String {
t.format("%Y-%m-%dT%H%M%SZ").to_string()
}
/// Background compaction task
pub struct CompactionTask {
manager: Arc<CompactionManager>,
interval: Duration,
}
impl CompactionTask {
/// Create a new background compaction task
pub fn new(manager: Arc<CompactionManager>, interval_seconds: u64) -> Self {
Self {
manager,
interval: Duration::from_secs(interval_seconds),
}
}
/// Run the compaction task in a loop
#[cfg_attr(feature = "hotpath", hotpath::measure)]
pub async fn run(self) {
let mut interval = tokio::time::interval(self.interval);
loop {
interval.tick().await;
if self.manager.should_compact() {
tracing::debug!("Auto-compaction check triggered");
match self.manager.compact() {
Ok(result) => {
if result.files_compacted > 0 {
tracing::info!(
"Auto-compaction succeeded: {} files, {:.2} MB saved",
result.files_compacted,
(result.bytes_before - result.bytes_after) as f64
/ (1024.0 * 1024.0)
);
}
}
Err(e) => {
tracing::error!("Auto-compaction failed: {}", e);
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_compaction_manager_creation() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = CompactionManager::new(temp_dir.path(), config);
assert_eq!(manager.stats().total_compactions, 0);
}
#[test]
fn test_should_compact() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
auto_compact: true,
compaction_interval_seconds: 1,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
// Should compact on first check (never compacted)
assert!(manager.should_compact());
}
#[test]
fn test_file_selection_size_based() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
small_file_threshold: 1024 * 1024, // 1 MB
min_files_to_compact: 2,
strategy: CompactionStrategy::SizeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let files = vec![
FileInfo {
path: PathBuf::from("small1.parquet"),
size: 500_000, // 500 KB
created: Utc::now(),
},
FileInfo {
path: PathBuf::from("small2.parquet"),
size: 600_000, // 600 KB
created: Utc::now(),
},
FileInfo {
path: PathBuf::from("large.parquet"),
size: 10_000_000, // 10 MB
created: Utc::now(),
},
];
let selected = manager.select_files_for_compaction(&files);
assert_eq!(selected.len(), 2); // Only the 2 small files
}
#[test]
fn test_default_compaction_config() {
let config = CompactionConfig::default();
assert_eq!(config.min_files_to_compact, 3);
assert_eq!(config.target_file_size, 128 * 1024 * 1024);
assert_eq!(config.max_file_size, 256 * 1024 * 1024);
assert_eq!(config.small_file_threshold, 10 * 1024 * 1024);
assert_eq!(config.compaction_interval_seconds, 3600);
assert!(config.auto_compact);
assert_eq!(config.strategy, CompactionStrategy::SizeBased);
}
#[test]
fn test_should_compact_disabled() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
auto_compact: false,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
assert!(!manager.should_compact());
}
#[test]
fn test_compact_empty_directory() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact().unwrap();
assert_eq!(result.files_compacted, 0);
assert_eq!(result.bytes_before, 0);
assert_eq!(result.bytes_after, 0);
assert_eq!(result.events_compacted, 0);
}
#[test]
fn test_compact_now() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact_now().unwrap();
assert_eq!(result.files_compacted, 0);
}
#[test]
fn test_get_config() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
min_files_to_compact: 5,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
assert_eq!(manager.config().min_files_to_compact, 5);
}
#[test]
fn test_get_stats() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = CompactionManager::new(temp_dir.path(), config);
let stats = manager.stats();
assert_eq!(stats.total_compactions, 0);
assert_eq!(stats.total_files_compacted, 0);
assert_eq!(stats.total_bytes_before, 0);
assert_eq!(stats.total_bytes_after, 0);
assert_eq!(stats.total_events_compacted, 0);
assert_eq!(stats.last_compaction_duration_ms, 0);
assert_eq!(stats.space_saved_bytes, 0);
}
#[test]
fn test_file_selection_not_enough_small_files() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
small_file_threshold: 1024 * 1024,
min_files_to_compact: 3, // Need 3 files
strategy: CompactionStrategy::SizeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let files = vec![
FileInfo {
path: PathBuf::from("small1.parquet"),
size: 500_000,
created: Utc::now(),
},
FileInfo {
path: PathBuf::from("small2.parquet"),
size: 600_000,
created: Utc::now(),
},
];
let selected = manager.select_files_for_compaction(&files);
assert_eq!(selected.len(), 0); // Not enough small files
}
#[test]
fn test_file_selection_time_based() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
min_files_to_compact: 2,
strategy: CompactionStrategy::TimeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let old_time = Utc::now() - chrono::Duration::hours(48);
let files = vec![
FileInfo {
path: PathBuf::from("old1.parquet"),
size: 1_000_000,
created: old_time,
},
FileInfo {
path: PathBuf::from("old2.parquet"),
size: 2_000_000,
created: old_time,
},
FileInfo {
path: PathBuf::from("new.parquet"),
size: 500_000,
created: Utc::now(),
},
];
let selected = manager.select_files_for_compaction(&files);
assert_eq!(selected.len(), 2); // Only the 2 old files
}
#[test]
fn test_file_selection_time_based_not_enough() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
min_files_to_compact: 3,
strategy: CompactionStrategy::TimeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let old_time = Utc::now() - chrono::Duration::hours(48);
let files = vec![
FileInfo {
path: PathBuf::from("old1.parquet"),
size: 1_000_000,
created: old_time,
},
FileInfo {
path: PathBuf::from("new.parquet"),
size: 500_000,
created: Utc::now(),
},
];
let selected = manager.select_files_for_compaction(&files);
assert_eq!(selected.len(), 0); // Not enough old files
}
#[test]
fn test_file_selection_full_compaction() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig {
strategy: CompactionStrategy::FullCompaction,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let files = vec![
FileInfo {
path: PathBuf::from("file1.parquet"),
size: 1_000_000,
created: Utc::now(),
},
FileInfo {
path: PathBuf::from("file2.parquet"),
size: 2_000_000,
created: Utc::now(),
},
];
let selected = manager.select_files_for_compaction(&files);
assert_eq!(selected.len(), 2); // All files selected
}
#[test]
fn test_compaction_strategy_serde() {
let strategies = vec![
CompactionStrategy::SizeBased,
CompactionStrategy::TimeBased,
CompactionStrategy::FullCompaction,
];
for strategy in strategies {
let json = serde_json::to_string(&strategy).unwrap();
let parsed: CompactionStrategy = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, strategy);
}
}
#[test]
fn test_compaction_stats_default() {
let stats = CompactionStats::default();
assert_eq!(stats.total_compactions, 0);
assert_eq!(stats.total_files_compacted, 0);
}
#[test]
fn test_compaction_stats_serde() {
let stats = CompactionStats {
total_compactions: 5,
total_files_compacted: 20,
total_bytes_before: 1000000,
total_bytes_after: 500000,
total_events_compacted: 10000,
last_compaction_duration_ms: 500,
space_saved_bytes: 500000,
};
let json = serde_json::to_string(&stats).unwrap();
assert!(json.contains("\"total_compactions\":5"));
assert!(json.contains("\"space_saved_bytes\":500000"));
}
#[test]
fn test_compaction_result_serde() {
let result = CompactionResult {
files_compacted: 3,
bytes_before: 1000000,
bytes_after: 500000,
events_compacted: 5000,
duration_ms: 250,
};
let json = serde_json::to_string(&result).unwrap();
assert!(json.contains("\"files_compacted\":3"));
assert!(json.contains("\"bytes_before\":1000000"));
}
#[test]
fn test_compaction_task_creation() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = Arc::new(CompactionManager::new(temp_dir.path(), config));
let _task = CompactionTask::new(manager.clone(), 60);
// Task created successfully
}
#[test]
fn test_list_parquet_files_empty() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = CompactionManager::new(temp_dir.path(), config);
let files = manager.list_parquet_files().unwrap();
assert!(files.is_empty());
}
#[test]
fn test_list_parquet_files_with_non_parquet() {
let temp_dir = TempDir::new().unwrap();
let config = CompactionConfig::default();
let manager = CompactionManager::new(temp_dir.path(), config);
// Create non-parquet files
std::fs::write(temp_dir.path().join("test.txt"), "test").unwrap();
std::fs::write(temp_dir.path().join("data.json"), "{}").unwrap();
let files = manager.list_parquet_files().unwrap();
assert!(files.is_empty()); // No parquet files
}
// -----------------------------------------------------------------
// Per-tenant compaction tests (Step 4, commit #2).
// -----------------------------------------------------------------
fn ingest_and_flush_per_call(storage_dir: &std::path::Path, tenant: &str, count: usize) {
// Each ingested batch produces one parquet file when its
// ParquetStorage is dropped, giving us multiple raw files
// per tenant for the strategy filter to pick up.
for i in 0..count {
let storage = ParquetStorage::with_config(
storage_dir,
crate::infrastructure::persistence::ParquetStorageConfig {
batch_size: 1,
..Default::default()
},
)
.unwrap();
let event = crate::domain::entities::Event::from_strings(
"test.event".to_string(),
format!("{tenant}-{i}"),
tenant.to_string(),
serde_json::json!({"i": i}),
None,
)
.unwrap();
storage.append_event(event).unwrap();
storage.flush().unwrap();
}
}
#[test]
fn test_compact_tenant_emits_one_snapshot_and_removes_originals() {
let temp_dir = TempDir::new().unwrap();
// Seed 4 raw files for alice.
ingest_and_flush_per_call(temp_dir.path(), "alice", 4);
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact_tenant("alice").unwrap();
assert_eq!(result.files_compacted, 4);
assert_eq!(result.events_compacted, 4);
// After: zero raw files, exactly one snapshot.* file under
// alice's subtree.
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
assert_eq!(
alice_files.len(),
1,
"expected exactly one snapshot file for alice"
);
let name = alice_files[0]
.file_name()
.and_then(|n| n.to_str())
.unwrap()
.to_string();
assert!(
name.starts_with("snapshot.alice."),
"expected snapshot prefix, got {name}"
);
assert!(name.ends_with(".parquet"));
// No tmp files left behind.
let tmps: Vec<_> = std::fs::read_dir(alice_files[0].parent().unwrap())
.unwrap()
.filter_map(std::result::Result::ok)
.filter(|e| e.path().to_string_lossy().ends_with(".tmp"))
.collect();
assert!(tmps.is_empty());
// Loaded events round-trip correctly.
let loaded = storage.load_events_for_tenant("alice").unwrap();
assert_eq!(loaded.len(), 4);
for e in &loaded {
assert_eq!(e.tenant_id_str(), "alice");
}
}
#[test]
fn test_compact_tenant_skips_existing_snapshot_files() {
// Seed alice with 4 raw files, run compaction → 1 snapshot.
// Run compaction AGAIN: the snapshot is excluded from the
// candidate set, no qualifying raw files remain, the second
// pass is a no-op.
let temp_dir = TempDir::new().unwrap();
ingest_and_flush_per_call(temp_dir.path(), "alice", 4);
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let r1 = manager.compact_tenant("alice").unwrap();
assert_eq!(r1.files_compacted, 4);
let r2 = manager.compact_tenant("alice").unwrap();
assert_eq!(r2.files_compacted, 0, "snapshot must not be re-compacted");
// Still exactly one file on disk for alice.
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
assert_eq!(alice_files.len(), 1);
}
#[test]
fn test_compact_tenant_below_threshold_is_a_noop() {
// 1 file < min_files_to_compact (default 3) → nothing happens.
let temp_dir = TempDir::new().unwrap();
ingest_and_flush_per_call(temp_dir.path(), "alice", 1);
let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
let result = manager.compact_tenant("alice").unwrap();
assert_eq!(result.files_compacted, 0);
// Raw file untouched.
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
assert_eq!(alice_files.len(), 1);
let name = alice_files[0]
.file_name()
.unwrap()
.to_string_lossy()
.into_owned();
assert!(
!name.starts_with("snapshot."),
"raw file must not be renamed"
);
}
#[test]
fn test_compact_iterates_every_tenant() {
// Two tenants each with enough raw files. compact() must
// produce one snapshot per tenant.
let temp_dir = TempDir::new().unwrap();
ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
ingest_and_flush_per_call(temp_dir.path(), "bob", 3);
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact().unwrap();
assert_eq!(result.files_compacted, 6);
assert_eq!(result.events_compacted, 6);
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
for tenant in ["alice", "bob"] {
let files = storage.list_parquet_files_for_tenant(tenant).unwrap();
assert_eq!(files.len(), 1, "{tenant} should have one snapshot");
let name = files[0].file_name().unwrap().to_string_lossy().into_owned();
assert!(name.starts_with(&format!("snapshot.{tenant}.")));
}
}
#[test]
fn test_retention_drops_events_older_than_ttl() {
// Bead's integration test: ingest 100 events spanning 60
// days, run compaction with 30-day TTL, only the last
// 30 days remain queryable.
let temp_dir = TempDir::new().unwrap();
// Seed alice with 100 events, timestamps spread across
// 60 days. We can't backdate via ingest (timestamp = now()
// in domain), so write parquet directly via flush of
// back-dated events.
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let now = Utc::now();
for i in 0..100 {
// Day 0 = 60 days ago; day 99 ≈ now. Spreads evenly.
let day_offset = 60 - (i * 60 / 99);
let ts = now - chrono::Duration::days(i64::from(day_offset));
let event = crate::domain::entities::Event::reconstruct_from_strings(
uuid::Uuid::new_v4(),
"test.event".to_string(),
format!("e-{i}"),
"alice".to_string(),
serde_json::json!({"i": i}),
ts,
None,
1,
);
storage.append_event(event).unwrap();
// Every 10 events get a fresh storage to produce a
// separate file (so compaction has multiple files
// to merge).
if i % 10 == 9 {
storage.flush().unwrap();
}
}
storage.flush().unwrap();
// 30-day TTL for alice via per-tenant override.
let mut retention = RetentionConfig::default();
retention.set("alice", Some(Duration::from_hours(30 * 24)));
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
retention,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact_tenant("alice").unwrap();
assert!(result.events_compacted > 0);
assert!(
result.events_compacted < 100,
"retention should have dropped some events; kept {} of 100",
result.events_compacted
);
// Re-load to confirm the dropped events are gone.
let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
let loaded = storage2.load_events_for_tenant("alice").unwrap();
assert_eq!(loaded.len(), result.events_compacted);
// Every loaded event must be within the 30-day window
// (with a generous fudge for test-clock drift).
let cutoff = Utc::now() - chrono::Duration::days(30);
for e in &loaded {
assert!(
e.timestamp >= cutoff - chrono::Duration::seconds(60),
"event with ts {} survived retention but is older than cutoff {}",
e.timestamp.to_rfc3339(),
cutoff.to_rfc3339()
);
}
}
#[test]
fn test_retention_keeps_forever_by_default_for_non_system_tenants() {
// alice has no override → falls through to default_ttl
// which is None. All events kept regardless of age.
let temp_dir = TempDir::new().unwrap();
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let now = Utc::now();
for i in 0..6 {
let ts = now - chrono::Duration::days(i * 365);
let event = crate::domain::entities::Event::reconstruct_from_strings(
uuid::Uuid::new_v4(),
"test.event".to_string(),
format!("e-{i}"),
"alice".to_string(),
serde_json::json!({"i": i}),
ts,
None,
1,
);
storage.append_event(event).unwrap();
if i % 2 == 1 {
storage.flush().unwrap();
}
}
storage.flush().unwrap();
// Default RetentionConfig: alice has no entry, default_ttl = None.
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact_tenant("alice").unwrap();
assert_eq!(result.events_compacted, 6, "no events should be dropped");
}
#[test]
fn test_retention_system_tenant_default_is_30_days() {
// The system tenant's 30-day TTL is the bead's headline
// requirement. Default config without any overrides
// should already enforce it.
let cfg = RetentionConfig::default();
let ttl = cfg.ttl_for("system").unwrap();
assert_eq!(ttl.as_secs(), 30 * 24 * 3600);
// No override for arbitrary tenants → keep forever.
assert!(cfg.ttl_for("acme").is_none());
}
#[test]
fn test_retention_drops_all_events_deletes_originals_without_snapshot() {
// Edge case: every event is past the TTL. We delete the
// raw files and emit no snapshot — there's nothing to
// write. Tenant ends with zero files on disk.
let temp_dir = TempDir::new().unwrap();
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let very_old = Utc::now() - chrono::Duration::days(90);
for i in 0..6 {
let event = crate::domain::entities::Event::reconstruct_from_strings(
uuid::Uuid::new_v4(),
"test.event".to_string(),
format!("e-{i}"),
"alice".to_string(),
serde_json::json!({"i": i}),
very_old,
None,
1,
);
storage.append_event(event).unwrap();
if i % 2 == 1 {
storage.flush().unwrap();
}
}
storage.flush().unwrap();
let mut retention = RetentionConfig::default();
retention.set("alice", Some(Duration::from_hours(7 * 24)));
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
retention,
..Default::default()
};
let manager = CompactionManager::new(temp_dir.path(), config);
let result = manager.compact_tenant("alice").unwrap();
assert_eq!(result.events_compacted, 0);
assert!(result.files_compacted >= 2); // originals were deleted
// Tenant subtree has zero parquet files now.
let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
let alice_files = storage2.list_parquet_files_for_tenant("alice").unwrap();
assert!(alice_files.is_empty(), "all originals should be deleted");
}
#[test]
fn test_compaction_with_simulated_crash_leaves_data_recoverable() {
// AC #7-#8: simulate "crash mid-snapshot" by manually
// dropping a tmp file in the partition, then asserting
// a fresh ParquetStorage::new boot cleans it up and the
// raw files (which would still be present in a real
// mid-rename crash) remain queryable.
let temp_dir = TempDir::new().unwrap();
// Seed alice with raw files.
ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
// Locate alice's partition dir.
let storage = ParquetStorage::new(temp_dir.path()).unwrap();
let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
let partition = alice_files[0].parent().unwrap().to_path_buf();
// Simulate the crash state: write a partial .tmp file as
// if write_atomic_parquet had crashed mid-rename.
let crashed_tmp = partition.join("snapshot.alice.range.parquet.tmp");
std::fs::write(&crashed_tmp, b"partial parquet bytes").unwrap();
assert!(crashed_tmp.is_file());
// Reboot — ParquetStorage::new triggers cleanup_partial_writes.
let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
assert!(
!crashed_tmp.exists(),
"stale tmp file should have been cleaned by ParquetStorage::new"
);
// Raw files survived; events queryable.
let events = storage2.load_events_for_tenant("alice").unwrap();
assert_eq!(events.len(), 3);
}
#[test]
fn test_cold_tier_archives_dropped_events_before_deletion() {
// Cold-tier integration: when retention drops events AND an
// archive target is configured, the dropped events end up
// in the archive root before originals are removed. This is
// the load-bearing property — without archive-before-delete
// the cold tier would silently lose data on retention runs.
use crate::infrastructure::persistence::cold_tier::LocalFsArchive;
let live_dir = TempDir::new().unwrap();
let archive_dir = TempDir::new().unwrap();
// Seed alice with 50 events spread across 60 days.
let storage = ParquetStorage::new(live_dir.path()).unwrap();
let now = Utc::now();
for i in 0..50 {
let day_offset = 60 - (i * 60 / 49);
let ts = now - chrono::Duration::days(i64::from(day_offset));
let event = crate::domain::entities::Event::reconstruct_from_strings(
uuid::Uuid::new_v4(),
"test.event".to_string(),
format!("e-{i}"),
"alice".to_string(),
serde_json::json!({"i": i}),
ts,
None,
1,
);
storage.append_event(event).unwrap();
if i % 5 == 4 {
storage.flush().unwrap();
}
}
storage.flush().unwrap();
// 30-day TTL + cold-tier archive.
let mut retention = RetentionConfig::default();
retention.set("alice", Some(Duration::from_hours(30 * 24)));
let archive: Arc<dyn ArchiveTarget> =
Arc::new(LocalFsArchive::new(archive_dir.path()).unwrap());
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
retention,
archive: Some(archive),
..Default::default()
};
let manager = CompactionManager::new(live_dir.path(), config);
let result = manager.compact_tenant("alice").unwrap();
assert!(result.events_compacted > 0, "some events kept");
assert!(
result.events_compacted < 50,
"some events dropped to retention; kept {} of 50",
result.events_compacted
);
// Live storage: only events within the 30-day window.
let live_after = ParquetStorage::new(live_dir.path())
.unwrap()
.load_events_for_tenant("alice")
.unwrap();
assert_eq!(live_after.len(), result.events_compacted);
// Archive: contains the dropped events. Walk the archive root
// and load any archive.alice.* file we find.
let mut archive_files = vec![];
let mut stack = vec![archive_dir.path().to_path_buf()];
while let Some(d) = stack.pop() {
for entry in std::fs::read_dir(&d).unwrap().flatten() {
let p = entry.path();
if p.is_dir() {
stack.push(p);
} else if p
.file_name()
.is_some_and(|n| n.to_string_lossy().starts_with("archive.alice."))
{
archive_files.push(p);
}
}
}
assert!(
!archive_files.is_empty(),
"archive directory must contain at least one archive.alice.* file"
);
// Sum events across archive files; total live + archived
// must equal the original 50 (no events lost in the pipeline).
let archive_storage = ParquetStorage::new(archive_dir.path()).unwrap();
let archived = archive_storage.load_events_for_tenant("alice").unwrap();
assert_eq!(
live_after.len() + archived.len(),
50,
"live + archived must equal original event count (live={}, archived={})",
live_after.len(),
archived.len()
);
}
#[test]
fn test_cold_tier_failure_keeps_originals_on_disk() {
// Crash-safety contract: a failing archive must NOT delete
// originals. We use a custom ArchiveTarget that always
// returns Err to simulate an outage.
let live_dir = TempDir::new().unwrap();
let storage = ParquetStorage::new(live_dir.path()).unwrap();
let now = Utc::now();
for i in 0..20 {
let ts = now - chrono::Duration::days(60 - i);
let event = crate::domain::entities::Event::reconstruct_from_strings(
uuid::Uuid::new_v4(),
"test.event".to_string(),
format!("e-{i}"),
"alice".to_string(),
serde_json::json!({"i": i}),
ts,
None,
1,
);
storage.append_event(event).unwrap();
if i % 5 == 4 {
storage.flush().unwrap();
}
}
storage.flush().unwrap();
// Count files before. The compaction pipeline should leave
// them all on disk after the failed archive.
let count_files = |dir: &std::path::Path| -> usize {
let mut n = 0;
let mut stack = vec![dir.to_path_buf()];
while let Some(d) = stack.pop() {
for entry in std::fs::read_dir(&d).unwrap().flatten() {
let p = entry.path();
if p.is_dir() {
stack.push(p);
} else if p.extension().is_some_and(|e| e == "parquet") {
n += 1;
}
}
}
n
};
let before = count_files(live_dir.path());
assert!(before > 0);
#[derive(Debug)]
struct FailingArchive;
impl ArchiveTarget for FailingArchive {
fn archive(
&self,
_: &str,
_: DateTime<Utc>,
_: DateTime<Utc>,
_: &[crate::domain::entities::Event],
) -> Result<()> {
Err(AllSourceError::StorageError(
"simulated archive outage".to_string(),
))
}
}
let mut retention = RetentionConfig::default();
retention.set("alice", Some(Duration::from_hours(30 * 24)));
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
retention,
archive: Some(Arc::new(FailingArchive) as Arc<dyn ArchiveTarget>),
..Default::default()
};
let manager = CompactionManager::new(live_dir.path(), config);
let result = manager.compact_tenant("alice");
assert!(result.is_err(), "compaction must fail when archive fails");
// Originals still on disk — every event still queryable.
let after = count_files(live_dir.path());
assert_eq!(
before, after,
"no files should be removed after archive failure"
);
let storage2 = ParquetStorage::new(live_dir.path()).unwrap();
let loaded = storage2.load_events_for_tenant("alice").unwrap();
assert_eq!(
loaded.len(),
20,
"all 20 events still present after failed archive"
);
}
#[test]
fn test_cold_tier_not_invoked_when_no_events_dropped() {
// If retention drops zero events (e.g. tenant has no TTL),
// the archive target must NOT be called. We assert by using
// an archive that panics on call.
let live_dir = TempDir::new().unwrap();
let storage = ParquetStorage::new(live_dir.path()).unwrap();
let now = Utc::now();
for i in 0..10 {
let ts = now - chrono::Duration::hours(i);
let event = crate::domain::entities::Event::reconstruct_from_strings(
uuid::Uuid::new_v4(),
"test.event".to_string(),
format!("e-{i}"),
"alice".to_string(),
serde_json::json!({"i": i}),
ts,
None,
1,
);
storage.append_event(event).unwrap();
if i % 3 == 2 {
storage.flush().unwrap();
}
}
storage.flush().unwrap();
#[derive(Debug)]
struct PanickingArchive;
impl ArchiveTarget for PanickingArchive {
fn archive(
&self,
_: &str,
_: DateTime<Utc>,
_: DateTime<Utc>,
_: &[crate::domain::entities::Event],
) -> Result<()> {
panic!("archive must not be called when no events are dropped");
}
}
// Default retention → alice has no TTL → no events dropped.
let config = CompactionConfig {
min_files_to_compact: 2,
small_file_threshold: 100 * 1024 * 1024,
strategy: CompactionStrategy::SizeBased,
archive: Some(Arc::new(PanickingArchive) as Arc<dyn ArchiveTarget>),
..Default::default()
};
let manager = CompactionManager::new(live_dir.path(), config);
let result = manager.compact_tenant("alice").unwrap();
assert_eq!(result.events_compacted, 10);
}
#[test]
fn test_discover_tenants_skips_system_and_hidden() {
// Ensure the tenant scan doesn't pick up __system or hidden
// directories — they're internal, not real tenants.
let temp_dir = TempDir::new().unwrap();
std::fs::create_dir_all(temp_dir.path().join("alice")).unwrap();
std::fs::create_dir_all(temp_dir.path().join("bob")).unwrap();
std::fs::create_dir_all(temp_dir.path().join("__system")).unwrap();
std::fs::create_dir_all(temp_dir.path().join(".hidden")).unwrap();
let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
let tenants = manager.discover_tenants().unwrap();
assert_eq!(tenants, vec!["alice".to_string(), "bob".to_string()]);
}
}