1use crate::{
2 error::{AllSourceError, Result},
3 infrastructure::persistence::{cold_tier::ArchiveTarget, storage::ParquetStorage},
4};
5use chrono::{DateTime, Utc};
6use parking_lot::RwLock;
7use serde::{Deserialize, Serialize};
8use std::{collections::HashMap, fs, path::PathBuf, sync::Arc, time::Duration};
9
10pub struct CompactionManager {
20 storage_dir: PathBuf,
22
23 config: CompactionConfig,
25
26 stats: Arc<RwLock<CompactionStats>>,
28
29 last_compaction: Arc<RwLock<Option<DateTime<Utc>>>>,
31
32 sweep_cursor: Arc<RwLock<Option<String>>>,
39}
40
41const SNAPSHOT_PREFIX: &str = "snapshot.";
50
51#[derive(Debug, Clone)]
52pub struct CompactionConfig {
53 pub min_files_to_compact: usize,
55
56 pub target_file_size: usize,
58
59 pub max_file_size: usize,
61
62 pub small_file_threshold: usize,
64
65 pub max_input_bytes_per_snapshot: u64,
72
73 pub max_input_files_per_snapshot: usize,
76
77 pub max_pass_seconds: u64,
85
86 pub compaction_interval_seconds: u64,
88
89 pub auto_compact: bool,
91
92 pub strategy: CompactionStrategy,
94
95 pub retention: RetentionConfig,
102
103 pub archive: Option<Arc<dyn ArchiveTarget>>,
111}
112
113#[derive(Debug, Clone)]
127pub struct RetentionConfig {
128 pub default_ttl: Option<Duration>,
130 pub per_tenant_ttl: HashMap<String, Option<Duration>>,
135}
136
137impl Default for RetentionConfig {
138 fn default() -> Self {
139 let mut per_tenant_ttl = HashMap::new();
140 per_tenant_ttl.insert("system".to_string(), Some(Duration::from_hours(30 * 24)));
141 Self {
142 default_ttl: None,
143 per_tenant_ttl,
144 }
145 }
146}
147
148impl RetentionConfig {
149 pub fn ttl_for(&self, tenant_id: &str) -> Option<Duration> {
156 match self.per_tenant_ttl.get(tenant_id) {
157 Some(v) => *v,
158 None => self.default_ttl,
159 }
160 }
161
162 pub fn set(&mut self, tenant_id: &str, ttl: Option<Duration>) {
165 self.per_tenant_ttl.insert(tenant_id.to_string(), ttl);
166 }
167}
168
169impl Default for CompactionConfig {
170 fn default() -> Self {
171 Self {
172 min_files_to_compact: 3,
173 target_file_size: 128 * 1024 * 1024, max_file_size: 256 * 1024 * 1024, small_file_threshold: 10 * 1024 * 1024, max_input_bytes_per_snapshot: 32 * 1024 * 1024, max_input_files_per_snapshot: 2000,
178 max_pass_seconds: 240,
179 compaction_interval_seconds: 3600, auto_compact: true,
181 strategy: CompactionStrategy::SizeBased,
182 retention: RetentionConfig::default(),
183 archive: None,
184 }
185 }
186}
187
188impl CompactionConfig {
189 pub fn from_env() -> Self {
200 let config = Self::from_env_vars(
201 std::env::var("ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS").ok(),
202 std::env::var("ALLSOURCE_RETENTION_SYSTEM_DAYS").ok(),
203 )
204 .with_input_bytes(std::env::var("ALLSOURCE_COMPACTION_INPUT_BYTES").ok());
205 config.with_cold_storage_url(std::env::var("ALLSOURCE_COLD_STORAGE_URL").ok())
206 }
207
208 pub fn with_input_bytes(mut self, bytes_var: Option<String>) -> Self {
211 if let Some(s) = bytes_var.filter(|s| !s.trim().is_empty()) {
212 match s.trim().parse::<u64>() {
213 Ok(v) if v > 0 => self.max_input_bytes_per_snapshot = v,
214 Ok(_) => tracing::warn!(
215 "ALLSOURCE_COMPACTION_INPUT_BYTES=0 is not a usable bound; keeping {}",
216 self.max_input_bytes_per_snapshot
217 ),
218 Err(e) => tracing::warn!(
219 "ALLSOURCE_COMPACTION_INPUT_BYTES={s:?} could not be parsed as u64: {e}; \
220 keeping {}",
221 self.max_input_bytes_per_snapshot
222 ),
223 }
224 }
225 self
226 }
227
228 #[allow(unused_variables, unused_mut)]
238 pub fn with_cold_storage_url(mut self, url: Option<String>) -> Self {
239 let Some(url) = url.filter(|u| !u.trim().is_empty()) else {
240 return self;
241 };
242
243 #[cfg(feature = "cold-tier-s3")]
244 {
245 match super::cold_tier_s3::S3Archive::from_url(url.trim()) {
246 Ok(archive) => {
247 tracing::info!(
248 target = %super::cold_tier::ArchiveTarget::description(&archive),
249 "cold-tier archive enabled"
250 );
251 self.archive = Some(std::sync::Arc::new(archive));
252 }
253 Err(e) => panic!("ALLSOURCE_COLD_STORAGE_URL={url:?} is set but unusable: {e}"),
254 }
255 }
256
257 #[cfg(not(feature = "cold-tier-s3"))]
258 panic!(
259 "ALLSOURCE_COLD_STORAGE_URL={url:?} is set but this binary was built without the \
260 `cold-tier-s3` feature, so nothing would be archived before retention deletes it. \
261 Rebuild with --features cold-tier-s3, or unset the variable."
262 );
263
264 #[cfg(feature = "cold-tier-s3")]
265 self
266 }
267
268 pub fn from_env_vars(
271 interval_var: Option<String>,
272 system_retention_days_var: Option<String>,
273 ) -> Self {
274 let mut config = Self::default();
275 if let Some(s) = interval_var.filter(|s| !s.is_empty()) {
276 match s.parse::<u64>() {
277 Ok(v) => config.compaction_interval_seconds = v,
278 Err(e) => {
279 tracing::warn!(
280 "ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS={s:?} could not be parsed as \
281 u64: {e}; defaulting to {}s",
282 config.compaction_interval_seconds
283 );
284 }
285 }
286 }
287 if let Some(s) = system_retention_days_var.filter(|s| !s.is_empty()) {
288 match s.parse::<u64>() {
289 Ok(0) => {
297 tracing::info!(
298 "ALLSOURCE_RETENTION_SYSTEM_DAYS=0: retention disabled for tenant=system"
299 );
300 config.retention.set("system", None);
301 }
302 Ok(days) => {
303 config
304 .retention
305 .set("system", Some(Duration::from_secs(days * 24 * 3600)));
306 }
307 Err(e) => {
308 tracing::warn!(
309 "ALLSOURCE_RETENTION_SYSTEM_DAYS={s:?} could not be parsed as u64: \
310 {e}; defaulting to 30 days for tenant=system"
311 );
312 }
313 }
314 }
315 config
316 }
317
318 pub fn from_env_var(interval_var: Option<String>) -> Self {
321 Self::from_env_vars(interval_var, None)
322 }
323}
324
325#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
326#[serde(rename_all = "lowercase")]
327pub enum CompactionStrategy {
328 SizeBased,
330 TimeBased,
332 FullCompaction,
334}
335
336#[derive(Debug, Clone, Default, Serialize)]
337pub struct CompactionStats {
338 pub total_compactions: u64,
339 pub total_files_compacted: u64,
340 pub total_bytes_before: u64,
341 pub total_bytes_after: u64,
342 pub total_events_compacted: u64,
343 pub last_compaction_duration_ms: u64,
344 pub space_saved_bytes: u64,
345}
346
347#[derive(Debug, Clone)]
349struct FileInfo {
350 path: PathBuf,
351 size: u64,
352 created: DateTime<Utc>,
353}
354
355impl CompactionManager {
356 pub fn new(storage_dir: impl Into<PathBuf>, config: CompactionConfig) -> Self {
358 let storage_dir = storage_dir.into();
359
360 tracing::info!(
361 "✅ Compaction manager initialized at: {}",
362 storage_dir.display()
363 );
364
365 Self {
366 storage_dir,
367 config,
368 stats: Arc::new(RwLock::new(CompactionStats::default())),
369 last_compaction: Arc::new(RwLock::new(None)),
370 sweep_cursor: Arc::new(RwLock::new(None)),
371 }
372 }
373
374 fn list_parquet_files(&self) -> Result<Vec<FileInfo>> {
376 let entries = fs::read_dir(&self.storage_dir).map_err(|e| {
377 AllSourceError::StorageError(format!("Failed to read storage directory: {e}"))
378 })?;
379
380 let mut files = Vec::new();
381
382 for entry in entries {
383 let entry = entry.map_err(|e| {
384 AllSourceError::StorageError(format!("Failed to read directory entry: {e}"))
385 })?;
386
387 let path = entry.path();
388 if let Some(ext) = path.extension()
389 && ext == "parquet"
390 {
391 let metadata = entry.metadata().map_err(|e| {
392 AllSourceError::StorageError(format!("Failed to read file metadata: {e}"))
393 })?;
394
395 let size = metadata.len();
396 let created = metadata
397 .created()
398 .ok()
399 .and_then(|t| {
400 t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| {
401 DateTime::from_timestamp(d.as_secs() as i64, 0).unwrap_or_else(Utc::now)
402 })
403 })
404 .unwrap_or_else(Utc::now);
405
406 files.push(FileInfo {
407 path,
408 size,
409 created,
410 });
411 }
412 }
413
414 files.sort_by_key(|f| f.created);
416
417 Ok(files)
418 }
419
420 fn select_files_for_compaction(&self, files: &[FileInfo]) -> Vec<FileInfo> {
422 match self.config.strategy {
423 CompactionStrategy::SizeBased => self.select_small_files(files),
424 CompactionStrategy::TimeBased => self.select_old_files(files),
425 CompactionStrategy::FullCompaction => files.to_vec(),
426 }
427 }
428
429 fn select_small_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
431 let small_files: Vec<FileInfo> = files
432 .iter()
433 .filter(|f| f.size < self.config.small_file_threshold as u64)
434 .cloned()
435 .collect();
436
437 if small_files.len() >= self.config.min_files_to_compact {
439 small_files
440 } else {
441 Vec::new()
442 }
443 }
444
445 fn select_old_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
447 let now = Utc::now();
448 let age_threshold = chrono::Duration::hours(24); let old_files: Vec<FileInfo> = files
451 .iter()
452 .filter(|f| now - f.created > age_threshold)
453 .cloned()
454 .collect();
455
456 if old_files.len() >= self.config.min_files_to_compact {
457 old_files
458 } else {
459 Vec::new()
460 }
461 }
462
463 #[cfg_attr(feature = "hotpath", hotpath::measure)]
465 pub fn should_compact(&self) -> bool {
466 if !self.config.auto_compact {
467 return false;
468 }
469
470 let last = self.last_compaction.read();
471 match *last {
472 None => true, Some(last_time) => {
474 let elapsed = (Utc::now() - last_time).num_seconds();
475 elapsed >= self.config.compaction_interval_seconds as i64
476 }
477 }
478 }
479
480 #[cfg_attr(feature = "hotpath", hotpath::measure)]
498 pub fn compact(&self) -> Result<CompactionResult> {
499 self.compact_until(None)
500 }
501
502 pub fn sweep_cursor(&self) -> Option<String> {
507 self.sweep_cursor.read().clone()
508 }
509
510 pub fn compact_until(&self, deadline: Option<std::time::Instant>) -> Result<CompactionResult> {
513 let start_time = std::time::Instant::now();
514 tracing::info!("🔄 Starting per-tenant compaction sweep...");
515
516 let tenants = self.discover_tenants()?;
517 if tenants.is_empty() {
518 tracing::debug!("No tenants found under {}", self.storage_dir.display());
519 *self.last_compaction.write() = Some(Utc::now());
523 return Ok(CompactionResult::default());
524 }
525
526 let tenants = self.rotate_to_cursor(tenants);
527 let deadline = deadline.unwrap_or_else(|| {
528 start_time + Duration::from_secs(self.config.max_pass_seconds.max(1))
529 });
530 let mut aggregate = CompactionResult::default();
531 let mut unvisited = 0usize;
532 let mut resume_at: Option<&String> = None;
536 for tenant in &tenants {
537 if std::time::Instant::now() >= deadline {
538 unvisited += 1;
539 resume_at = resume_at.or(Some(tenant));
540 continue;
541 }
542 match self.sweep_tenant(tenant, Some(deadline)) {
543 Ok((r, complete)) => {
544 aggregate.files_compacted += r.files_compacted;
545 aggregate.bytes_before += r.bytes_before;
546 aggregate.bytes_after += r.bytes_after;
547 aggregate.events_compacted += r.events_compacted;
548 if !complete {
549 resume_at = resume_at.or(Some(tenant));
550 }
551 }
552 Err(e) => {
553 tracing::error!(
554 tenant_id = %tenant,
555 "compact_tenant failed: {e}"
556 );
557 }
558 }
559 }
560 *self.sweep_cursor.write() = resume_at.or(tenants.first()).cloned();
563 if unvisited > 0 {
564 tracing::info!(
565 unvisited_tenants = unvisited,
566 resume_at = ?resume_at,
567 budget_secs = self.config.max_pass_seconds,
568 "compaction sweep hit its time budget; resuming next tick"
569 );
570 }
571 aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
572
573 if aggregate.files_compacted > 0 {
574 let mut stats = self.stats.write();
575 stats.total_compactions += 1;
576 stats.total_files_compacted += aggregate.files_compacted as u64;
577 stats.total_bytes_before += aggregate.bytes_before;
578 stats.total_bytes_after += aggregate.bytes_after;
579 stats.total_events_compacted += aggregate.events_compacted as u64;
580 stats.last_compaction_duration_ms = aggregate.duration_ms;
581 stats.space_saved_bytes += aggregate.bytes_before.saturating_sub(aggregate.bytes_after);
582 }
583 *self.last_compaction.write() = Some(Utc::now());
584
585 tracing::info!(
586 "✅ Compaction sweep complete: {} files → 1 snapshot per tenant, \
587 {:.2} MB → {:.2} MB, {} events, {} tenants in {}ms",
588 aggregate.files_compacted,
589 aggregate.bytes_before as f64 / (1024.0 * 1024.0),
590 aggregate.bytes_after as f64 / (1024.0 * 1024.0),
591 aggregate.events_compacted,
592 tenants.len(),
593 aggregate.duration_ms
594 );
595
596 Ok(aggregate)
597 }
598
599 pub fn compact_tenant(&self, tenant_id: &str) -> Result<CompactionResult> {
620 self.compact_tenant_until(tenant_id, None)
621 }
622
623 pub fn compact_tenant_until(
628 &self,
629 tenant_id: &str,
630 deadline: Option<std::time::Instant>,
631 ) -> Result<CompactionResult> {
632 self.sweep_tenant(tenant_id, deadline)
633 .map(|(result, _complete)| result)
634 }
635
636 fn sweep_tenant(
641 &self,
642 tenant_id: &str,
643 deadline: Option<std::time::Instant>,
644 ) -> Result<(CompactionResult, bool)> {
645 let start_time = std::time::Instant::now();
646
647 let storage = ParquetStorage::new(&self.storage_dir)?;
648 let all_files = storage.list_parquet_files_for_tenant(tenant_id)?;
649 let threshold = self.config.small_file_threshold as u64;
650 let raw_files: Vec<FileInfo> = all_files
651 .into_iter()
652 .filter_map(|p| {
653 let metadata = fs::metadata(&p).ok()?;
654 let size = metadata.len();
655 let is_snapshot = p
656 .file_name()
657 .and_then(|n| n.to_str())
658 .is_some_and(|n| n.starts_with(SNAPSHOT_PREFIX));
659 if is_snapshot && size >= threshold {
663 return None;
664 }
665 let created = metadata
666 .created()
667 .ok()
668 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
669 .and_then(|d| DateTime::from_timestamp(d.as_secs() as i64, 0))
670 .unwrap_or_else(Utc::now);
671 Some(FileInfo {
672 path: p,
673 size,
674 created,
675 })
676 })
677 .collect();
678
679 let mut candidates = self.select_files_for_compaction(&raw_files);
680 if candidates.is_empty() {
681 tracing::debug!(
682 tenant_id = tenant_id,
683 strategy = ?self.config.strategy,
684 "no files meet compaction criteria"
685 );
686 return Ok((CompactionResult::default(), true));
687 }
688 candidates.sort_by_key(|f| f.created);
691
692 let total_bytes: u64 = candidates.iter().map(|f| f.size).sum();
693 let groups = self.split_into_bounded_groups(candidates);
694 tracing::info!(
695 tenant_id = tenant_id,
696 groups = groups.len(),
697 mib = total_bytes as f64 / (1024.0 * 1024.0),
698 "compacting tenant"
699 );
700
701 let total_groups = groups.len();
702 let mut aggregate = CompactionResult::default();
703 let mut done = 0usize;
704 let mut first_error = None;
710 let mut complete = true;
711 for group in groups {
712 if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
713 tracing::info!(
714 tenant_id = tenant_id,
715 groups_done = done,
716 groups_total = total_groups,
717 "tenant compaction paused on the sweep budget"
718 );
719 complete = false;
720 break;
721 }
722 match self.compact_group(tenant_id, &storage, &group) {
723 Ok(result) => {
724 aggregate.files_compacted += result.files_compacted;
725 aggregate.bytes_before += result.bytes_before;
726 aggregate.bytes_after += result.bytes_after;
727 aggregate.events_compacted += result.events_compacted;
728 done += 1;
729 }
730 Err(error) => {
731 tracing::error!(
732 tenant_id = tenant_id,
733 files = group.len(),
734 "compaction group failed: {error}"
735 );
736 if first_error.is_none() {
737 first_error = Some(error);
738 }
739 }
740 }
741 }
742 if let Some(error) = first_error {
743 return Err(error);
744 }
745 aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
746 Ok((aggregate, complete))
747 }
748
749 fn split_into_bounded_groups(&self, candidates: Vec<FileInfo>) -> Vec<Vec<FileInfo>> {
753 let max_bytes = self.config.max_input_bytes_per_snapshot.max(1);
754 let max_files = self.config.max_input_files_per_snapshot.max(1);
755 let mut groups: Vec<Vec<FileInfo>> = Vec::new();
756 let mut current: Vec<FileInfo> = Vec::new();
757 let mut current_bytes = 0u64;
758 for file in candidates {
759 let would_exceed = !current.is_empty()
760 && (current_bytes + file.size > max_bytes || current.len() >= max_files);
761 if would_exceed {
762 groups.push(std::mem::take(&mut current));
763 current_bytes = 0;
764 }
765 current_bytes += file.size;
766 current.push(file);
767 }
768 if !current.is_empty() {
769 groups.push(current);
770 }
771 groups
772 }
773
774 fn compact_group(
777 &self,
778 tenant_id: &str,
779 storage: &ParquetStorage,
780 candidates: &[FileInfo],
781 ) -> Result<CompactionResult> {
782 let start_time = std::time::Instant::now();
783 let bytes_before: u64 = candidates.iter().map(|f| f.size).sum();
784
785 let mut events = Vec::new();
790 for fi in candidates {
791 let event_tenant = match fi.path.strip_prefix(&self.storage_dir).ok() {
794 Some(rel) => rel
795 .components()
796 .next()
797 .and_then(|c| match c {
798 std::path::Component::Normal(t) => Some(t.to_string_lossy().into_owned()),
799 _ => None,
800 })
801 .unwrap_or_else(|| "default".to_string()),
802 None => "default".to_string(),
803 };
804 let mut loaded = storage
808 .load_events_from_file_path(&fi.path, &event_tenant)
809 .map_err(|error| {
810 AllSourceError::StorageError(format!(
811 "Compaction refused unreadable candidate {}: {error}",
812 fi.path.display()
813 ))
814 })?;
815 events.append(&mut loaded);
816 }
817
818 if events.is_empty() {
819 tracing::warn!(
820 tenant_id = tenant_id,
821 "candidate files had no readable events; skipping snapshot"
822 );
823 return Ok(CompactionResult::default());
824 }
825
826 let dropped_by_retention = if let Some(ttl) = self.config.retention.ttl_for(tenant_id) {
842 let cutoff = Utc::now()
843 - chrono::Duration::from_std(ttl).unwrap_or_else(|_| chrono::Duration::zero());
844 let before = events.len();
845
846 let (drained, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut events)
851 .into_iter()
852 .partition(|e| e.timestamp < cutoff);
853 events = kept;
854 let dropped = before - events.len();
855
856 if dropped > 0 {
857 tracing::info!(
858 retention_tenant = tenant_id,
859 dropped = dropped,
860 kept = events.len(),
861 cutoff = %cutoff.to_rfc3339(),
862 ttl_secs = ttl.as_secs(),
863 "retention: dropped events older than TTL"
864 );
865
866 if let Some(archive) = self.config.archive.as_ref() {
867 let from = drained
868 .iter()
869 .map(|e| e.timestamp)
870 .min()
871 .expect("dropped > 0 guarantees non-empty drained");
872 let to = drained
873 .iter()
874 .map(|e| e.timestamp)
875 .max()
876 .expect("dropped > 0 guarantees non-empty drained");
877 archive.archive(tenant_id, from, to, &drained)?;
878 tracing::info!(
879 retention_tenant = tenant_id,
880 archived_to = %archive.description(),
881 archived = drained.len(),
882 "retention: dropped events archived to cold tier"
883 );
884 }
885 }
886 dropped
887 } else {
888 0
889 };
890
891 if events.is_empty() {
899 tracing::info!(
900 tenant_id = tenant_id,
901 files_dropped = candidates.len(),
902 events_dropped = dropped_by_retention,
903 "retention: every event aged out — deleting originals without snapshot"
904 );
905 for fi in candidates {
906 if let Err(e) = fs::remove_file(&fi.path) {
907 tracing::error!(
908 file = %fi.path.display(),
909 "failed to remove fully-aged raw file: {e}"
910 );
911 }
912 }
913 return Ok(CompactionResult {
914 files_compacted: candidates.len(),
915 bytes_before,
916 bytes_after: 0,
917 events_compacted: 0,
918 duration_ms: start_time.elapsed().as_millis() as u64,
919 });
920 }
921
922 events.sort_by_key(|e| e.timestamp);
923 let from = events.first().expect("non-empty checked above").timestamp;
924 let to = events.last().expect("non-empty checked above").timestamp;
925
926 let unique = Utc::now().timestamp_nanos_opt().unwrap_or_default();
932 let file_stem = format!(
933 "snapshot.{tenant_id}.{}-{}.{unique}",
934 format_iso_basic(from),
935 format_iso_basic(to)
936 );
937 let snapshot_path = storage.write_atomic_parquet(tenant_id, &file_stem, &events)?;
938 let bytes_after = fs::metadata(&snapshot_path).map_or(0, |m| m.len());
939
940 for fi in candidates {
944 if fi.path == snapshot_path {
945 continue;
946 }
947 if let Err(e) = fs::remove_file(&fi.path) {
948 tracing::error!(
949 file = %fi.path.display(),
950 "failed to remove pre-snapshot raw file: {e}"
951 );
952 }
953 }
954
955 let duration_ms = start_time.elapsed().as_millis() as u64;
956 tracing::info!(
957 tenant_id = tenant_id,
958 files_compacted = candidates.len(),
959 events = events.len(),
960 dropped_by_retention = dropped_by_retention,
961 mib_before = bytes_before as f64 / (1024.0 * 1024.0),
962 mib_after = bytes_after as f64 / (1024.0 * 1024.0),
963 duration_ms = duration_ms,
964 "tenant compaction group complete"
965 );
966
967 Ok(CompactionResult {
968 files_compacted: candidates.len(),
969 bytes_before,
970 bytes_after,
971 events_compacted: events.len(),
972 duration_ms,
973 })
974 }
975
976 fn rotate_to_cursor(&self, tenants: Vec<String>) -> Vec<String> {
983 let cursor = self.sweep_cursor.read().clone();
984 let Some(cursor) = cursor else {
985 return tenants;
986 };
987 let Some(position) = tenants.iter().position(|tenant| *tenant == cursor) else {
988 return tenants;
989 };
990 let mut rotated = tenants;
991 rotated.rotate_left(position);
992 rotated
993 }
994
995 fn discover_tenants(&self) -> Result<Vec<String>> {
1000 let Ok(entries) = fs::read_dir(&self.storage_dir) else {
1001 return Ok(Vec::new());
1002 };
1003 let mut tenants: Vec<String> = entries
1004 .filter_map(std::result::Result::ok)
1005 .filter_map(|entry| {
1006 let ft = entry.file_type().ok()?;
1007 if !ft.is_dir() {
1008 return None;
1009 }
1010 let name = entry.file_name().to_string_lossy().into_owned();
1011 if name.starts_with('.') || name == "__system" {
1014 return None;
1015 }
1016 Some(name)
1017 })
1018 .collect();
1019 tenants.sort();
1020 Ok(tenants)
1021 }
1022
1023 pub fn stats(&self) -> CompactionStats {
1025 (*self.stats.read()).clone()
1026 }
1027
1028 pub fn config(&self) -> &CompactionConfig {
1030 &self.config
1031 }
1032
1033 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1035 pub fn compact_now(&self) -> Result<CompactionResult> {
1036 tracing::info!("Manual compaction triggered");
1037 self.compact()
1038 }
1039}
1040
1041#[derive(Debug, Clone, Default, Serialize)]
1043pub struct CompactionResult {
1044 pub files_compacted: usize,
1045 pub bytes_before: u64,
1046 pub bytes_after: u64,
1047 pub events_compacted: usize,
1048 pub duration_ms: u64,
1049}
1050
1051pub(super) fn format_iso_basic(t: DateTime<Utc>) -> String {
1057 t.format("%Y-%m-%dT%H%M%SZ").to_string()
1058}
1059
1060pub struct CompactionTask {
1062 manager: Arc<CompactionManager>,
1063 interval: Duration,
1064}
1065
1066impl CompactionTask {
1067 pub fn new(manager: Arc<CompactionManager>, interval_seconds: u64) -> Self {
1069 Self {
1070 manager,
1071 interval: Duration::from_secs(interval_seconds),
1072 }
1073 }
1074
1075 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1077 pub async fn run(self) {
1078 let mut interval = tokio::time::interval(self.interval);
1079
1080 loop {
1081 interval.tick().await;
1082
1083 if self.manager.should_compact() {
1084 tracing::debug!("Auto-compaction check triggered");
1085
1086 match self.manager.compact() {
1087 Ok(result) => {
1088 if result.files_compacted > 0 {
1089 tracing::info!(
1090 "Auto-compaction succeeded: {} files, {:.2} MB saved",
1091 result.files_compacted,
1092 (result.bytes_before - result.bytes_after) as f64
1093 / (1024.0 * 1024.0)
1094 );
1095 }
1096 }
1097 Err(e) => {
1098 tracing::error!("Auto-compaction failed: {}", e);
1099 }
1100 }
1101 }
1102 }
1103 }
1104}
1105
1106#[cfg(test)]
1107mod tests {
1108 use super::*;
1109 use tempfile::TempDir;
1110
1111 #[test]
1112 fn test_compaction_manager_creation() {
1113 let temp_dir = TempDir::new().unwrap();
1114 let config = CompactionConfig::default();
1115 let manager = CompactionManager::new(temp_dir.path(), config);
1116
1117 assert_eq!(manager.stats().total_compactions, 0);
1118 }
1119
1120 #[test]
1121 fn test_should_compact() {
1122 let temp_dir = TempDir::new().unwrap();
1123 let config = CompactionConfig {
1124 auto_compact: true,
1125 compaction_interval_seconds: 1,
1126 ..Default::default()
1127 };
1128 let manager = CompactionManager::new(temp_dir.path(), config);
1129
1130 assert!(manager.should_compact());
1132 }
1133
1134 #[test]
1135 fn test_file_selection_size_based() {
1136 let temp_dir = TempDir::new().unwrap();
1137 let config = CompactionConfig {
1138 small_file_threshold: 1024 * 1024, min_files_to_compact: 2,
1140 strategy: CompactionStrategy::SizeBased,
1141 ..Default::default()
1142 };
1143 let manager = CompactionManager::new(temp_dir.path(), config);
1144
1145 let files = vec![
1146 FileInfo {
1147 path: PathBuf::from("small1.parquet"),
1148 size: 500_000, created: Utc::now(),
1150 },
1151 FileInfo {
1152 path: PathBuf::from("small2.parquet"),
1153 size: 600_000, created: Utc::now(),
1155 },
1156 FileInfo {
1157 path: PathBuf::from("large.parquet"),
1158 size: 10_000_000, created: Utc::now(),
1160 },
1161 ];
1162
1163 let selected = manager.select_files_for_compaction(&files);
1164 assert_eq!(selected.len(), 2); }
1166
1167 #[test]
1168 fn test_default_compaction_config() {
1169 let config = CompactionConfig::default();
1170 assert_eq!(config.min_files_to_compact, 3);
1171 assert_eq!(config.target_file_size, 128 * 1024 * 1024);
1172 assert_eq!(config.max_file_size, 256 * 1024 * 1024);
1173 assert_eq!(config.small_file_threshold, 10 * 1024 * 1024);
1174 assert_eq!(config.compaction_interval_seconds, 3600);
1175 assert!(config.auto_compact);
1176 assert_eq!(config.strategy, CompactionStrategy::SizeBased);
1177 }
1178
1179 #[test]
1180 fn test_should_compact_disabled() {
1181 let temp_dir = TempDir::new().unwrap();
1182 let config = CompactionConfig {
1183 auto_compact: false,
1184 ..Default::default()
1185 };
1186 let manager = CompactionManager::new(temp_dir.path(), config);
1187
1188 assert!(!manager.should_compact());
1189 }
1190
1191 #[test]
1192 fn test_compact_empty_directory() {
1193 let temp_dir = TempDir::new().unwrap();
1194 let config = CompactionConfig::default();
1195 let manager = CompactionManager::new(temp_dir.path(), config);
1196
1197 let result = manager.compact().unwrap();
1198 assert_eq!(result.files_compacted, 0);
1199 assert_eq!(result.bytes_before, 0);
1200 assert_eq!(result.bytes_after, 0);
1201 assert_eq!(result.events_compacted, 0);
1202 }
1203
1204 #[test]
1205 fn test_compact_now() {
1206 let temp_dir = TempDir::new().unwrap();
1207 let config = CompactionConfig::default();
1208 let manager = CompactionManager::new(temp_dir.path(), config);
1209
1210 let result = manager.compact_now().unwrap();
1211 assert_eq!(result.files_compacted, 0);
1212 }
1213
1214 #[test]
1215 fn test_get_config() {
1216 let temp_dir = TempDir::new().unwrap();
1217 let config = CompactionConfig {
1218 min_files_to_compact: 5,
1219 ..Default::default()
1220 };
1221 let manager = CompactionManager::new(temp_dir.path(), config);
1222
1223 assert_eq!(manager.config().min_files_to_compact, 5);
1224 }
1225
1226 #[test]
1227 fn test_get_stats() {
1228 let temp_dir = TempDir::new().unwrap();
1229 let config = CompactionConfig::default();
1230 let manager = CompactionManager::new(temp_dir.path(), config);
1231
1232 let stats = manager.stats();
1233 assert_eq!(stats.total_compactions, 0);
1234 assert_eq!(stats.total_files_compacted, 0);
1235 assert_eq!(stats.total_bytes_before, 0);
1236 assert_eq!(stats.total_bytes_after, 0);
1237 assert_eq!(stats.total_events_compacted, 0);
1238 assert_eq!(stats.last_compaction_duration_ms, 0);
1239 assert_eq!(stats.space_saved_bytes, 0);
1240 }
1241
1242 #[test]
1243 fn test_file_selection_not_enough_small_files() {
1244 let temp_dir = TempDir::new().unwrap();
1245 let config = CompactionConfig {
1246 small_file_threshold: 1024 * 1024,
1247 min_files_to_compact: 3, strategy: CompactionStrategy::SizeBased,
1249 ..Default::default()
1250 };
1251 let manager = CompactionManager::new(temp_dir.path(), config);
1252
1253 let files = vec![
1254 FileInfo {
1255 path: PathBuf::from("small1.parquet"),
1256 size: 500_000,
1257 created: Utc::now(),
1258 },
1259 FileInfo {
1260 path: PathBuf::from("small2.parquet"),
1261 size: 600_000,
1262 created: Utc::now(),
1263 },
1264 ];
1265
1266 let selected = manager.select_files_for_compaction(&files);
1267 assert_eq!(selected.len(), 0); }
1269
1270 #[test]
1271 fn test_file_selection_time_based() {
1272 let temp_dir = TempDir::new().unwrap();
1273 let config = CompactionConfig {
1274 min_files_to_compact: 2,
1275 strategy: CompactionStrategy::TimeBased,
1276 ..Default::default()
1277 };
1278 let manager = CompactionManager::new(temp_dir.path(), config);
1279
1280 let old_time = Utc::now() - chrono::Duration::hours(48);
1281 let files = vec![
1282 FileInfo {
1283 path: PathBuf::from("old1.parquet"),
1284 size: 1_000_000,
1285 created: old_time,
1286 },
1287 FileInfo {
1288 path: PathBuf::from("old2.parquet"),
1289 size: 2_000_000,
1290 created: old_time,
1291 },
1292 FileInfo {
1293 path: PathBuf::from("new.parquet"),
1294 size: 500_000,
1295 created: Utc::now(),
1296 },
1297 ];
1298
1299 let selected = manager.select_files_for_compaction(&files);
1300 assert_eq!(selected.len(), 2); }
1302
1303 #[test]
1304 fn test_file_selection_time_based_not_enough() {
1305 let temp_dir = TempDir::new().unwrap();
1306 let config = CompactionConfig {
1307 min_files_to_compact: 3,
1308 strategy: CompactionStrategy::TimeBased,
1309 ..Default::default()
1310 };
1311 let manager = CompactionManager::new(temp_dir.path(), config);
1312
1313 let old_time = Utc::now() - chrono::Duration::hours(48);
1314 let files = vec![
1315 FileInfo {
1316 path: PathBuf::from("old1.parquet"),
1317 size: 1_000_000,
1318 created: old_time,
1319 },
1320 FileInfo {
1321 path: PathBuf::from("new.parquet"),
1322 size: 500_000,
1323 created: Utc::now(),
1324 },
1325 ];
1326
1327 let selected = manager.select_files_for_compaction(&files);
1328 assert_eq!(selected.len(), 0); }
1330
1331 #[test]
1332 fn test_file_selection_full_compaction() {
1333 let temp_dir = TempDir::new().unwrap();
1334 let config = CompactionConfig {
1335 strategy: CompactionStrategy::FullCompaction,
1336 ..Default::default()
1337 };
1338 let manager = CompactionManager::new(temp_dir.path(), config);
1339
1340 let files = vec![
1341 FileInfo {
1342 path: PathBuf::from("file1.parquet"),
1343 size: 1_000_000,
1344 created: Utc::now(),
1345 },
1346 FileInfo {
1347 path: PathBuf::from("file2.parquet"),
1348 size: 2_000_000,
1349 created: Utc::now(),
1350 },
1351 ];
1352
1353 let selected = manager.select_files_for_compaction(&files);
1354 assert_eq!(selected.len(), 2); }
1356
1357 #[test]
1358 fn test_compaction_strategy_serde() {
1359 let strategies = vec![
1360 CompactionStrategy::SizeBased,
1361 CompactionStrategy::TimeBased,
1362 CompactionStrategy::FullCompaction,
1363 ];
1364
1365 for strategy in strategies {
1366 let json = serde_json::to_string(&strategy).unwrap();
1367 let parsed: CompactionStrategy = serde_json::from_str(&json).unwrap();
1368 assert_eq!(parsed, strategy);
1369 }
1370 }
1371
1372 #[test]
1373 fn test_compaction_stats_default() {
1374 let stats = CompactionStats::default();
1375 assert_eq!(stats.total_compactions, 0);
1376 assert_eq!(stats.total_files_compacted, 0);
1377 }
1378
1379 #[test]
1380 fn test_compaction_stats_serde() {
1381 let stats = CompactionStats {
1382 total_compactions: 5,
1383 total_files_compacted: 20,
1384 total_bytes_before: 1000000,
1385 total_bytes_after: 500000,
1386 total_events_compacted: 10000,
1387 last_compaction_duration_ms: 500,
1388 space_saved_bytes: 500000,
1389 };
1390
1391 let json = serde_json::to_string(&stats).unwrap();
1392 assert!(json.contains("\"total_compactions\":5"));
1393 assert!(json.contains("\"space_saved_bytes\":500000"));
1394 }
1395
1396 #[test]
1397 fn test_compaction_result_serde() {
1398 let result = CompactionResult {
1399 files_compacted: 3,
1400 bytes_before: 1000000,
1401 bytes_after: 500000,
1402 events_compacted: 5000,
1403 duration_ms: 250,
1404 };
1405
1406 let json = serde_json::to_string(&result).unwrap();
1407 assert!(json.contains("\"files_compacted\":3"));
1408 assert!(json.contains("\"bytes_before\":1000000"));
1409 }
1410
1411 #[test]
1412 fn test_compaction_task_creation() {
1413 let temp_dir = TempDir::new().unwrap();
1414 let config = CompactionConfig::default();
1415 let manager = Arc::new(CompactionManager::new(temp_dir.path(), config));
1416
1417 let _task = CompactionTask::new(manager.clone(), 60);
1418 }
1420
1421 #[test]
1422 fn test_list_parquet_files_empty() {
1423 let temp_dir = TempDir::new().unwrap();
1424 let config = CompactionConfig::default();
1425 let manager = CompactionManager::new(temp_dir.path(), config);
1426
1427 let files = manager.list_parquet_files().unwrap();
1428 assert!(files.is_empty());
1429 }
1430
1431 #[test]
1432 fn test_list_parquet_files_with_non_parquet() {
1433 let temp_dir = TempDir::new().unwrap();
1434 let config = CompactionConfig::default();
1435 let manager = CompactionManager::new(temp_dir.path(), config);
1436
1437 std::fs::write(temp_dir.path().join("test.txt"), "test").unwrap();
1439 std::fs::write(temp_dir.path().join("data.json"), "{}").unwrap();
1440
1441 let files = manager.list_parquet_files().unwrap();
1442 assert!(files.is_empty()); }
1444
1445 fn ingest_and_flush_per_call(storage_dir: &std::path::Path, tenant: &str, count: usize) {
1450 for i in 0..count {
1454 let storage = ParquetStorage::with_config(
1455 storage_dir,
1456 crate::infrastructure::persistence::ParquetStorageConfig {
1457 batch_size: 1,
1458 ..Default::default()
1459 },
1460 )
1461 .unwrap();
1462 let event = crate::domain::entities::Event::from_strings(
1463 "test.event".to_string(),
1464 format!("{tenant}-{i}"),
1465 tenant.to_string(),
1466 serde_json::json!({"i": i}),
1467 None,
1468 )
1469 .unwrap();
1470 storage.append_event(event).unwrap();
1471 storage.flush().unwrap();
1472 }
1473 }
1474
1475 #[test]
1476 fn test_compact_tenant_emits_one_snapshot_and_removes_originals() {
1477 let temp_dir = TempDir::new().unwrap();
1478
1479 ingest_and_flush_per_call(temp_dir.path(), "alice", 4);
1481
1482 let config = CompactionConfig {
1483 min_files_to_compact: 2,
1484 small_file_threshold: 100 * 1024 * 1024,
1485 strategy: CompactionStrategy::SizeBased,
1486 ..Default::default()
1487 };
1488 let manager = CompactionManager::new(temp_dir.path(), config);
1489
1490 let result = manager.compact_tenant("alice").unwrap();
1491 assert_eq!(result.files_compacted, 4);
1492 assert_eq!(result.events_compacted, 4);
1493
1494 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1497 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1498 assert_eq!(
1499 alice_files.len(),
1500 1,
1501 "expected exactly one snapshot file for alice"
1502 );
1503
1504 let name = alice_files[0]
1505 .file_name()
1506 .and_then(|n| n.to_str())
1507 .unwrap()
1508 .to_string();
1509 assert!(
1510 name.starts_with("snapshot.alice."),
1511 "expected snapshot prefix, got {name}"
1512 );
1513 assert!(name.ends_with(".parquet"));
1514
1515 let tmps: Vec<_> = std::fs::read_dir(alice_files[0].parent().unwrap())
1517 .unwrap()
1518 .filter_map(std::result::Result::ok)
1519 .filter(|e| e.path().to_string_lossy().ends_with(".tmp"))
1520 .collect();
1521 assert!(tmps.is_empty());
1522
1523 let loaded = storage.load_events_for_tenant("alice").unwrap();
1525 assert_eq!(loaded.len(), 4);
1526 for e in &loaded {
1527 assert_eq!(e.tenant_id_str(), "alice");
1528 }
1529 }
1530
1531 #[test]
1532 fn test_compact_tenant_skips_existing_snapshot_files() {
1533 let temp_dir = TempDir::new().unwrap();
1538 ingest_and_flush_per_call(temp_dir.path(), "alice", 4);
1539
1540 let config = CompactionConfig {
1541 min_files_to_compact: 2,
1542 small_file_threshold: 100 * 1024 * 1024,
1543 ..Default::default()
1544 };
1545 let manager = CompactionManager::new(temp_dir.path(), config);
1546
1547 let r1 = manager.compact_tenant("alice").unwrap();
1548 assert_eq!(r1.files_compacted, 4);
1549
1550 let r2 = manager.compact_tenant("alice").unwrap();
1551 assert_eq!(r2.files_compacted, 0, "snapshot must not be re-compacted");
1552
1553 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1555 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1556 assert_eq!(alice_files.len(), 1);
1557 }
1558
1559 #[test]
1560 fn test_compact_tenant_below_threshold_is_a_noop() {
1561 let temp_dir = TempDir::new().unwrap();
1563 ingest_and_flush_per_call(temp_dir.path(), "alice", 1);
1564
1565 let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
1566 let result = manager.compact_tenant("alice").unwrap();
1567 assert_eq!(result.files_compacted, 0);
1568
1569 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1571 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1572 assert_eq!(alice_files.len(), 1);
1573 let name = alice_files[0]
1574 .file_name()
1575 .unwrap()
1576 .to_string_lossy()
1577 .into_owned();
1578 assert!(
1579 !name.starts_with("snapshot."),
1580 "raw file must not be renamed"
1581 );
1582 }
1583
1584 #[test]
1585 fn test_compact_iterates_every_tenant() {
1586 let temp_dir = TempDir::new().unwrap();
1589 ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
1590 ingest_and_flush_per_call(temp_dir.path(), "bob", 3);
1591
1592 let config = CompactionConfig {
1593 min_files_to_compact: 2,
1594 small_file_threshold: 100 * 1024 * 1024,
1595 strategy: CompactionStrategy::SizeBased,
1596 ..Default::default()
1597 };
1598 let manager = CompactionManager::new(temp_dir.path(), config);
1599
1600 let result = manager.compact().unwrap();
1601 assert_eq!(result.files_compacted, 6);
1602 assert_eq!(result.events_compacted, 6);
1603
1604 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1605 for tenant in ["alice", "bob"] {
1606 let files = storage.list_parquet_files_for_tenant(tenant).unwrap();
1607 assert_eq!(files.len(), 1, "{tenant} should have one snapshot");
1608 let name = files[0].file_name().unwrap().to_string_lossy().into_owned();
1609 assert!(name.starts_with(&format!("snapshot.{tenant}.")));
1610 }
1611 }
1612
1613 #[test]
1614 fn test_retention_drops_events_older_than_ttl() {
1615 let temp_dir = TempDir::new().unwrap();
1619
1620 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1625 let now = Utc::now();
1626 for i in 0..100 {
1627 let day_offset = 60 - (i * 60 / 99);
1629 let ts = now - chrono::Duration::days(i64::from(day_offset));
1630 let event = crate::domain::entities::Event::reconstruct_from_strings(
1631 uuid::Uuid::new_v4(),
1632 "test.event".to_string(),
1633 format!("e-{i}"),
1634 "alice".to_string(),
1635 serde_json::json!({"i": i}),
1636 ts,
1637 None,
1638 1,
1639 );
1640 storage.append_event(event).unwrap();
1641 if i % 10 == 9 {
1645 storage.flush().unwrap();
1646 }
1647 }
1648 storage.flush().unwrap();
1649
1650 let mut retention = RetentionConfig::default();
1652 retention.set("alice", Some(Duration::from_hours(30 * 24)));
1653 let config = CompactionConfig {
1654 min_files_to_compact: 2,
1655 small_file_threshold: 100 * 1024 * 1024,
1656 strategy: CompactionStrategy::SizeBased,
1657 retention,
1658 ..Default::default()
1659 };
1660 let manager = CompactionManager::new(temp_dir.path(), config);
1661
1662 let result = manager.compact_tenant("alice").unwrap();
1663 assert!(result.events_compacted > 0);
1664 assert!(
1665 result.events_compacted < 100,
1666 "retention should have dropped some events; kept {} of 100",
1667 result.events_compacted
1668 );
1669
1670 let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
1672 let loaded = storage2.load_events_for_tenant("alice").unwrap();
1673 assert_eq!(loaded.len(), result.events_compacted);
1674
1675 let cutoff = Utc::now() - chrono::Duration::days(30);
1678 for e in &loaded {
1679 assert!(
1680 e.timestamp >= cutoff - chrono::Duration::seconds(60),
1681 "event with ts {} survived retention but is older than cutoff {}",
1682 e.timestamp.to_rfc3339(),
1683 cutoff.to_rfc3339()
1684 );
1685 }
1686 }
1687
1688 #[test]
1689 fn test_retention_keeps_forever_by_default_for_non_system_tenants() {
1690 let temp_dir = TempDir::new().unwrap();
1693 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1694 let now = Utc::now();
1695 for i in 0..6 {
1696 let ts = now - chrono::Duration::days(i * 365);
1697 let event = crate::domain::entities::Event::reconstruct_from_strings(
1698 uuid::Uuid::new_v4(),
1699 "test.event".to_string(),
1700 format!("e-{i}"),
1701 "alice".to_string(),
1702 serde_json::json!({"i": i}),
1703 ts,
1704 None,
1705 1,
1706 );
1707 storage.append_event(event).unwrap();
1708 if i % 2 == 1 {
1709 storage.flush().unwrap();
1710 }
1711 }
1712 storage.flush().unwrap();
1713
1714 let config = CompactionConfig {
1716 min_files_to_compact: 2,
1717 small_file_threshold: 100 * 1024 * 1024,
1718 strategy: CompactionStrategy::SizeBased,
1719 ..Default::default()
1720 };
1721 let manager = CompactionManager::new(temp_dir.path(), config);
1722 let result = manager.compact_tenant("alice").unwrap();
1723 assert_eq!(result.events_compacted, 6, "no events should be dropped");
1724 }
1725
1726 #[test]
1727 fn test_retention_system_tenant_default_is_30_days() {
1728 let cfg = RetentionConfig::default();
1732 let ttl = cfg.ttl_for("system").unwrap();
1733 assert_eq!(ttl.as_secs(), 30 * 24 * 3600);
1734 assert!(cfg.ttl_for("acme").is_none());
1736 }
1737
1738 #[test]
1739 fn test_retention_drops_all_events_deletes_originals_without_snapshot() {
1740 let temp_dir = TempDir::new().unwrap();
1744 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1745 let very_old = Utc::now() - chrono::Duration::days(90);
1746 for i in 0..6 {
1747 let event = crate::domain::entities::Event::reconstruct_from_strings(
1748 uuid::Uuid::new_v4(),
1749 "test.event".to_string(),
1750 format!("e-{i}"),
1751 "alice".to_string(),
1752 serde_json::json!({"i": i}),
1753 very_old,
1754 None,
1755 1,
1756 );
1757 storage.append_event(event).unwrap();
1758 if i % 2 == 1 {
1759 storage.flush().unwrap();
1760 }
1761 }
1762 storage.flush().unwrap();
1763
1764 let mut retention = RetentionConfig::default();
1765 retention.set("alice", Some(Duration::from_hours(7 * 24)));
1766 let config = CompactionConfig {
1767 min_files_to_compact: 2,
1768 small_file_threshold: 100 * 1024 * 1024,
1769 strategy: CompactionStrategy::SizeBased,
1770 retention,
1771 ..Default::default()
1772 };
1773 let manager = CompactionManager::new(temp_dir.path(), config);
1774 let result = manager.compact_tenant("alice").unwrap();
1775 assert_eq!(result.events_compacted, 0);
1776 assert!(result.files_compacted >= 2); let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
1780 let alice_files = storage2.list_parquet_files_for_tenant("alice").unwrap();
1781 assert!(alice_files.is_empty(), "all originals should be deleted");
1782 }
1783
1784 #[test]
1785 fn test_compaction_with_simulated_crash_leaves_data_recoverable() {
1786 let temp_dir = TempDir::new().unwrap();
1792
1793 ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
1795
1796 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1798 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1799 let partition = alice_files[0].parent().unwrap().to_path_buf();
1800
1801 let crashed_tmp = partition.join("snapshot.alice.range.parquet.tmp");
1804 std::fs::write(&crashed_tmp, b"partial parquet bytes").unwrap();
1805 assert!(crashed_tmp.is_file());
1806
1807 let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
1809 assert!(
1810 !crashed_tmp.exists(),
1811 "stale tmp file should have been cleaned by ParquetStorage::new"
1812 );
1813
1814 let events = storage2.load_events_for_tenant("alice").unwrap();
1816 assert_eq!(events.len(), 3);
1817 }
1818
1819 #[test]
1820 fn test_cold_tier_archives_dropped_events_before_deletion() {
1821 use crate::infrastructure::persistence::cold_tier::LocalFsArchive;
1827
1828 let live_dir = TempDir::new().unwrap();
1829 let archive_dir = TempDir::new().unwrap();
1830
1831 let storage = ParquetStorage::new(live_dir.path()).unwrap();
1833 let now = Utc::now();
1834 for i in 0..50 {
1835 let day_offset = 60 - (i * 60 / 49);
1836 let ts = now - chrono::Duration::days(i64::from(day_offset));
1837 let event = crate::domain::entities::Event::reconstruct_from_strings(
1838 uuid::Uuid::new_v4(),
1839 "test.event".to_string(),
1840 format!("e-{i}"),
1841 "alice".to_string(),
1842 serde_json::json!({"i": i}),
1843 ts,
1844 None,
1845 1,
1846 );
1847 storage.append_event(event).unwrap();
1848 if i % 5 == 4 {
1849 storage.flush().unwrap();
1850 }
1851 }
1852 storage.flush().unwrap();
1853
1854 let mut retention = RetentionConfig::default();
1856 retention.set("alice", Some(Duration::from_hours(30 * 24)));
1857 let archive: Arc<dyn ArchiveTarget> =
1858 Arc::new(LocalFsArchive::new(archive_dir.path()).unwrap());
1859 let config = CompactionConfig {
1860 min_files_to_compact: 2,
1861 small_file_threshold: 100 * 1024 * 1024,
1862 strategy: CompactionStrategy::SizeBased,
1863 retention,
1864 archive: Some(archive),
1865 ..Default::default()
1866 };
1867 let manager = CompactionManager::new(live_dir.path(), config);
1868
1869 let result = manager.compact_tenant("alice").unwrap();
1870 assert!(result.events_compacted > 0, "some events kept");
1871 assert!(
1872 result.events_compacted < 50,
1873 "some events dropped to retention; kept {} of 50",
1874 result.events_compacted
1875 );
1876
1877 let live_after = ParquetStorage::new(live_dir.path())
1879 .unwrap()
1880 .load_events_for_tenant("alice")
1881 .unwrap();
1882 assert_eq!(live_after.len(), result.events_compacted);
1883
1884 let mut archive_files = vec![];
1887 let mut stack = vec![archive_dir.path().to_path_buf()];
1888 while let Some(d) = stack.pop() {
1889 for entry in std::fs::read_dir(&d).unwrap().flatten() {
1890 let p = entry.path();
1891 if p.is_dir() {
1892 stack.push(p);
1893 } else if p
1894 .file_name()
1895 .is_some_and(|n| n.to_string_lossy().starts_with("archive.alice."))
1896 {
1897 archive_files.push(p);
1898 }
1899 }
1900 }
1901 assert!(
1902 !archive_files.is_empty(),
1903 "archive directory must contain at least one archive.alice.* file"
1904 );
1905
1906 let archive_storage = ParquetStorage::new(archive_dir.path()).unwrap();
1909 let archived = archive_storage.load_events_for_tenant("alice").unwrap();
1910 assert_eq!(
1911 live_after.len() + archived.len(),
1912 50,
1913 "live + archived must equal original event count (live={}, archived={})",
1914 live_after.len(),
1915 archived.len()
1916 );
1917 }
1918
1919 #[test]
1920 fn test_cold_tier_failure_keeps_originals_on_disk() {
1921 let live_dir = TempDir::new().unwrap();
1925 let storage = ParquetStorage::new(live_dir.path()).unwrap();
1926 let now = Utc::now();
1927 for i in 0..20 {
1928 let ts = now - chrono::Duration::days(60 - i);
1929 let event = crate::domain::entities::Event::reconstruct_from_strings(
1930 uuid::Uuid::new_v4(),
1931 "test.event".to_string(),
1932 format!("e-{i}"),
1933 "alice".to_string(),
1934 serde_json::json!({"i": i}),
1935 ts,
1936 None,
1937 1,
1938 );
1939 storage.append_event(event).unwrap();
1940 if i % 5 == 4 {
1941 storage.flush().unwrap();
1942 }
1943 }
1944 storage.flush().unwrap();
1945
1946 let count_files = |dir: &std::path::Path| -> usize {
1949 let mut n = 0;
1950 let mut stack = vec![dir.to_path_buf()];
1951 while let Some(d) = stack.pop() {
1952 for entry in std::fs::read_dir(&d).unwrap().flatten() {
1953 let p = entry.path();
1954 if p.is_dir() {
1955 stack.push(p);
1956 } else if p.extension().is_some_and(|e| e == "parquet") {
1957 n += 1;
1958 }
1959 }
1960 }
1961 n
1962 };
1963 let before = count_files(live_dir.path());
1964 assert!(before > 0);
1965
1966 #[derive(Debug)]
1967 struct FailingArchive;
1968 impl ArchiveTarget for FailingArchive {
1969 fn archive(
1970 &self,
1971 _: &str,
1972 _: DateTime<Utc>,
1973 _: DateTime<Utc>,
1974 _: &[crate::domain::entities::Event],
1975 ) -> Result<()> {
1976 Err(AllSourceError::StorageError(
1977 "simulated archive outage".to_string(),
1978 ))
1979 }
1980 }
1981
1982 let mut retention = RetentionConfig::default();
1983 retention.set("alice", Some(Duration::from_hours(30 * 24)));
1984 let config = CompactionConfig {
1985 min_files_to_compact: 2,
1986 small_file_threshold: 100 * 1024 * 1024,
1987 strategy: CompactionStrategy::SizeBased,
1988 retention,
1989 archive: Some(Arc::new(FailingArchive) as Arc<dyn ArchiveTarget>),
1990 ..Default::default()
1991 };
1992 let manager = CompactionManager::new(live_dir.path(), config);
1993
1994 let result = manager.compact_tenant("alice");
1995 assert!(result.is_err(), "compaction must fail when archive fails");
1996
1997 let after = count_files(live_dir.path());
1999 assert_eq!(
2000 before, after,
2001 "no files should be removed after archive failure"
2002 );
2003
2004 let storage2 = ParquetStorage::new(live_dir.path()).unwrap();
2005 let loaded = storage2.load_events_for_tenant("alice").unwrap();
2006 assert_eq!(
2007 loaded.len(),
2008 20,
2009 "all 20 events still present after failed archive"
2010 );
2011 }
2012
2013 #[test]
2014 fn test_cold_tier_not_invoked_when_no_events_dropped() {
2015 let live_dir = TempDir::new().unwrap();
2019 let storage = ParquetStorage::new(live_dir.path()).unwrap();
2020 let now = Utc::now();
2021 for i in 0..10 {
2022 let ts = now - chrono::Duration::hours(i);
2023 let event = crate::domain::entities::Event::reconstruct_from_strings(
2024 uuid::Uuid::new_v4(),
2025 "test.event".to_string(),
2026 format!("e-{i}"),
2027 "alice".to_string(),
2028 serde_json::json!({"i": i}),
2029 ts,
2030 None,
2031 1,
2032 );
2033 storage.append_event(event).unwrap();
2034 if i % 3 == 2 {
2035 storage.flush().unwrap();
2036 }
2037 }
2038 storage.flush().unwrap();
2039
2040 #[derive(Debug)]
2041 struct PanickingArchive;
2042 impl ArchiveTarget for PanickingArchive {
2043 fn archive(
2044 &self,
2045 _: &str,
2046 _: DateTime<Utc>,
2047 _: DateTime<Utc>,
2048 _: &[crate::domain::entities::Event],
2049 ) -> Result<()> {
2050 panic!("archive must not be called when no events are dropped");
2051 }
2052 }
2053
2054 let config = CompactionConfig {
2056 min_files_to_compact: 2,
2057 small_file_threshold: 100 * 1024 * 1024,
2058 strategy: CompactionStrategy::SizeBased,
2059 archive: Some(Arc::new(PanickingArchive) as Arc<dyn ArchiveTarget>),
2060 ..Default::default()
2061 };
2062 let manager = CompactionManager::new(live_dir.path(), config);
2063 let result = manager.compact_tenant("alice").unwrap();
2064 assert_eq!(result.events_compacted, 10);
2065 }
2066
2067 #[test]
2068 fn test_discover_tenants_skips_system_and_hidden() {
2069 let temp_dir = TempDir::new().unwrap();
2072 std::fs::create_dir_all(temp_dir.path().join("alice")).unwrap();
2073 std::fs::create_dir_all(temp_dir.path().join("bob")).unwrap();
2074 std::fs::create_dir_all(temp_dir.path().join("__system")).unwrap();
2075 std::fs::create_dir_all(temp_dir.path().join(".hidden")).unwrap();
2076
2077 let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
2078 let tenants = manager.discover_tenants().unwrap();
2079 assert_eq!(tenants, vec!["alice".to_string(), "bob".to_string()]);
2080 }
2081}