1use crate::{
2 error::{AllSourceError, Result},
3 infrastructure::persistence::{
4 archive_budget::ArchiveReadLimits,
5 archive_repack::{
6 archive_directory_guard, archive_mutation_guard, read_repack_receipt,
7 repack_archive_file_in_sweep,
8 },
9 cold_tier::ArchiveTarget,
10 storage::ParquetStorage,
11 },
12};
13use chrono::{DateTime, Utc};
14use parking_lot::RwLock;
15use serde::{Deserialize, Serialize};
16use std::{
17 collections::HashMap,
18 fs,
19 path::{Path, PathBuf},
20 sync::Arc,
21 time::Duration,
22};
23
24const SWEEP_STATE_FILE: &str = "_compaction_state.json";
30
31#[derive(Serialize, Deserialize)]
32struct SweepState {
33 last_compaction: DateTime<Utc>,
34 #[serde(default)]
35 paused: bool,
36}
37
38pub struct CompactionManager {
48 storage_dir: PathBuf,
50
51 config: CompactionConfig,
53
54 stats: Arc<RwLock<CompactionStats>>,
56
57 last_compaction: Arc<RwLock<Option<DateTime<Utc>>>>,
59
60 sweep_cursor: Arc<RwLock<Option<String>>>,
67
68 last_sweep_paused: Arc<RwLock<bool>>,
74}
75
76const SNAPSHOT_PREFIX: &str = "snapshot.";
85
86#[derive(Debug, Clone)]
87pub struct CompactionConfig {
88 pub min_files_to_compact: usize,
90
91 pub target_file_size: usize,
93
94 pub max_file_size: usize,
96
97 pub small_file_threshold: usize,
99
100 pub max_input_bytes_per_snapshot: u64,
107
108 pub max_input_files_per_snapshot: usize,
111
112 pub max_pass_seconds: u64,
120
121 pub compaction_interval_seconds: u64,
123
124 pub auto_compact: bool,
126
127 pub strategy: CompactionStrategy,
129
130 pub retention: RetentionConfig,
137
138 pub archive: Option<Arc<dyn ArchiveTarget>>,
146}
147
148#[derive(Debug, Clone)]
162pub struct RetentionConfig {
163 pub default_ttl: Option<Duration>,
165 pub per_tenant_ttl: HashMap<String, Option<Duration>>,
170}
171
172impl Default for RetentionConfig {
173 fn default() -> Self {
174 let mut per_tenant_ttl = HashMap::new();
175 per_tenant_ttl.insert("system".to_string(), Some(Duration::from_hours(30 * 24)));
176 Self {
177 default_ttl: None,
178 per_tenant_ttl,
179 }
180 }
181}
182
183impl RetentionConfig {
184 pub fn ttl_for(&self, tenant_id: &str) -> Option<Duration> {
191 match self.per_tenant_ttl.get(tenant_id) {
192 Some(v) => *v,
193 None => self.default_ttl,
194 }
195 }
196
197 pub fn set(&mut self, tenant_id: &str, ttl: Option<Duration>) {
200 self.per_tenant_ttl.insert(tenant_id.to_string(), ttl);
201 }
202}
203
204impl Default for CompactionConfig {
205 fn default() -> Self {
206 Self {
207 min_files_to_compact: 3,
208 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,
213 max_pass_seconds: 240,
214 compaction_interval_seconds: 3600, auto_compact: true,
216 strategy: CompactionStrategy::SizeBased,
217 retention: RetentionConfig::default(),
218 archive: None,
219 }
220 }
221}
222
223impl CompactionConfig {
224 pub fn from_env() -> Self {
235 let config = Self::from_env_vars(
236 std::env::var("ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS").ok(),
237 std::env::var("ALLSOURCE_RETENTION_SYSTEM_DAYS").ok(),
238 )
239 .with_input_bytes(std::env::var("ALLSOURCE_COMPACTION_INPUT_BYTES").ok());
240 config.with_cold_storage_url(std::env::var("ALLSOURCE_COLD_STORAGE_URL").ok())
241 }
242
243 pub fn with_input_bytes(mut self, bytes_var: Option<String>) -> Self {
246 if let Some(s) = bytes_var.filter(|s| !s.trim().is_empty()) {
247 match s.trim().parse::<u64>() {
248 Ok(v) if v > 0 => self.max_input_bytes_per_snapshot = v,
249 Ok(_) => tracing::warn!(
250 "ALLSOURCE_COMPACTION_INPUT_BYTES=0 is not a usable bound; keeping {}",
251 self.max_input_bytes_per_snapshot
252 ),
253 Err(e) => tracing::warn!(
254 "ALLSOURCE_COMPACTION_INPUT_BYTES={s:?} could not be parsed as u64: {e}; \
255 keeping {}",
256 self.max_input_bytes_per_snapshot
257 ),
258 }
259 }
260 self
261 }
262
263 #[allow(unused_variables, unused_mut)]
273 pub fn with_cold_storage_url(mut self, url: Option<String>) -> Self {
274 let Some(url) = url.filter(|u| !u.trim().is_empty()) else {
275 return self;
276 };
277
278 #[cfg(feature = "cold-tier-s3")]
279 {
280 match super::cold_tier_s3::S3Archive::from_url(url.trim()) {
281 Ok(archive) => {
282 tracing::info!(
283 target = %super::cold_tier::ArchiveTarget::description(&archive),
284 "cold-tier archive enabled"
285 );
286 self.archive = Some(std::sync::Arc::new(archive));
287 }
288 Err(e) => panic!("ALLSOURCE_COLD_STORAGE_URL={url:?} is set but unusable: {e}"),
289 }
290 }
291
292 #[cfg(not(feature = "cold-tier-s3"))]
293 panic!(
294 "ALLSOURCE_COLD_STORAGE_URL={url:?} is set but this binary was built without the \
295 `cold-tier-s3` feature, so nothing would be archived before retention deletes it. \
296 Rebuild with --features cold-tier-s3, or unset the variable."
297 );
298
299 #[cfg(feature = "cold-tier-s3")]
300 self
301 }
302
303 pub fn from_env_vars(
306 interval_var: Option<String>,
307 system_retention_days_var: Option<String>,
308 ) -> Self {
309 let mut config = Self::default();
310 if let Some(s) = interval_var.filter(|s| !s.is_empty()) {
311 match s.parse::<u64>() {
312 Ok(v) => config.compaction_interval_seconds = v,
313 Err(e) => {
314 tracing::warn!(
315 "ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS={s:?} could not be parsed as \
316 u64: {e}; defaulting to {}s",
317 config.compaction_interval_seconds
318 );
319 }
320 }
321 }
322 if let Some(s) = system_retention_days_var.filter(|s| !s.is_empty()) {
323 match s.parse::<u64>() {
324 Ok(0) => {
332 tracing::info!(
333 "ALLSOURCE_RETENTION_SYSTEM_DAYS=0: retention disabled for tenant=system"
334 );
335 config.retention.set("system", None);
336 }
337 Ok(days) => {
338 config
339 .retention
340 .set("system", Some(Duration::from_secs(days * 24 * 3600)));
341 }
342 Err(e) => {
343 tracing::warn!(
344 "ALLSOURCE_RETENTION_SYSTEM_DAYS={s:?} could not be parsed as u64: \
345 {e}; defaulting to 30 days for tenant=system"
346 );
347 }
348 }
349 }
350 config
351 }
352
353 pub fn from_env_var(interval_var: Option<String>) -> Self {
356 Self::from_env_vars(interval_var, None)
357 }
358}
359
360#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
361#[serde(rename_all = "lowercase")]
362pub enum CompactionStrategy {
363 SizeBased,
365 TimeBased,
367 FullCompaction,
369}
370
371#[derive(Debug, Clone, Default, Serialize)]
372pub struct CompactionStats {
373 pub total_compactions: u64,
374 pub total_files_compacted: u64,
375 pub total_bytes_before: u64,
376 pub total_bytes_after: u64,
377 pub total_events_compacted: u64,
378 pub last_compaction_duration_ms: u64,
379 pub space_saved_bytes: u64,
380}
381
382#[derive(Debug, Clone)]
384struct FileInfo {
385 path: PathBuf,
386 size: u64,
387 created: DateTime<Utc>,
388}
389
390impl CompactionManager {
391 pub fn new(storage_dir: impl Into<PathBuf>, config: CompactionConfig) -> Self {
393 let storage_dir = storage_dir.into();
394
395 tracing::info!(
396 "✅ Compaction manager initialized at: {}",
397 storage_dir.display()
398 );
399
400 let state = Self::load_sweep_state(&storage_dir);
401
402 Self {
403 storage_dir,
404 config,
405 stats: Arc::new(RwLock::new(CompactionStats::default())),
406 last_compaction: Arc::new(RwLock::new(state.as_ref().map(|s| s.last_compaction))),
407 sweep_cursor: Arc::new(RwLock::new(None)),
408 last_sweep_paused: Arc::new(RwLock::new(state.as_ref().is_some_and(|s| s.paused))),
409 }
410 }
411
412 fn sweep_state_path(storage_dir: &Path) -> PathBuf {
413 storage_dir.join(SWEEP_STATE_FILE)
414 }
415
416 fn load_sweep_state(storage_dir: &Path) -> Option<SweepState> {
417 let raw = fs::read_to_string(Self::sweep_state_path(storage_dir)).ok()?;
418 match serde_json::from_str::<SweepState>(&raw) {
419 Ok(state) => Some(state),
420 Err(e) => {
421 tracing::warn!("Unreadable compaction state, treating as never swept: {e}");
424 None
425 }
426 }
427 }
428
429 pub fn last_compaction(&self) -> Option<DateTime<Utc>> {
431 *self.last_compaction.read()
432 }
433
434 pub fn last_sweep_paused(&self) -> bool {
436 *self.last_sweep_paused.read()
437 }
438
439 pub fn delay_until_next_sweep(&self, settle: Duration) -> Duration {
446 if *self.last_sweep_paused.read() {
447 return settle;
448 }
449 let interval =
450 Duration::from_secs(self.config.compaction_interval_seconds.clamp(60, 86_400));
451 match self.last_compaction() {
452 None => settle,
453 Some(last) => {
454 let elapsed = (Utc::now() - last).to_std().unwrap_or(Duration::ZERO);
455 interval.saturating_sub(elapsed).max(settle)
456 }
457 }
458 }
459
460 fn record_sweep(&self, at: DateTime<Utc>, paused: bool) {
465 *self.last_compaction.write() = Some(at);
466 *self.last_sweep_paused.write() = paused;
467 let path = Self::sweep_state_path(&self.storage_dir);
468 let written = serde_json::to_vec(&SweepState {
469 last_compaction: at,
470 paused,
471 })
472 .map_err(|e| e.to_string())
473 .and_then(|bytes| fs::write(&path, bytes).map_err(|e| e.to_string()));
474 if let Err(e) = written {
475 tracing::warn!("Could not persist compaction state to {path:?}: {e}");
476 }
477 }
478
479 fn list_parquet_files(&self) -> Result<Vec<FileInfo>> {
481 let entries = fs::read_dir(&self.storage_dir).map_err(|e| {
482 AllSourceError::StorageError(format!("Failed to read storage directory: {e}"))
483 })?;
484
485 let mut files = Vec::new();
486
487 for entry in entries {
488 let entry = entry.map_err(|e| {
489 AllSourceError::StorageError(format!("Failed to read directory entry: {e}"))
490 })?;
491
492 let path = entry.path();
493 if let Some(ext) = path.extension()
494 && ext == "parquet"
495 {
496 let metadata = entry.metadata().map_err(|e| {
497 AllSourceError::StorageError(format!("Failed to read file metadata: {e}"))
498 })?;
499
500 let size = metadata.len();
501 let created = metadata
502 .created()
503 .ok()
504 .and_then(|t| {
505 t.duration_since(std::time::UNIX_EPOCH).ok().map(|d| {
506 DateTime::from_timestamp(d.as_secs() as i64, 0).unwrap_or_else(Utc::now)
507 })
508 })
509 .unwrap_or_else(Utc::now);
510
511 files.push(FileInfo {
512 path,
513 size,
514 created,
515 });
516 }
517 }
518
519 files.sort_by_key(|f| f.created);
521
522 Ok(files)
523 }
524
525 fn select_files_for_compaction(&self, files: &[FileInfo]) -> Vec<FileInfo> {
527 match self.config.strategy {
528 CompactionStrategy::SizeBased => self.select_small_files(files),
529 CompactionStrategy::TimeBased => self.select_old_files(files),
530 CompactionStrategy::FullCompaction => files.to_vec(),
531 }
532 }
533
534 fn select_small_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
536 let small_files: Vec<FileInfo> = files
537 .iter()
538 .filter(|f| f.size < self.config.small_file_threshold as u64)
539 .cloned()
540 .collect();
541
542 if small_files.len() >= self.config.min_files_to_compact {
544 small_files
545 } else {
546 Vec::new()
547 }
548 }
549
550 fn select_old_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
552 let now = Utc::now();
553 let age_threshold = chrono::Duration::hours(24); let old_files: Vec<FileInfo> = files
556 .iter()
557 .filter(|f| now - f.created > age_threshold)
558 .cloned()
559 .collect();
560
561 if old_files.len() >= self.config.min_files_to_compact {
562 old_files
563 } else {
564 Vec::new()
565 }
566 }
567
568 #[cfg_attr(feature = "hotpath", hotpath::measure)]
570 pub fn should_compact(&self) -> bool {
571 if !self.config.auto_compact {
572 return false;
573 }
574
575 let last = self.last_compaction.read();
576 match *last {
577 None => true, Some(last_time) => {
579 let elapsed = (Utc::now() - last_time).num_seconds();
580 elapsed >= self.config.compaction_interval_seconds as i64
581 }
582 }
583 }
584
585 #[cfg_attr(feature = "hotpath", hotpath::measure)]
603 pub fn compact(&self) -> Result<CompactionResult> {
604 self.compact_until(None)
605 }
606
607 pub fn sweep_cursor(&self) -> Option<String> {
612 self.sweep_cursor.read().clone()
613 }
614
615 pub fn compact_until(&self, deadline: Option<std::time::Instant>) -> Result<CompactionResult> {
618 let start_time = std::time::Instant::now();
619 tracing::info!("🔄 Starting per-tenant compaction sweep...");
620
621 let tenants = self.discover_tenants()?;
622 if tenants.is_empty() {
623 tracing::debug!("No tenants found under {}", self.storage_dir.display());
624 self.record_sweep(Utc::now(), false);
628 return Ok(CompactionResult::default());
629 }
630
631 let tenants = self.rotate_to_cursor(tenants);
632 let deadline = deadline.unwrap_or_else(|| {
633 start_time + Duration::from_secs(self.config.max_pass_seconds.max(1))
634 });
635 let mut aggregate = CompactionResult::default();
636 let mut unvisited = 0usize;
637 let mut resume_at: Option<&String> = None;
641 for tenant in &tenants {
642 if std::time::Instant::now() >= deadline {
643 unvisited += 1;
644 resume_at = resume_at.or(Some(tenant));
645 continue;
646 }
647 match self.sweep_tenant(tenant, Some(deadline)) {
648 Ok((r, complete)) => {
649 aggregate.files_compacted += r.files_compacted;
650 aggregate.bytes_before += r.bytes_before;
651 aggregate.bytes_after += r.bytes_after;
652 aggregate.events_compacted += r.events_compacted;
653 if !complete {
654 resume_at = resume_at.or(Some(tenant));
655 }
656 }
657 Err(e) => {
658 tracing::error!(
659 tenant_id = %tenant,
660 "compact_tenant failed: {e}"
661 );
662 }
663 }
664 }
665 *self.sweep_cursor.write() = resume_at.or(tenants.first()).cloned();
668 if unvisited > 0 {
669 tracing::info!(
670 unvisited_tenants = unvisited,
671 resume_at = ?resume_at,
672 budget_secs = self.config.max_pass_seconds,
673 "compaction sweep hit its time budget; resuming next tick"
674 );
675 }
676 aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
677
678 if aggregate.files_compacted > 0 {
679 let mut stats = self.stats.write();
680 stats.total_compactions += 1;
681 stats.total_files_compacted += aggregate.files_compacted as u64;
682 stats.total_bytes_before += aggregate.bytes_before;
683 stats.total_bytes_after += aggregate.bytes_after;
684 stats.total_events_compacted += aggregate.events_compacted as u64;
685 stats.last_compaction_duration_ms = aggregate.duration_ms;
686 stats.space_saved_bytes += aggregate.bytes_before.saturating_sub(aggregate.bytes_after);
687 }
688 self.record_sweep(Utc::now(), unvisited > 0);
689
690 tracing::info!(
691 "✅ Compaction sweep complete: {} files → bounded snapshots, \
692 {:.2} MB → {:.2} MB, {} events, {} tenants in {}ms",
693 aggregate.files_compacted,
694 aggregate.bytes_before as f64 / (1024.0 * 1024.0),
695 aggregate.bytes_after as f64 / (1024.0 * 1024.0),
696 aggregate.events_compacted,
697 tenants.len(),
698 aggregate.duration_ms
699 );
700
701 Ok(aggregate)
702 }
703
704 pub fn compact_tenant(&self, tenant_id: &str) -> Result<CompactionResult> {
725 self.compact_tenant_until(tenant_id, None)
726 }
727
728 pub fn compact_tenant_until(
733 &self,
734 tenant_id: &str,
735 deadline: Option<std::time::Instant>,
736 ) -> Result<CompactionResult> {
737 self.sweep_tenant(tenant_id, deadline)
738 .map(|(result, _complete)| result)
739 }
740
741 fn sweep_tenant(
746 &self,
747 tenant_id: &str,
748 deadline: Option<std::time::Instant>,
749 ) -> Result<(CompactionResult, bool)> {
750 let start_time = std::time::Instant::now();
751 let deadline =
752 Some(deadline.unwrap_or_else(|| start_time + std::time::Duration::from_secs(240)));
753 if deadline.is_some_and(|end| start_time >= end) {
754 return Ok((CompactionResult::default(), false));
755 }
756 let Some(_mutation) = archive_mutation_guard(deadline) else {
757 return Ok((CompactionResult::default(), false));
758 };
759 let storage = ParquetStorage::open_existing(&self.storage_dir)?;
760 let all_files = storage.list_parquet_files_for_tenant(tenant_id)?;
761 let mut aggregate = CompactionResult::default();
762 let mut first_error = None;
763 let mut failed_repairs = std::collections::HashSet::new();
764 for path in &all_files {
765 let bytes = fs::metadata(path)
766 .map_err(|error| AllSourceError::StorageError(error.to_string()))?
767 .len();
768 if bytes <= ArchiveReadLimits::default().max_file_bytes {
769 continue;
770 }
771 if deadline.is_some_and(|end| std::time::Instant::now() >= end) {
772 if let Some(error) = first_error {
773 return Err(error);
774 }
775 aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
776 return Ok((aggregate, false));
777 }
778 let repaired = repack_archive_file_in_sweep(path, deadline).and_then(|receipt_path| {
779 read_repack_receipt(&receipt_path).map(|receipt| (receipt_path, receipt))
780 });
781 let (receipt_path, receipt) = match repaired {
782 Ok(repaired) => repaired,
783 Err(error) => {
784 tracing::error!(tenant_id, file = %path.display(), "oversized archive repair failed: {error}");
785 failed_repairs.insert(path.clone());
786 if first_error.is_none() {
787 first_error = Some(error);
788 }
789 continue;
790 }
791 };
792 aggregate.files_compacted += 1;
793 aggregate.bytes_before += receipt.original_bytes;
794 aggregate.bytes_after += receipt.output_bytes;
795 aggregate.events_compacted += usize::try_from(receipt.rows)
796 .map_err(|_| AllSourceError::StorageError("Archive row count overflow".into()))?;
797 tracing::info!(tenant_id, receipt = %receipt_path.display(), "oversized archive repacked; original retained");
798 }
799 let all_files = storage.list_parquet_files_for_tenant(tenant_id)?;
800 let mut age_indexes = std::collections::HashMap::new();
801 let mut repair_ages = std::collections::HashMap::new();
802 for path in &all_files {
803 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
804 continue;
805 };
806 if !name.starts_with("events.repacked.") {
807 continue;
808 }
809 let Some(directory) = path.parent() else {
810 continue;
811 };
812 let index = age_indexes
813 .entry(directory.to_path_buf())
814 .or_insert_with(|| {
815 let (index, error) = repair_age_index(directory, deadline);
816 if first_error.is_none() {
817 first_error = error;
818 }
819 index
820 });
821 if let Some(created) = index.get(name) {
822 repair_ages.insert(path.clone(), *created);
823 } else {
824 failed_repairs.insert(path.clone());
825 if first_error.is_none() {
826 first_error = Some(AllSourceError::StorageError(
827 "Repaired archive receipt missing".into(),
828 ));
829 }
830 }
831 }
832 let threshold = self.config.small_file_threshold as u64;
833 let raw_files: Vec<FileInfo> = all_files
834 .into_iter()
835 .filter_map(|p| {
836 if failed_repairs.contains(&p) {
837 return None;
838 }
839 let metadata = fs::metadata(&p).ok()?;
840 let size = metadata.len();
841 let is_snapshot = p
842 .file_name()
843 .and_then(|n| n.to_str())
844 .is_some_and(|n| n.starts_with(SNAPSHOT_PREFIX));
845 if is_snapshot && size >= threshold {
849 return None;
850 }
851 let created = repair_ages
852 .get(&p)
853 .copied()
854 .flatten()
855 .or_else(|| metadata.created().ok())
856 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
857 .and_then(|d| DateTime::from_timestamp(d.as_secs() as i64, 0))
858 .unwrap_or_else(Utc::now);
859 Some(FileInfo {
860 path: p,
861 size,
862 created,
863 })
864 })
865 .collect();
866
867 let mut candidates = self.select_files_for_compaction(&raw_files);
868 if candidates.is_empty() {
869 if let Some(error) = first_error {
870 return Err(error);
871 }
872 tracing::debug!(
873 tenant_id = tenant_id,
874 strategy = ?self.config.strategy,
875 "no files meet compaction criteria"
876 );
877 aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
878 return Ok((aggregate, true));
879 }
880 candidates.sort_by_key(|f| f.created);
883
884 let total_bytes: u64 = candidates.iter().map(|f| f.size).sum();
885 let groups = self.split_into_bounded_groups(candidates);
886 tracing::info!(
887 tenant_id = tenant_id,
888 groups = groups.len(),
889 mib = total_bytes as f64 / (1024.0 * 1024.0),
890 "compacting tenant"
891 );
892
893 let total_groups = groups.len();
894 let mut done = 0usize;
895 let mut complete = true;
901 for group in groups {
902 if deadline.is_some_and(|d| std::time::Instant::now() >= d) {
903 tracing::info!(
904 tenant_id = tenant_id,
905 groups_done = done,
906 groups_total = total_groups,
907 "tenant compaction paused on the sweep budget"
908 );
909 complete = false;
910 break;
911 }
912 match self.compact_group(tenant_id, &storage, &group) {
913 Ok(result) => {
914 aggregate.files_compacted += result.files_compacted;
915 aggregate.bytes_before += result.bytes_before;
916 aggregate.bytes_after += result.bytes_after;
917 aggregate.events_compacted += result.events_compacted;
918 done += 1;
919 }
920 Err(error) => {
921 tracing::error!(
922 tenant_id = tenant_id,
923 files = group.len(),
924 "compaction group failed: {error}"
925 );
926 if first_error.is_none() {
927 first_error = Some(error);
928 }
929 }
930 }
931 }
932 if let Some(error) = first_error {
933 return Err(error);
934 }
935 aggregate.duration_ms = start_time.elapsed().as_millis() as u64;
936 Ok((aggregate, complete))
937 }
938
939 fn split_into_bounded_groups(&self, candidates: Vec<FileInfo>) -> Vec<Vec<FileInfo>> {
943 let max_bytes = self.config.max_input_bytes_per_snapshot.max(1);
944 let max_files = self.config.max_input_files_per_snapshot.max(1);
945 let mut groups: Vec<Vec<FileInfo>> = Vec::new();
946 let mut current: Vec<FileInfo> = Vec::new();
947 let mut current_bytes = 0u64;
948 for file in candidates {
949 let would_exceed = !current.is_empty()
950 && (current_bytes + file.size > max_bytes || current.len() >= max_files);
951 if would_exceed {
952 groups.push(std::mem::take(&mut current));
953 current_bytes = 0;
954 }
955 current_bytes += file.size;
956 current.push(file);
957 }
958 if !current.is_empty() {
959 groups.push(current);
960 }
961 groups
962 }
963
964 fn compact_group(
967 &self,
968 tenant_id: &str,
969 storage: &ParquetStorage,
970 candidates: &[FileInfo],
971 ) -> Result<CompactionResult> {
972 let start_time = std::time::Instant::now();
973 let bytes_before: u64 = candidates.iter().map(|f| f.size).sum();
974 let mut directories = candidates
975 .iter()
976 .filter_map(|file| file.path.parent())
977 .collect::<Vec<_>>();
978 directories.sort();
979 directories.dedup();
980 let _directories = directories
981 .into_iter()
982 .map(archive_directory_guard)
983 .collect::<Result<Vec<_>>>()?;
984
985 let mut events = Vec::new();
990 for fi in candidates {
991 let event_tenant = match fi.path.strip_prefix(&self.storage_dir).ok() {
994 Some(rel) => rel
995 .components()
996 .next()
997 .and_then(|c| match c {
998 std::path::Component::Normal(t) => Some(t.to_string_lossy().into_owned()),
999 _ => None,
1000 })
1001 .unwrap_or_else(|| "default".to_string()),
1002 None => "default".to_string(),
1003 };
1004 let mut loaded = storage
1008 .load_events_from_file_path(&fi.path, &event_tenant)
1009 .map_err(|error| {
1010 AllSourceError::StorageError(format!(
1011 "Compaction refused unreadable candidate {}: {error}",
1012 fi.path.display()
1013 ))
1014 })?;
1015 events.append(&mut loaded);
1016 }
1017
1018 if events.is_empty() {
1019 tracing::warn!(
1020 tenant_id = tenant_id,
1021 "candidate files had no readable events; skipping snapshot"
1022 );
1023 return Ok(CompactionResult::default());
1024 }
1025
1026 let dropped_by_retention = if let Some(ttl) = self.config.retention.ttl_for(tenant_id) {
1042 let cutoff = Utc::now()
1043 - chrono::Duration::from_std(ttl).unwrap_or_else(|_| chrono::Duration::zero());
1044 let before = events.len();
1045
1046 let (drained, kept): (Vec<_>, Vec<_>) = std::mem::take(&mut events)
1051 .into_iter()
1052 .partition(|e| e.timestamp < cutoff);
1053 events = kept;
1054 let dropped = before - events.len();
1055
1056 if dropped > 0 {
1057 tracing::info!(
1058 retention_tenant = tenant_id,
1059 dropped = dropped,
1060 kept = events.len(),
1061 cutoff = %cutoff.to_rfc3339(),
1062 ttl_secs = ttl.as_secs(),
1063 "retention: dropped events older than TTL"
1064 );
1065
1066 if let Some(archive) = self.config.archive.as_ref() {
1067 let from = drained
1068 .iter()
1069 .map(|e| e.timestamp)
1070 .min()
1071 .expect("dropped > 0 guarantees non-empty drained");
1072 let to = drained
1073 .iter()
1074 .map(|e| e.timestamp)
1075 .max()
1076 .expect("dropped > 0 guarantees non-empty drained");
1077 archive.archive(tenant_id, from, to, &drained)?;
1078 tracing::info!(
1079 retention_tenant = tenant_id,
1080 archived_to = %archive.description(),
1081 archived = drained.len(),
1082 "retention: dropped events archived to cold tier"
1083 );
1084 }
1085 }
1086 dropped
1087 } else {
1088 0
1089 };
1090
1091 if events.is_empty() {
1099 tracing::info!(
1100 tenant_id = tenant_id,
1101 files_dropped = candidates.len(),
1102 events_dropped = dropped_by_retention,
1103 "retention: every event aged out — deleting originals without snapshot"
1104 );
1105 for fi in candidates {
1106 if let Err(e) = fs::remove_file(&fi.path) {
1107 tracing::error!(
1108 file = %fi.path.display(),
1109 "failed to remove fully-aged raw file: {e}"
1110 );
1111 }
1112 }
1113 return Ok(CompactionResult {
1114 files_compacted: candidates.len(),
1115 bytes_before,
1116 bytes_after: 0,
1117 events_compacted: 0,
1118 duration_ms: start_time.elapsed().as_millis() as u64,
1119 });
1120 }
1121
1122 events.sort_by_key(|e| e.timestamp);
1123 let from = events.first().expect("non-empty checked above").timestamp;
1124 let to = events.last().expect("non-empty checked above").timestamp;
1125
1126 let unique = Utc::now().timestamp_nanos_opt().unwrap_or_default();
1132 let file_stem = format!(
1133 "snapshot.{tenant_id}.{}-{}.{unique}",
1134 format_iso_basic(from),
1135 format_iso_basic(to)
1136 );
1137 let snapshot_paths = storage.write_atomic_parquet_parts(tenant_id, &file_stem, &events)?;
1138 let bytes_after = snapshot_paths.iter().try_fold(0u64, |sum, path| {
1139 let bytes = fs::metadata(path)
1140 .map_err(|error| {
1141 AllSourceError::StorageError(format!("Cannot inspect archive output: {error}"))
1142 })?
1143 .len();
1144 sum.checked_add(bytes).ok_or_else(|| {
1145 AllSourceError::StorageError("Archive output byte count overflow".into())
1146 })
1147 })?;
1148
1149 for fi in candidates {
1153 if snapshot_paths.contains(&fi.path) {
1154 continue;
1155 }
1156 if let Err(e) = fs::remove_file(&fi.path) {
1157 tracing::error!(
1158 file = %fi.path.display(),
1159 "failed to remove pre-snapshot raw file: {e}"
1160 );
1161 }
1162 }
1163
1164 let duration_ms = start_time.elapsed().as_millis() as u64;
1165 tracing::info!(
1166 tenant_id = tenant_id,
1167 files_compacted = candidates.len(),
1168 events = events.len(),
1169 dropped_by_retention = dropped_by_retention,
1170 mib_before = bytes_before as f64 / (1024.0 * 1024.0),
1171 mib_after = bytes_after as f64 / (1024.0 * 1024.0),
1172 duration_ms = duration_ms,
1173 "tenant compaction group complete"
1174 );
1175
1176 Ok(CompactionResult {
1177 files_compacted: candidates.len(),
1178 bytes_before,
1179 bytes_after,
1180 events_compacted: events.len(),
1181 duration_ms,
1182 })
1183 }
1184
1185 fn rotate_to_cursor(&self, tenants: Vec<String>) -> Vec<String> {
1192 let cursor = self.sweep_cursor.read().clone();
1193 let Some(cursor) = cursor else {
1194 return tenants;
1195 };
1196 let Some(position) = tenants.iter().position(|tenant| *tenant == cursor) else {
1197 return tenants;
1198 };
1199 let mut rotated = tenants;
1200 rotated.rotate_left(position);
1201 rotated
1202 }
1203
1204 fn discover_tenants(&self) -> Result<Vec<String>> {
1209 let Ok(entries) = fs::read_dir(&self.storage_dir) else {
1210 return Ok(Vec::new());
1211 };
1212 let mut tenants: Vec<String> = entries
1213 .filter_map(std::result::Result::ok)
1214 .filter_map(|entry| {
1215 let ft = entry.file_type().ok()?;
1216 if !ft.is_dir() {
1217 return None;
1218 }
1219 let name = entry.file_name().to_string_lossy().into_owned();
1220 if name.starts_with('.') || name == "__system" {
1223 return None;
1224 }
1225 Some(name)
1226 })
1227 .collect();
1228 tenants.sort();
1229 Ok(tenants)
1230 }
1231
1232 pub fn stats(&self) -> CompactionStats {
1234 (*self.stats.read()).clone()
1235 }
1236
1237 pub fn config(&self) -> &CompactionConfig {
1239 &self.config
1240 }
1241
1242 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1244 pub fn compact_now(&self) -> Result<CompactionResult> {
1245 tracing::info!("Manual compaction triggered");
1246 self.compact()
1247 }
1248}
1249
1250fn repair_age_index(
1251 directory: &std::path::Path,
1252 deadline: Option<std::time::Instant>,
1253) -> (
1254 std::collections::HashMap<String, Option<std::time::SystemTime>>,
1255 Option<AllSourceError>,
1256) {
1257 let mut index = std::collections::HashMap::new();
1258 let mut first_error = None;
1259 let entries = match fs::read_dir(directory) {
1260 Ok(entries) => entries,
1261 Err(error) => return (index, Some(AllSourceError::StorageError(error.to_string()))),
1262 };
1263 for entry in entries {
1264 if deadline.is_some_and(|end| std::time::Instant::now() >= end) {
1265 return (
1266 index,
1267 Some(AllSourceError::StorageError(
1268 "Archive age lookup deadline exceeded".into(),
1269 )),
1270 );
1271 }
1272 let receipt_path = match entry {
1273 Ok(entry) => entry.path(),
1274 Err(error) => {
1275 if first_error.is_none() {
1276 first_error = Some(AllSourceError::StorageError(error.to_string()));
1277 }
1278 continue;
1279 }
1280 };
1281 if receipt_path.extension() != Some(std::ffi::OsStr::new("json"))
1282 || !receipt_path
1283 .file_name()
1284 .and_then(|name| name.to_str())
1285 .is_some_and(|name| name.contains(".parquet.repair."))
1286 {
1287 continue;
1288 }
1289 match read_repack_receipt(&receipt_path) {
1290 Ok(receipt) => {
1291 for output in receipt.outputs {
1292 index.insert(output, receipt.original_created_at);
1293 }
1294 }
1295 Err(error) => {
1296 if first_error.is_none() {
1297 first_error = Some(error);
1298 }
1299 }
1300 }
1301 }
1302 (index, first_error)
1303}
1304
1305#[derive(Debug, Clone, Default, Serialize)]
1307pub struct CompactionResult {
1308 pub files_compacted: usize,
1309 pub bytes_before: u64,
1310 pub bytes_after: u64,
1311 pub events_compacted: usize,
1312 pub duration_ms: u64,
1313}
1314
1315pub(super) fn format_iso_basic(t: DateTime<Utc>) -> String {
1321 t.format("%Y-%m-%dT%H%M%SZ").to_string()
1322}
1323
1324pub struct CompactionTask {
1326 manager: Arc<CompactionManager>,
1327 interval: Duration,
1328}
1329
1330impl CompactionTask {
1331 pub fn new(manager: Arc<CompactionManager>, interval_seconds: u64) -> Self {
1333 Self {
1334 manager,
1335 interval: Duration::from_secs(interval_seconds),
1336 }
1337 }
1338
1339 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1341 pub async fn run(self) {
1342 let mut interval = tokio::time::interval(self.interval);
1343
1344 loop {
1345 interval.tick().await;
1346
1347 if self.manager.should_compact() {
1348 tracing::debug!("Auto-compaction check triggered");
1349
1350 match self.manager.compact() {
1351 Ok(result) => {
1352 if result.files_compacted > 0 {
1353 tracing::info!(
1354 "Auto-compaction succeeded: {} files, {:.2} MB saved",
1355 result.files_compacted,
1356 result.bytes_before.saturating_sub(result.bytes_after) as f64
1357 / (1024.0 * 1024.0)
1358 );
1359 }
1360 }
1361 Err(e) => {
1362 tracing::error!("Auto-compaction failed: {}", e);
1363 }
1364 }
1365 }
1366 }
1367 }
1368}
1369
1370#[cfg(test)]
1371mod tests {
1372 use super::*;
1373 use tempfile::TempDir;
1374
1375 #[test]
1376 fn test_compaction_manager_creation() {
1377 let temp_dir = TempDir::new().unwrap();
1378 let config = CompactionConfig::default();
1379 let manager = CompactionManager::new(temp_dir.path(), config);
1380
1381 assert_eq!(manager.stats().total_compactions, 0);
1382 }
1383
1384 #[test]
1385 fn a_completed_sweep_is_remembered_across_restarts() {
1386 let temp_dir = TempDir::new().unwrap();
1387 let config = CompactionConfig {
1388 auto_compact: true,
1389 compaction_interval_seconds: 3600,
1390 ..Default::default()
1391 };
1392
1393 let manager = CompactionManager::new(temp_dir.path(), config.clone());
1394 assert!(manager.last_compaction().is_none());
1395 assert!(manager.should_compact());
1396 manager.compact().unwrap();
1397 let recorded = manager.last_compaction().expect("sweep was recorded");
1398
1399 let restarted = CompactionManager::new(temp_dir.path(), config);
1400 assert_eq!(restarted.last_compaction(), Some(recorded));
1401 assert!(
1402 !restarted.should_compact(),
1403 "a restart must not re-arm a sweep that just ran"
1404 );
1405 }
1406
1407 #[test]
1408 fn a_restart_does_not_push_the_next_sweep_a_full_interval_away() {
1409 let temp_dir = TempDir::new().unwrap();
1410 let settle = Duration::from_secs(120);
1411 let config = CompactionConfig {
1412 auto_compact: true,
1413 compaction_interval_seconds: 3600,
1414 ..Default::default()
1415 };
1416
1417 let never_swept = CompactionManager::new(temp_dir.path(), config.clone());
1418 assert_eq!(never_swept.delay_until_next_sweep(settle), settle);
1419
1420 never_swept.compact().unwrap();
1421 let after_sweep = never_swept.delay_until_next_sweep(settle);
1422 assert!(
1423 after_sweep > settle && after_sweep <= Duration::from_secs(3600),
1424 "{after_sweep:?}"
1425 );
1426
1427 *never_swept.last_compaction.write() = Some(Utc::now() - chrono::Duration::seconds(7200));
1428 assert_eq!(never_swept.delay_until_next_sweep(settle), settle);
1429 }
1430
1431 #[test]
1432 fn a_paused_sweep_resumes_at_the_settle_delay_even_after_a_restart() {
1433 let temp_dir = TempDir::new().unwrap();
1434 let settle = Duration::from_secs(120);
1435 let config = CompactionConfig {
1436 auto_compact: true,
1437 compaction_interval_seconds: 3600,
1438 ..Default::default()
1439 };
1440
1441 let manager = CompactionManager::new(temp_dir.path(), config.clone());
1442 manager.record_sweep(Utc::now(), true);
1443 assert_eq!(manager.delay_until_next_sweep(settle), settle);
1444
1445 let restarted = CompactionManager::new(temp_dir.path(), config.clone());
1446 assert!(restarted.last_sweep_paused());
1447 assert_eq!(restarted.delay_until_next_sweep(settle), settle);
1448
1449 restarted.record_sweep(Utc::now(), false);
1450 let finished = CompactionManager::new(temp_dir.path(), config);
1451 assert!(!finished.last_sweep_paused());
1452 assert!(finished.delay_until_next_sweep(settle) > settle);
1453 }
1454
1455 #[test]
1456 fn unreadable_sweep_state_schedules_a_sweep_rather_than_skipping_one() {
1457 let temp_dir = TempDir::new().unwrap();
1458 fs::write(temp_dir.path().join(SWEEP_STATE_FILE), "not json").unwrap();
1459
1460 let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
1461
1462 assert!(manager.last_compaction().is_none());
1463 assert_eq!(
1464 manager.delay_until_next_sweep(Duration::from_secs(120)),
1465 Duration::from_secs(120)
1466 );
1467 }
1468
1469 #[test]
1470 fn test_should_compact() {
1471 let temp_dir = TempDir::new().unwrap();
1472 let config = CompactionConfig {
1473 auto_compact: true,
1474 compaction_interval_seconds: 1,
1475 ..Default::default()
1476 };
1477 let manager = CompactionManager::new(temp_dir.path(), config);
1478
1479 assert!(manager.should_compact());
1481 }
1482
1483 #[test]
1484 fn test_file_selection_size_based() {
1485 let temp_dir = TempDir::new().unwrap();
1486 let config = CompactionConfig {
1487 small_file_threshold: 1024 * 1024, min_files_to_compact: 2,
1489 strategy: CompactionStrategy::SizeBased,
1490 ..Default::default()
1491 };
1492 let manager = CompactionManager::new(temp_dir.path(), config);
1493
1494 let files = vec![
1495 FileInfo {
1496 path: PathBuf::from("small1.parquet"),
1497 size: 500_000, created: Utc::now(),
1499 },
1500 FileInfo {
1501 path: PathBuf::from("small2.parquet"),
1502 size: 600_000, created: Utc::now(),
1504 },
1505 FileInfo {
1506 path: PathBuf::from("large.parquet"),
1507 size: 10_000_000, created: Utc::now(),
1509 },
1510 ];
1511
1512 let selected = manager.select_files_for_compaction(&files);
1513 assert_eq!(selected.len(), 2); }
1515
1516 #[test]
1517 fn test_default_compaction_config() {
1518 let config = CompactionConfig::default();
1519 assert_eq!(config.min_files_to_compact, 3);
1520 assert_eq!(config.target_file_size, 128 * 1024 * 1024);
1521 assert_eq!(config.max_file_size, 256 * 1024 * 1024);
1522 assert_eq!(config.small_file_threshold, 10 * 1024 * 1024);
1523 assert_eq!(config.compaction_interval_seconds, 3600);
1524 assert!(config.auto_compact);
1525 assert_eq!(config.strategy, CompactionStrategy::SizeBased);
1526 }
1527
1528 #[test]
1529 fn test_should_compact_disabled() {
1530 let temp_dir = TempDir::new().unwrap();
1531 let config = CompactionConfig {
1532 auto_compact: false,
1533 ..Default::default()
1534 };
1535 let manager = CompactionManager::new(temp_dir.path(), config);
1536
1537 assert!(!manager.should_compact());
1538 }
1539
1540 #[test]
1541 fn test_compact_empty_directory() {
1542 let temp_dir = TempDir::new().unwrap();
1543 let config = CompactionConfig::default();
1544 let manager = CompactionManager::new(temp_dir.path(), config);
1545
1546 let result = manager.compact().unwrap();
1547 assert_eq!(result.files_compacted, 0);
1548 assert_eq!(result.bytes_before, 0);
1549 assert_eq!(result.bytes_after, 0);
1550 assert_eq!(result.events_compacted, 0);
1551 }
1552
1553 #[test]
1554 fn test_compact_now() {
1555 let temp_dir = TempDir::new().unwrap();
1556 let config = CompactionConfig::default();
1557 let manager = CompactionManager::new(temp_dir.path(), config);
1558
1559 let result = manager.compact_now().unwrap();
1560 assert_eq!(result.files_compacted, 0);
1561 }
1562
1563 #[test]
1564 fn test_get_config() {
1565 let temp_dir = TempDir::new().unwrap();
1566 let config = CompactionConfig {
1567 min_files_to_compact: 5,
1568 ..Default::default()
1569 };
1570 let manager = CompactionManager::new(temp_dir.path(), config);
1571
1572 assert_eq!(manager.config().min_files_to_compact, 5);
1573 }
1574
1575 #[test]
1576 fn test_get_stats() {
1577 let temp_dir = TempDir::new().unwrap();
1578 let config = CompactionConfig::default();
1579 let manager = CompactionManager::new(temp_dir.path(), config);
1580
1581 let stats = manager.stats();
1582 assert_eq!(stats.total_compactions, 0);
1583 assert_eq!(stats.total_files_compacted, 0);
1584 assert_eq!(stats.total_bytes_before, 0);
1585 assert_eq!(stats.total_bytes_after, 0);
1586 assert_eq!(stats.total_events_compacted, 0);
1587 assert_eq!(stats.last_compaction_duration_ms, 0);
1588 assert_eq!(stats.space_saved_bytes, 0);
1589 }
1590
1591 #[test]
1592 fn test_file_selection_not_enough_small_files() {
1593 let temp_dir = TempDir::new().unwrap();
1594 let config = CompactionConfig {
1595 small_file_threshold: 1024 * 1024,
1596 min_files_to_compact: 3, strategy: CompactionStrategy::SizeBased,
1598 ..Default::default()
1599 };
1600 let manager = CompactionManager::new(temp_dir.path(), config);
1601
1602 let files = vec![
1603 FileInfo {
1604 path: PathBuf::from("small1.parquet"),
1605 size: 500_000,
1606 created: Utc::now(),
1607 },
1608 FileInfo {
1609 path: PathBuf::from("small2.parquet"),
1610 size: 600_000,
1611 created: Utc::now(),
1612 },
1613 ];
1614
1615 let selected = manager.select_files_for_compaction(&files);
1616 assert_eq!(selected.len(), 0); }
1618
1619 #[test]
1620 fn test_file_selection_time_based() {
1621 let temp_dir = TempDir::new().unwrap();
1622 let config = CompactionConfig {
1623 min_files_to_compact: 2,
1624 strategy: CompactionStrategy::TimeBased,
1625 ..Default::default()
1626 };
1627 let manager = CompactionManager::new(temp_dir.path(), config);
1628
1629 let old_time = Utc::now() - chrono::Duration::hours(48);
1630 let files = vec![
1631 FileInfo {
1632 path: PathBuf::from("old1.parquet"),
1633 size: 1_000_000,
1634 created: old_time,
1635 },
1636 FileInfo {
1637 path: PathBuf::from("old2.parquet"),
1638 size: 2_000_000,
1639 created: old_time,
1640 },
1641 FileInfo {
1642 path: PathBuf::from("new.parquet"),
1643 size: 500_000,
1644 created: Utc::now(),
1645 },
1646 ];
1647
1648 let selected = manager.select_files_for_compaction(&files);
1649 assert_eq!(selected.len(), 2); }
1651
1652 #[test]
1653 fn test_file_selection_time_based_not_enough() {
1654 let temp_dir = TempDir::new().unwrap();
1655 let config = CompactionConfig {
1656 min_files_to_compact: 3,
1657 strategy: CompactionStrategy::TimeBased,
1658 ..Default::default()
1659 };
1660 let manager = CompactionManager::new(temp_dir.path(), config);
1661
1662 let old_time = Utc::now() - chrono::Duration::hours(48);
1663 let files = vec![
1664 FileInfo {
1665 path: PathBuf::from("old1.parquet"),
1666 size: 1_000_000,
1667 created: old_time,
1668 },
1669 FileInfo {
1670 path: PathBuf::from("new.parquet"),
1671 size: 500_000,
1672 created: Utc::now(),
1673 },
1674 ];
1675
1676 let selected = manager.select_files_for_compaction(&files);
1677 assert_eq!(selected.len(), 0); }
1679
1680 #[test]
1681 fn test_file_selection_full_compaction() {
1682 let temp_dir = TempDir::new().unwrap();
1683 let config = CompactionConfig {
1684 strategy: CompactionStrategy::FullCompaction,
1685 ..Default::default()
1686 };
1687 let manager = CompactionManager::new(temp_dir.path(), config);
1688
1689 let files = vec![
1690 FileInfo {
1691 path: PathBuf::from("file1.parquet"),
1692 size: 1_000_000,
1693 created: Utc::now(),
1694 },
1695 FileInfo {
1696 path: PathBuf::from("file2.parquet"),
1697 size: 2_000_000,
1698 created: Utc::now(),
1699 },
1700 ];
1701
1702 let selected = manager.select_files_for_compaction(&files);
1703 assert_eq!(selected.len(), 2); }
1705
1706 #[test]
1707 fn test_compaction_strategy_serde() {
1708 let strategies = vec![
1709 CompactionStrategy::SizeBased,
1710 CompactionStrategy::TimeBased,
1711 CompactionStrategy::FullCompaction,
1712 ];
1713
1714 for strategy in strategies {
1715 let json = serde_json::to_string(&strategy).unwrap();
1716 let parsed: CompactionStrategy = serde_json::from_str(&json).unwrap();
1717 assert_eq!(parsed, strategy);
1718 }
1719 }
1720
1721 #[test]
1722 fn test_compaction_stats_default() {
1723 let stats = CompactionStats::default();
1724 assert_eq!(stats.total_compactions, 0);
1725 assert_eq!(stats.total_files_compacted, 0);
1726 }
1727
1728 #[test]
1729 fn test_compaction_stats_serde() {
1730 let stats = CompactionStats {
1731 total_compactions: 5,
1732 total_files_compacted: 20,
1733 total_bytes_before: 1000000,
1734 total_bytes_after: 500000,
1735 total_events_compacted: 10000,
1736 last_compaction_duration_ms: 500,
1737 space_saved_bytes: 500000,
1738 };
1739
1740 let json = serde_json::to_string(&stats).unwrap();
1741 assert!(json.contains("\"total_compactions\":5"));
1742 assert!(json.contains("\"space_saved_bytes\":500000"));
1743 }
1744
1745 #[test]
1746 fn test_compaction_result_serde() {
1747 let result = CompactionResult {
1748 files_compacted: 3,
1749 bytes_before: 1000000,
1750 bytes_after: 500000,
1751 events_compacted: 5000,
1752 duration_ms: 250,
1753 };
1754
1755 let json = serde_json::to_string(&result).unwrap();
1756 assert!(json.contains("\"files_compacted\":3"));
1757 assert!(json.contains("\"bytes_before\":1000000"));
1758 }
1759
1760 #[test]
1761 fn test_compaction_task_creation() {
1762 let temp_dir = TempDir::new().unwrap();
1763 let config = CompactionConfig::default();
1764 let manager = Arc::new(CompactionManager::new(temp_dir.path(), config));
1765
1766 let _task = CompactionTask::new(manager.clone(), 60);
1767 }
1769
1770 #[test]
1771 fn test_list_parquet_files_empty() {
1772 let temp_dir = TempDir::new().unwrap();
1773 let config = CompactionConfig::default();
1774 let manager = CompactionManager::new(temp_dir.path(), config);
1775
1776 let files = manager.list_parquet_files().unwrap();
1777 assert!(files.is_empty());
1778 }
1779
1780 #[test]
1781 fn test_list_parquet_files_with_non_parquet() {
1782 let temp_dir = TempDir::new().unwrap();
1783 let config = CompactionConfig::default();
1784 let manager = CompactionManager::new(temp_dir.path(), config);
1785
1786 std::fs::write(temp_dir.path().join("test.txt"), "test").unwrap();
1788 std::fs::write(temp_dir.path().join("data.json"), "{}").unwrap();
1789
1790 let files = manager.list_parquet_files().unwrap();
1791 assert!(files.is_empty()); }
1793
1794 fn ingest_and_flush_per_call(storage_dir: &std::path::Path, tenant: &str, count: usize) {
1799 for i in 0..count {
1803 let storage = ParquetStorage::with_config(
1804 storage_dir,
1805 crate::infrastructure::persistence::ParquetStorageConfig {
1806 batch_size: 1,
1807 ..Default::default()
1808 },
1809 )
1810 .unwrap();
1811 let event = crate::domain::entities::Event::from_strings(
1812 "test.event".to_string(),
1813 format!("{tenant}-{i}"),
1814 tenant.to_string(),
1815 serde_json::json!({"i": i}),
1816 None,
1817 )
1818 .unwrap();
1819 storage.append_event(event).unwrap();
1820 storage.flush().unwrap();
1821 }
1822 }
1823
1824 #[test]
1825 fn test_compact_tenant_emits_one_snapshot_and_removes_originals() {
1826 let temp_dir = TempDir::new().unwrap();
1827
1828 ingest_and_flush_per_call(temp_dir.path(), "alice", 4);
1830
1831 let config = CompactionConfig {
1832 min_files_to_compact: 2,
1833 small_file_threshold: 100 * 1024 * 1024,
1834 strategy: CompactionStrategy::SizeBased,
1835 ..Default::default()
1836 };
1837 let manager = CompactionManager::new(temp_dir.path(), config);
1838
1839 let result = manager.compact_tenant("alice").unwrap();
1840 assert_eq!(result.files_compacted, 4);
1841 assert_eq!(result.events_compacted, 4);
1842
1843 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1846 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1847 assert_eq!(
1848 alice_files.len(),
1849 1,
1850 "expected exactly one snapshot file for alice"
1851 );
1852
1853 let name = alice_files[0]
1854 .file_name()
1855 .and_then(|n| n.to_str())
1856 .unwrap()
1857 .to_string();
1858 assert!(
1859 name.starts_with("snapshot.alice."),
1860 "expected snapshot prefix, got {name}"
1861 );
1862 assert!(name.ends_with(".parquet"));
1863
1864 let tmps: Vec<_> = std::fs::read_dir(alice_files[0].parent().unwrap())
1866 .unwrap()
1867 .filter_map(std::result::Result::ok)
1868 .filter(|e| e.path().to_string_lossy().ends_with(".tmp"))
1869 .collect();
1870 assert!(tmps.is_empty());
1871
1872 let loaded = storage.load_events_for_tenant("alice").unwrap();
1874 assert_eq!(loaded.len(), 4);
1875 for e in &loaded {
1876 assert_eq!(e.tenant_id_str(), "alice");
1877 }
1878 }
1879
1880 #[test]
1881 fn test_compact_tenant_skips_existing_snapshot_files() {
1882 let temp_dir = TempDir::new().unwrap();
1887 ingest_and_flush_per_call(temp_dir.path(), "alice", 4);
1888
1889 let config = CompactionConfig {
1890 min_files_to_compact: 2,
1891 small_file_threshold: 100 * 1024 * 1024,
1892 ..Default::default()
1893 };
1894 let manager = CompactionManager::new(temp_dir.path(), config);
1895
1896 let r1 = manager.compact_tenant("alice").unwrap();
1897 assert_eq!(r1.files_compacted, 4);
1898
1899 let r2 = manager.compact_tenant("alice").unwrap();
1900 assert_eq!(r2.files_compacted, 0, "snapshot must not be re-compacted");
1901
1902 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1904 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1905 assert_eq!(alice_files.len(), 1);
1906 }
1907
1908 #[test]
1909 fn test_compact_tenant_below_threshold_is_a_noop() {
1910 let temp_dir = TempDir::new().unwrap();
1912 ingest_and_flush_per_call(temp_dir.path(), "alice", 1);
1913
1914 let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
1915 let result = manager.compact_tenant("alice").unwrap();
1916 assert_eq!(result.files_compacted, 0);
1917
1918 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1920 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
1921 assert_eq!(alice_files.len(), 1);
1922 let name = alice_files[0]
1923 .file_name()
1924 .unwrap()
1925 .to_string_lossy()
1926 .into_owned();
1927 assert!(
1928 !name.starts_with("snapshot."),
1929 "raw file must not be renamed"
1930 );
1931 }
1932
1933 #[test]
1934 fn test_compact_iterates_every_tenant() {
1935 let temp_dir = TempDir::new().unwrap();
1938 ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
1939 ingest_and_flush_per_call(temp_dir.path(), "bob", 3);
1940
1941 let config = CompactionConfig {
1942 min_files_to_compact: 2,
1943 small_file_threshold: 100 * 1024 * 1024,
1944 strategy: CompactionStrategy::SizeBased,
1945 ..Default::default()
1946 };
1947 let manager = CompactionManager::new(temp_dir.path(), config);
1948
1949 let result = manager.compact().unwrap();
1950 assert_eq!(result.files_compacted, 6);
1951 assert_eq!(result.events_compacted, 6);
1952
1953 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1954 for tenant in ["alice", "bob"] {
1955 let files = storage.list_parquet_files_for_tenant(tenant).unwrap();
1956 assert_eq!(files.len(), 1, "{tenant} should have one snapshot");
1957 let name = files[0].file_name().unwrap().to_string_lossy().into_owned();
1958 assert!(name.starts_with(&format!("snapshot.{tenant}.")));
1959 }
1960 }
1961
1962 #[test]
1963 fn test_retention_drops_events_older_than_ttl() {
1964 let temp_dir = TempDir::new().unwrap();
1968
1969 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1974 let now = Utc::now();
1975 for i in 0..100 {
1976 let day_offset = 60 - (i * 60 / 99);
1978 let ts = now - chrono::Duration::days(i64::from(day_offset));
1979 let event = crate::domain::entities::Event::reconstruct_from_strings(
1980 uuid::Uuid::new_v4(),
1981 "test.event".to_string(),
1982 format!("e-{i}"),
1983 "alice".to_string(),
1984 serde_json::json!({"i": i}),
1985 ts,
1986 None,
1987 1,
1988 );
1989 storage.append_event(event).unwrap();
1990 if i % 10 == 9 {
1994 storage.flush().unwrap();
1995 }
1996 }
1997 storage.flush().unwrap();
1998
1999 let mut retention = RetentionConfig::default();
2001 retention.set("alice", Some(Duration::from_hours(30 * 24)));
2002 let config = CompactionConfig {
2003 min_files_to_compact: 2,
2004 small_file_threshold: 100 * 1024 * 1024,
2005 strategy: CompactionStrategy::SizeBased,
2006 retention,
2007 ..Default::default()
2008 };
2009 let manager = CompactionManager::new(temp_dir.path(), config);
2010
2011 let result = manager.compact_tenant("alice").unwrap();
2012 assert!(result.events_compacted > 0);
2013 assert!(
2014 result.events_compacted < 100,
2015 "retention should have dropped some events; kept {} of 100",
2016 result.events_compacted
2017 );
2018
2019 let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
2021 let loaded = storage2.load_events_for_tenant("alice").unwrap();
2022 assert_eq!(loaded.len(), result.events_compacted);
2023
2024 let cutoff = Utc::now() - chrono::Duration::days(30);
2027 for e in &loaded {
2028 assert!(
2029 e.timestamp >= cutoff - chrono::Duration::seconds(60),
2030 "event with ts {} survived retention but is older than cutoff {}",
2031 e.timestamp.to_rfc3339(),
2032 cutoff.to_rfc3339()
2033 );
2034 }
2035 }
2036
2037 #[test]
2038 fn test_retention_keeps_forever_by_default_for_non_system_tenants() {
2039 let temp_dir = TempDir::new().unwrap();
2042 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2043 let now = Utc::now();
2044 for i in 0..6 {
2045 let ts = now - chrono::Duration::days(i * 365);
2046 let event = crate::domain::entities::Event::reconstruct_from_strings(
2047 uuid::Uuid::new_v4(),
2048 "test.event".to_string(),
2049 format!("e-{i}"),
2050 "alice".to_string(),
2051 serde_json::json!({"i": i}),
2052 ts,
2053 None,
2054 1,
2055 );
2056 storage.append_event(event).unwrap();
2057 if i % 2 == 1 {
2058 storage.flush().unwrap();
2059 }
2060 }
2061 storage.flush().unwrap();
2062
2063 let config = CompactionConfig {
2065 min_files_to_compact: 2,
2066 small_file_threshold: 100 * 1024 * 1024,
2067 strategy: CompactionStrategy::SizeBased,
2068 ..Default::default()
2069 };
2070 let manager = CompactionManager::new(temp_dir.path(), config);
2071 let result = manager.compact_tenant("alice").unwrap();
2072 assert_eq!(result.events_compacted, 6, "no events should be dropped");
2073 }
2074
2075 #[test]
2076 fn test_retention_system_tenant_default_is_30_days() {
2077 let cfg = RetentionConfig::default();
2081 let ttl = cfg.ttl_for("system").unwrap();
2082 assert_eq!(ttl.as_secs(), 30 * 24 * 3600);
2083 assert!(cfg.ttl_for("acme").is_none());
2085 }
2086
2087 #[test]
2088 fn test_retention_drops_all_events_deletes_originals_without_snapshot() {
2089 let temp_dir = TempDir::new().unwrap();
2093 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2094 let very_old = Utc::now() - chrono::Duration::days(90);
2095 for i in 0..6 {
2096 let event = crate::domain::entities::Event::reconstruct_from_strings(
2097 uuid::Uuid::new_v4(),
2098 "test.event".to_string(),
2099 format!("e-{i}"),
2100 "alice".to_string(),
2101 serde_json::json!({"i": i}),
2102 very_old,
2103 None,
2104 1,
2105 );
2106 storage.append_event(event).unwrap();
2107 if i % 2 == 1 {
2108 storage.flush().unwrap();
2109 }
2110 }
2111 storage.flush().unwrap();
2112
2113 let mut retention = RetentionConfig::default();
2114 retention.set("alice", Some(Duration::from_hours(7 * 24)));
2115 let config = CompactionConfig {
2116 min_files_to_compact: 2,
2117 small_file_threshold: 100 * 1024 * 1024,
2118 strategy: CompactionStrategy::SizeBased,
2119 retention,
2120 ..Default::default()
2121 };
2122 let manager = CompactionManager::new(temp_dir.path(), config);
2123 let result = manager.compact_tenant("alice").unwrap();
2124 assert_eq!(result.events_compacted, 0);
2125 assert!(result.files_compacted >= 2); let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
2129 let alice_files = storage2.list_parquet_files_for_tenant("alice").unwrap();
2130 assert!(alice_files.is_empty(), "all originals should be deleted");
2131 }
2132
2133 #[test]
2134 fn test_compaction_with_simulated_crash_leaves_data_recoverable() {
2135 let temp_dir = TempDir::new().unwrap();
2141
2142 ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
2144
2145 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2147 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
2148 let partition = alice_files[0].parent().unwrap().to_path_buf();
2149
2150 let crashed_tmp = partition.join("snapshot.alice.range.parquet.tmp");
2153 std::fs::write(&crashed_tmp, b"partial parquet bytes").unwrap();
2154 assert!(crashed_tmp.is_file());
2155
2156 let storage2 = ParquetStorage::new(temp_dir.path()).unwrap();
2158 assert!(
2159 !crashed_tmp.exists(),
2160 "stale tmp file should have been cleaned by ParquetStorage::new"
2161 );
2162
2163 let events = storage2.load_events_for_tenant("alice").unwrap();
2165 assert_eq!(events.len(), 3);
2166 }
2167
2168 #[test]
2169 fn test_cold_tier_archives_dropped_events_before_deletion() {
2170 use crate::infrastructure::persistence::cold_tier::LocalFsArchive;
2176
2177 let live_dir = TempDir::new().unwrap();
2178 let archive_dir = TempDir::new().unwrap();
2179
2180 let storage = ParquetStorage::new(live_dir.path()).unwrap();
2182 let now = Utc::now();
2183 for i in 0..50 {
2184 let day_offset = 60 - (i * 60 / 49);
2185 let ts = now - chrono::Duration::days(i64::from(day_offset));
2186 let event = crate::domain::entities::Event::reconstruct_from_strings(
2187 uuid::Uuid::new_v4(),
2188 "test.event".to_string(),
2189 format!("e-{i}"),
2190 "alice".to_string(),
2191 serde_json::json!({"i": i}),
2192 ts,
2193 None,
2194 1,
2195 );
2196 storage.append_event(event).unwrap();
2197 if i % 5 == 4 {
2198 storage.flush().unwrap();
2199 }
2200 }
2201 storage.flush().unwrap();
2202
2203 let mut retention = RetentionConfig::default();
2205 retention.set("alice", Some(Duration::from_hours(30 * 24)));
2206 let archive: Arc<dyn ArchiveTarget> =
2207 Arc::new(LocalFsArchive::new(archive_dir.path()).unwrap());
2208 let config = CompactionConfig {
2209 min_files_to_compact: 2,
2210 small_file_threshold: 100 * 1024 * 1024,
2211 strategy: CompactionStrategy::SizeBased,
2212 retention,
2213 archive: Some(archive),
2214 ..Default::default()
2215 };
2216 let manager = CompactionManager::new(live_dir.path(), config);
2217
2218 let result = manager.compact_tenant("alice").unwrap();
2219 assert!(result.events_compacted > 0, "some events kept");
2220 assert!(
2221 result.events_compacted < 50,
2222 "some events dropped to retention; kept {} of 50",
2223 result.events_compacted
2224 );
2225
2226 let live_after = ParquetStorage::new(live_dir.path())
2228 .unwrap()
2229 .load_events_for_tenant("alice")
2230 .unwrap();
2231 assert_eq!(live_after.len(), result.events_compacted);
2232
2233 let mut archive_files = vec![];
2236 let mut stack = vec![archive_dir.path().to_path_buf()];
2237 while let Some(d) = stack.pop() {
2238 for entry in std::fs::read_dir(&d).unwrap().flatten() {
2239 let p = entry.path();
2240 if p.is_dir() {
2241 stack.push(p);
2242 } else if p
2243 .file_name()
2244 .is_some_and(|n| n.to_string_lossy().starts_with("archive.alice."))
2245 {
2246 archive_files.push(p);
2247 }
2248 }
2249 }
2250 assert!(
2251 !archive_files.is_empty(),
2252 "archive directory must contain at least one archive.alice.* file"
2253 );
2254
2255 let archive_storage = ParquetStorage::new(archive_dir.path()).unwrap();
2258 let archived = archive_storage.load_events_for_tenant("alice").unwrap();
2259 assert_eq!(
2260 live_after.len() + archived.len(),
2261 50,
2262 "live + archived must equal original event count (live={}, archived={})",
2263 live_after.len(),
2264 archived.len()
2265 );
2266 }
2267
2268 #[test]
2269 fn test_cold_tier_failure_keeps_originals_on_disk() {
2270 let live_dir = TempDir::new().unwrap();
2274 let storage = ParquetStorage::new(live_dir.path()).unwrap();
2275 let now = Utc::now();
2276 for i in 0..20 {
2277 let ts = now - chrono::Duration::days(60 - i);
2278 let event = crate::domain::entities::Event::reconstruct_from_strings(
2279 uuid::Uuid::new_v4(),
2280 "test.event".to_string(),
2281 format!("e-{i}"),
2282 "alice".to_string(),
2283 serde_json::json!({"i": i}),
2284 ts,
2285 None,
2286 1,
2287 );
2288 storage.append_event(event).unwrap();
2289 if i % 5 == 4 {
2290 storage.flush().unwrap();
2291 }
2292 }
2293 storage.flush().unwrap();
2294
2295 let count_files = |dir: &std::path::Path| -> usize {
2298 let mut n = 0;
2299 let mut stack = vec![dir.to_path_buf()];
2300 while let Some(d) = stack.pop() {
2301 for entry in std::fs::read_dir(&d).unwrap().flatten() {
2302 let p = entry.path();
2303 if p.is_dir() {
2304 stack.push(p);
2305 } else if p.extension().is_some_and(|e| e == "parquet") {
2306 n += 1;
2307 }
2308 }
2309 }
2310 n
2311 };
2312 let before = count_files(live_dir.path());
2313 assert!(before > 0);
2314
2315 #[derive(Debug)]
2316 struct FailingArchive;
2317 impl ArchiveTarget for FailingArchive {
2318 fn archive(
2319 &self,
2320 _: &str,
2321 _: DateTime<Utc>,
2322 _: DateTime<Utc>,
2323 _: &[crate::domain::entities::Event],
2324 ) -> Result<()> {
2325 Err(AllSourceError::StorageError(
2326 "simulated archive outage".to_string(),
2327 ))
2328 }
2329 }
2330
2331 let mut retention = RetentionConfig::default();
2332 retention.set("alice", Some(Duration::from_hours(30 * 24)));
2333 let config = CompactionConfig {
2334 min_files_to_compact: 2,
2335 small_file_threshold: 100 * 1024 * 1024,
2336 strategy: CompactionStrategy::SizeBased,
2337 retention,
2338 archive: Some(Arc::new(FailingArchive) as Arc<dyn ArchiveTarget>),
2339 ..Default::default()
2340 };
2341 let manager = CompactionManager::new(live_dir.path(), config);
2342
2343 let result = manager.compact_tenant("alice");
2344 assert!(result.is_err(), "compaction must fail when archive fails");
2345
2346 let after = count_files(live_dir.path());
2348 assert_eq!(
2349 before, after,
2350 "no files should be removed after archive failure"
2351 );
2352
2353 let storage2 = ParquetStorage::new(live_dir.path()).unwrap();
2354 let loaded = storage2.load_events_for_tenant("alice").unwrap();
2355 assert_eq!(
2356 loaded.len(),
2357 20,
2358 "all 20 events still present after failed archive"
2359 );
2360 }
2361
2362 #[test]
2363 fn test_cold_tier_not_invoked_when_no_events_dropped() {
2364 let live_dir = TempDir::new().unwrap();
2368 let storage = ParquetStorage::new(live_dir.path()).unwrap();
2369 let now = Utc::now();
2370 for i in 0..10 {
2371 let ts = now - chrono::Duration::hours(i);
2372 let event = crate::domain::entities::Event::reconstruct_from_strings(
2373 uuid::Uuid::new_v4(),
2374 "test.event".to_string(),
2375 format!("e-{i}"),
2376 "alice".to_string(),
2377 serde_json::json!({"i": i}),
2378 ts,
2379 None,
2380 1,
2381 );
2382 storage.append_event(event).unwrap();
2383 if i % 3 == 2 {
2384 storage.flush().unwrap();
2385 }
2386 }
2387 storage.flush().unwrap();
2388
2389 #[derive(Debug)]
2390 struct PanickingArchive;
2391 impl ArchiveTarget for PanickingArchive {
2392 fn archive(
2393 &self,
2394 _: &str,
2395 _: DateTime<Utc>,
2396 _: DateTime<Utc>,
2397 _: &[crate::domain::entities::Event],
2398 ) -> Result<()> {
2399 panic!("archive must not be called when no events are dropped");
2400 }
2401 }
2402
2403 let config = CompactionConfig {
2405 min_files_to_compact: 2,
2406 small_file_threshold: 100 * 1024 * 1024,
2407 strategy: CompactionStrategy::SizeBased,
2408 archive: Some(Arc::new(PanickingArchive) as Arc<dyn ArchiveTarget>),
2409 ..Default::default()
2410 };
2411 let manager = CompactionManager::new(live_dir.path(), config);
2412 let result = manager.compact_tenant("alice").unwrap();
2413 assert_eq!(result.events_compacted, 10);
2414 }
2415
2416 #[test]
2417 fn test_discover_tenants_skips_system_and_hidden() {
2418 let temp_dir = TempDir::new().unwrap();
2421 std::fs::create_dir_all(temp_dir.path().join("alice")).unwrap();
2422 std::fs::create_dir_all(temp_dir.path().join("bob")).unwrap();
2423 std::fs::create_dir_all(temp_dir.path().join("__system")).unwrap();
2424 std::fs::create_dir_all(temp_dir.path().join(".hidden")).unwrap();
2425
2426 let manager = CompactionManager::new(temp_dir.path(), CompactionConfig::default());
2427 let tenants = manager.discover_tenants().unwrap();
2428 assert_eq!(tenants, vec!["alice".to_string(), "bob".to_string()]);
2429 }
2430}