Skip to main content

allsource_core/infrastructure/persistence/
compaction.rs

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
10/// Manages Parquet file compaction for optimal storage and query performance.
11///
12/// Step 4 of the sustainable data strategy moved compaction from a
13/// global-stream pass to a per-tenant pass. Each invocation iterates
14/// the tenants discovered under `<storage_dir>/<tenant>/...` and
15/// emits a `snapshot.<tenant>.<from>-<to>.parquet` per qualifying
16/// chunk. Snapshot files are written atomically (tmp + rename) and
17/// their constituent raw files are removed only after the rename
18/// succeeds — so a mid-compaction crash leaves data intact.
19pub struct CompactionManager {
20    /// Directory where Parquet files are stored
21    storage_dir: PathBuf,
22
23    /// Configuration
24    config: CompactionConfig,
25
26    /// Statistics
27    stats: Arc<RwLock<CompactionStats>>,
28
29    /// Last compaction time
30    last_compaction: Arc<RwLock<Option<DateTime<Utc>>>>,
31
32    /// Tenant the previous sweep stopped after.
33    ///
34    /// A sweep has a time budget and visits tenants in a stable order, so
35    /// without a cursor the tenants sorting last never get reached while
36    /// there is a backlog — and the worst offender is not usually the one
37    /// that sorts first. Each sweep resumes after this one.
38    sweep_cursor: Arc<RwLock<Option<String>>>,
39}
40
41/// Filename prefix that marks a file as already-compacted output.
42///
43/// A snapshot is a candidate again while it is still smaller than
44/// `small_file_threshold`, so a pass that can only reach part of a tenant
45/// merges its own earlier output upward instead of leaving a snapshot per
46/// pass behind. Excluding them unconditionally traded one fragmentation
47/// rate for a slower one: the tenant in gh#321 takes ~7 new files an hour,
48/// which is a snapshot an hour, forever.
49const SNAPSHOT_PREFIX: &str = "snapshot.";
50
51#[derive(Debug, Clone)]
52pub struct CompactionConfig {
53    /// Minimum number of files to trigger compaction
54    pub min_files_to_compact: usize,
55
56    /// Target size for compacted files (in bytes)
57    pub target_file_size: usize,
58
59    /// Maximum size for a single compacted file (in bytes)
60    pub max_file_size: usize,
61
62    /// Minimum file size to consider for compaction (small files)
63    pub small_file_threshold: usize,
64
65    /// Compressed input bytes one snapshot may be built from.
66    ///
67    /// A group's events are all resident at once, and decoding this archive
68    /// shape costs roughly 16× its on-disk size, so this is the term that
69    /// bounds a compaction pass's peak memory. A tenant whose candidates
70    /// exceed it is compacted into several snapshots instead of one.
71    pub max_input_bytes_per_snapshot: u64,
72
73    /// Input files one snapshot may be built from, bounding footer opens and
74    /// path bookkeeping independently of how small the files are.
75    pub max_input_files_per_snapshot: usize,
76
77    /// Wall-clock budget for one compaction sweep. Checked between groups,
78    /// so a sweep overruns by at most one group.
79    ///
80    /// A backlog is resumed on the next tick rather than drained in one
81    /// pass: the first sweep over an uncompacted tenant has as many groups
82    /// as the tenant has, and an unbounded sweep would hold CPU and disk
83    /// for as long as that takes.
84    pub max_pass_seconds: u64,
85
86    /// Time interval between automatic compactions (in seconds)
87    pub compaction_interval_seconds: u64,
88
89    /// Enable automatic background compaction
90    pub auto_compact: bool,
91
92    /// Compaction strategy
93    pub strategy: CompactionStrategy,
94
95    /// Per-tenant retention TTLs (Step 5 of the sustainable data
96    /// strategy). Applied during the same compaction pass — events
97    /// older than `now - ttl` for that tenant are dropped from the
98    /// snapshot output and the originals are removed. Default
99    /// honors the bead: tenant `system` keeps 30 days; everyone
100    /// else keeps forever.
101    pub retention: RetentionConfig,
102
103    /// Optional cold-tier archive. When set, events that would be
104    /// dropped by retention are archived to this target BEFORE the
105    /// originals are deleted. A failed archive aborts the
106    /// compaction pass — originals stay on disk and the next run
107    /// retries. Default `None` preserves the pre-cold-tier behavior:
108    /// retention deletes outright. See
109    /// `infrastructure::persistence::cold_tier`.
110    pub archive: Option<Arc<dyn ArchiveTarget>>,
111}
112
113/// Per-tenant retention configuration. Look up a TTL via
114/// `ttl_for(tenant_id)`; `None` means "keep forever" for that
115/// tenant.
116///
117/// The default rule (from the bead): the CP heartbeat tenant
118/// (`system`) defaults to 30 days. The CP emits ~69k heartbeat
119/// events/day; without retention this grows unbounded for data
120/// that has no audit value past the dashboard window. Other
121/// tenants default to no TTL — user data stays put unless the
122/// owner opts in.
123///
124/// Per-tenant overrides win over `default_ttl`; "no entry" falls
125/// back to `default_ttl`.
126#[derive(Debug, Clone)]
127pub struct RetentionConfig {
128    /// Default TTL when no per-tenant override exists. `None` = keep forever.
129    pub default_ttl: Option<Duration>,
130    /// Per-tenant overrides. `Some(None)` would mean "explicitly no
131    /// TTL"; the API uses `Option<Duration>` directly so an entry
132    /// can record an explicit "keep forever" decision distinct
133    /// from "no entry".
134    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    /// Effective TTL for `tenant_id`. Returns `None` if the tenant
150    /// has no TTL (keep forever).
151    ///
152    /// Lookup order:
153    /// 1. Per-tenant entry → that value (whether Some or explicit None).
154    /// 2. No entry → fall back to `default_ttl`.
155    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    /// Override the TTL for a specific tenant. Use `None` to mean
163    /// "keep forever for this tenant".
164    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,    // 128 MB
174            max_file_size: 256 * 1024 * 1024,       // 256 MB
175            small_file_threshold: 10 * 1024 * 1024, // 10 MB
176            max_input_bytes_per_snapshot: 32 * 1024 * 1024, // 32 MiB ≈ 512 MiB resident
177            max_input_files_per_snapshot: 2000,
178            max_pass_seconds: 240,
179            compaction_interval_seconds: 3600, // 1 hour
180            auto_compact: true,
181            strategy: CompactionStrategy::SizeBased,
182            retention: RetentionConfig::default(),
183            archive: None,
184        }
185    }
186}
187
188impl CompactionConfig {
189    /// Build a config from the relevant env vars:
190    /// - `ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS`: per-pass cadence
191    ///   (default 3600).
192    /// - `ALLSOURCE_RETENTION_SYSTEM_DAYS`: TTL for the `system`
193    ///   tenant in days (default 30).
194    /// - `ALLSOURCE_COMPACTION_INPUT_BYTES`: compressed input bytes per
195    ///   snapshot, which bounds a pass's peak memory (default 32 MiB).
196    ///
197    /// Unparseable values log a warning and fall back to defaults
198    /// — boot doesn't fail.
199    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    /// Override `max_input_bytes_per_snapshot`. Zero is rejected: it would
209    /// make every file its own group and rewrite the tenant file-for-file.
210    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    /// Attach a cold-tier archive from `ALLSOURCE_COLD_STORAGE_URL`
229    /// (`s3://bucket/prefix`). Unset or empty leaves `archive` as `None`,
230    /// which is the default: retention deletes without archiving.
231    ///
232    /// A URL that is set but unusable is a hard error, not a warning. Every
233    /// other env var here falls back to a default because a wrong interval
234    /// costs a slow pass; this one decides whether events are copied somewhere
235    /// before compaction deletes the originals, so degrading to "no archive"
236    /// would turn an operator's typo into silent data loss.
237    #[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    /// Testable variant of `from_env`. Production calls `from_env`;
269    /// tests pass explicit values.
270    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                // Zero days means keep forever, not "expire everything now".
290                // The literal reading would have this variable delete the
291                // tenant's entire history, which is not what an operator
292                // reaching for a smaller number is asking for, and there is
293                // no other way to express "no TTL" through the environment:
294                // leaving the variable unset falls back to the 30-day
295                // default rather than disabling it.
296                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    /// Backwards-compatible single-arg variant for existing
319    /// callers that only set the snapshot interval.
320    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    /// Compact based on file size (default)
329    SizeBased,
330    /// Compact based on file age
331    TimeBased,
332    /// Compact all files into one
333    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/// Information about a Parquet file candidate for compaction
348#[derive(Debug, Clone)]
349struct FileInfo {
350    path: PathBuf,
351    size: u64,
352    created: DateTime<Utc>,
353}
354
355impl CompactionManager {
356    /// Create a new compaction manager
357    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    /// List all Parquet files in the storage directory
375    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        // Sort by creation time (oldest first)
415        files.sort_by_key(|f| f.created);
416
417        Ok(files)
418    }
419
420    /// Identify files that should be compacted based on strategy
421    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    /// Select small files for compaction
430    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        // Only compact if we have enough small files
438        if small_files.len() >= self.config.min_files_to_compact {
439            small_files
440        } else {
441            Vec::new()
442        }
443    }
444
445    /// Select old files for time-based compaction
446    fn select_old_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
447        let now = Utc::now();
448        let age_threshold = chrono::Duration::hours(24); // Files older than 24 hours
449
450        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    /// Check if compaction should run
464    #[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, // Never compacted
473            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    /// Perform compaction across every discovered tenant.
481    ///
482    /// Iterates the tenants under `<storage_dir>/<tenant>/...`, calls
483    /// `compact_tenant` for each, and aggregates the results. Step 4
484    /// of the sustainable data strategy: per-tenant compaction
485    /// instead of global, keyed off the per-tenant directory tree
486    /// Step 1 introduced.
487    ///
488    /// Errors compacting one tenant are logged but don't abort the
489    /// pass — other tenants still get compacted. The aggregate
490    /// result reflects what actually completed.
491    ///
492    /// The sweep stops starting work once `max_pass_seconds` is spent and
493    /// resumes on the next tick. Tenants are visited in a stable order, so a
494    /// sweep that runs out of budget always leaves the same tail — the
495    /// per-pass bound is on time, and progress comes from the files each
496    /// group removes.
497    #[cfg_attr(feature = "hotpath", hotpath::measure)]
498    pub fn compact(&self) -> Result<CompactionResult> {
499        self.compact_until(None)
500    }
501
502    /// Where the next sweep will start, or `None` before the first one.
503    ///
504    /// Diagnostic: a cursor that never moves off one tenant means that
505    /// tenant's backlog is larger than a single pass's budget.
506    pub fn sweep_cursor(&self) -> Option<String> {
507        self.sweep_cursor.read().clone()
508    }
509
510    /// [`Self::compact`] with an explicit deadline in place of the one
511    /// `max_pass_seconds` derives.
512    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            // Still a sweep that happened. Leaving `last_compaction` unset
520            // would have `should_compact` answer yes on every tick, so an
521            // empty store would be swept continuously.
522            *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        // The first tenant this sweep did not finish. The next sweep starts
533        // there, so a tenant paused half way is resumed rather than waiting
534        // a full rotation, and a tenant never reached is reached next.
535        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        // Everything finished: start the next sweep where this one did, so a
561        // steady state keeps visiting tenants in one stable order.
562        *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    /// Compact one tenant's event files into snapshot files under that
600    /// tenant's partition.
601    ///
602    /// Per-tenant pipeline:
603    /// 1. List `<storage>/<tenant>/...*.parquet`, keeping an existing
604    ///    `snapshot.*` only while it is still under
605    ///    `small_file_threshold` so partial passes merge upward.
606    /// 2. Apply the configured strategy (size / time / full) to
607    ///    pick candidates.
608    /// 3. Split the candidates into groups bounded by
609    ///    `max_input_bytes_per_snapshot` and
610    ///    `max_input_files_per_snapshot`, and compact each group on its
611    ///    own. One group's events are resident at a time, so a tenant's
612    ///    size sets how many snapshots a pass writes, never how much
613    ///    memory it needs.
614    ///
615    /// Each group is independently crash-safe: its snapshot is renamed
616    /// into place before any of its own inputs is deleted, and a crash
617    /// between groups leaves the earlier groups compacted and the later
618    /// ones untouched.
619    pub fn compact_tenant(&self, tenant_id: &str) -> Result<CompactionResult> {
620        self.compact_tenant_until(tenant_id, None)
621    }
622
623    /// `compact_tenant` with a sweep deadline. Checked between groups, so the
624    /// tenant's remaining groups are left for the next tick rather than
625    /// abandoned mid-group — a group either publishes its snapshot and
626    /// deletes its inputs or does neither.
627    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    /// `compact_tenant_until`, also reporting whether every group ran.
637    ///
638    /// The sweep needs that answer to place its cursor: a tenant paused on
639    /// the budget has to be the next sweep's first call.
640    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                // A snapshot that already reached the threshold is finished
660                // output: re-reading it would rewrite the whole tenant every
661                // pass for no reduction in file count.
662                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        // Oldest first, so each group covers a contiguous time range and the
689        // snapshots a pass writes do not interleave.
690        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        // A group that fails does not stop the others. One unreadable file
705        // otherwise blocks its whole tenant from ever compacting, and the
706        // groups that have nothing wrong with them are what reduce the file
707        // count. The failure is still returned, so a caller cannot read a
708        // partial sweep as a clean one.
709        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    /// Split candidates into groups no larger than the configured input
750    /// bounds. A single file over the byte bound is its own group — refusing
751    /// it would leave it uncompactable forever.
752    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    /// Compact one bounded group of this tenant's files into a single
775    /// snapshot. Only this group's events are resident.
776    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        // Each file is read individually rather than through
786        // load_events_for_tenant so only the candidate set is picked up —
787        // concurrent writes that produced new files since enumeration are
788        // deferred to the next interval (AC #6).
789        let mut events = Vec::new();
790        for fi in candidates {
791            // Recover tenant from path so loaded events keep
792            // their identity (Step 1's path-as-tenant-source).
793            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            // Every selected input must be readable before any retention,
805            // archive, snapshot or deletion step can run. Skipping a failed
806            // input would later delete it as if its contents were preserved.
807            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        // Apply retention (Step 5). Drop events older than the
827        // tenant's TTL before they get rewritten into the
828        // snapshot. The originals get deleted at the end of the
829        // happy path either way, so dropped events go away with
830        // the same crash-safe guarantee as the rest of the
831        // compaction pipeline (snapshot rename completes BEFORE
832        // any original is deleted; AC #6).
833        //
834        // Cold-tier (sustainability): when an `archive` target is
835        // configured, dropped events are written to it BEFORE this
836        // function deletes any original file. A failed archive
837        // returns `Err`, originals stay on disk, and the next
838        // compaction pass retries — same crash-safety contract as
839        // the snapshot path. Without an archive, retention behaves
840        // exactly as before (delete outright).
841        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            // Partition: drained = events past TTL, kept = events to keep.
847            // Using drain_filter would be simpler but it's unstable;
848            // partition + reassign keeps events: Vec<Event> with the
849            // kept slice in original order.
850            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        // Edge case: every event aged out. Skip the snapshot
892        // write and just delete originals — the data is gone by
893        // design. Delete-without-snapshot is safe here because
894        // every event we'd have written to the snapshot was
895        // already past its TTL, and the input files live under
896        // the tenant's partition with nothing else relying on
897        // them.
898        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        // Filename: snapshot.<tenant>.<from>-<to>.<nanos> with
927        // filesystem-safe ISO-basic timestamps (no colons). The nanosecond
928        // discriminator keeps two snapshots covering the same range from
929        // sharing a path: a snapshot can itself be an input, so a colliding
930        // stem would have the write land on a file the delete below removes.
931        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        // Delete inputs AFTER the snapshot is durably renamed. AC #6: a
941        // snapshot-write failure short-circuits via the `?` above, so inputs
942        // stay on disk and events remain queryable until the next pass.
943        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    /// Reorder `tenants` so the sweep begins at the cursor, wrapping around.
977    ///
978    /// The cursor names the tenant to start at, not the one last finished: a
979    /// tenant paused on the time budget has to be the next sweep's first
980    /// call, or its remaining groups wait a full rotation. A cursor naming a
981    /// tenant that no longer exists falls back to the start.
982    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    /// Discover tenant ids by scanning `<storage_dir>/<X>/` for
996    /// directories. The migration tool's flat-layout files at the
997    /// root are not picked up — Step 1 #3's migration moves them
998    /// under `default/`.
999    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                // Skip the system metadata subtree (Core's own
1012                // event-sourced repos) and any hidden folders.
1013                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    /// Get compaction statistics
1024    pub fn stats(&self) -> CompactionStats {
1025        (*self.stats.read()).clone()
1026    }
1027
1028    /// Get configuration
1029    pub fn config(&self) -> &CompactionConfig {
1030        &self.config
1031    }
1032
1033    /// Trigger manual compaction
1034    #[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/// Result of a compaction operation
1042#[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
1051/// Format a UTC timestamp as a filename-safe ISO-8601 basic-form
1052/// string: `2026-04-27T134567Z` — no colons, no fractional second.
1053/// Used for the `<from>-<to>` portion of snapshot filenames so
1054/// they're portable across filesystems. `pub(super)` so the
1055/// cold-tier archive can reuse the same naming convention.
1056pub(super) fn format_iso_basic(t: DateTime<Utc>) -> String {
1057    t.format("%Y-%m-%dT%H%M%SZ").to_string()
1058}
1059
1060/// Background compaction task
1061pub struct CompactionTask {
1062    manager: Arc<CompactionManager>,
1063    interval: Duration,
1064}
1065
1066impl CompactionTask {
1067    /// Create a new background compaction task
1068    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    /// Run the compaction task in a loop
1076    #[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        // Should compact on first check (never compacted)
1131        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, // 1 MB
1139            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, // 500 KB
1149                created: Utc::now(),
1150            },
1151            FileInfo {
1152                path: PathBuf::from("small2.parquet"),
1153                size: 600_000, // 600 KB
1154                created: Utc::now(),
1155            },
1156            FileInfo {
1157                path: PathBuf::from("large.parquet"),
1158                size: 10_000_000, // 10 MB
1159                created: Utc::now(),
1160            },
1161        ];
1162
1163        let selected = manager.select_files_for_compaction(&files);
1164        assert_eq!(selected.len(), 2); // Only the 2 small files
1165    }
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, // Need 3 files
1248            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); // Not enough small files
1268    }
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); // Only the 2 old files
1301    }
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); // Not enough old files
1329    }
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); // All files selected
1355    }
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        // Task created successfully
1419    }
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        // Create non-parquet files
1438        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()); // No parquet files
1443    }
1444
1445    // -----------------------------------------------------------------
1446    // Per-tenant compaction tests (Step 4, commit #2).
1447    // -----------------------------------------------------------------
1448
1449    fn ingest_and_flush_per_call(storage_dir: &std::path::Path, tenant: &str, count: usize) {
1450        // Each ingested batch produces one parquet file when its
1451        // ParquetStorage is dropped, giving us multiple raw files
1452        // per tenant for the strategy filter to pick up.
1453        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        // Seed 4 raw files for alice.
1480        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        // After: zero raw files, exactly one snapshot.* file under
1495        // alice's subtree.
1496        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        // No tmp files left behind.
1516        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        // Loaded events round-trip correctly.
1524        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        // Seed alice with 4 raw files, run compaction → 1 snapshot.
1534        // Run compaction AGAIN: the snapshot is excluded from the
1535        // candidate set, no qualifying raw files remain, the second
1536        // pass is a no-op.
1537        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        // Still exactly one file on disk for alice.
1554        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        // 1 file < min_files_to_compact (default 3) → nothing happens.
1562        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        // Raw file untouched.
1570        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        // Two tenants each with enough raw files. compact() must
1587        // produce one snapshot per tenant.
1588        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        // Bead's integration test: ingest 100 events spanning 60
1616        // days, run compaction with 30-day TTL, only the last
1617        // 30 days remain queryable.
1618        let temp_dir = TempDir::new().unwrap();
1619
1620        // Seed alice with 100 events, timestamps spread across
1621        // 60 days. We can't backdate via ingest (timestamp = now()
1622        // in domain), so write parquet directly via flush of
1623        // back-dated events.
1624        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1625        let now = Utc::now();
1626        for i in 0..100 {
1627            // Day 0 = 60 days ago; day 99 ≈ now. Spreads evenly.
1628            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            // Every 10 events get a fresh storage to produce a
1642            // separate file (so compaction has multiple files
1643            // to merge).
1644            if i % 10 == 9 {
1645                storage.flush().unwrap();
1646            }
1647        }
1648        storage.flush().unwrap();
1649
1650        // 30-day TTL for alice via per-tenant override.
1651        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        // Re-load to confirm the dropped events are gone.
1671        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        // Every loaded event must be within the 30-day window
1676        // (with a generous fudge for test-clock drift).
1677        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        // alice has no override → falls through to default_ttl
1691        // which is None. All events kept regardless of age.
1692        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        // Default RetentionConfig: alice has no entry, default_ttl = None.
1715        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        // The system tenant's 30-day TTL is the bead's headline
1729        // requirement. Default config without any overrides
1730        // should already enforce it.
1731        let cfg = RetentionConfig::default();
1732        let ttl = cfg.ttl_for("system").unwrap();
1733        assert_eq!(ttl.as_secs(), 30 * 24 * 3600);
1734        // No override for arbitrary tenants → keep forever.
1735        assert!(cfg.ttl_for("acme").is_none());
1736    }
1737
1738    #[test]
1739    fn test_retention_drops_all_events_deletes_originals_without_snapshot() {
1740        // Edge case: every event is past the TTL. We delete the
1741        // raw files and emit no snapshot — there's nothing to
1742        // write. Tenant ends with zero files on disk.
1743        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); // originals were deleted
1777
1778        // Tenant subtree has zero parquet files now.
1779        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        // AC #7-#8: simulate "crash mid-snapshot" by manually
1787        // dropping a tmp file in the partition, then asserting
1788        // a fresh ParquetStorage::new boot cleans it up and the
1789        // raw files (which would still be present in a real
1790        // mid-rename crash) remain queryable.
1791        let temp_dir = TempDir::new().unwrap();
1792
1793        // Seed alice with raw files.
1794        ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
1795
1796        // Locate alice's partition dir.
1797        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        // Simulate the crash state: write a partial .tmp file as
1802        // if write_atomic_parquet had crashed mid-rename.
1803        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        // Reboot — ParquetStorage::new triggers cleanup_partial_writes.
1808        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        // Raw files survived; events queryable.
1815        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        // Cold-tier integration: when retention drops events AND an
1822        // archive target is configured, the dropped events end up
1823        // in the archive root before originals are removed. This is
1824        // the load-bearing property — without archive-before-delete
1825        // the cold tier would silently lose data on retention runs.
1826        use crate::infrastructure::persistence::cold_tier::LocalFsArchive;
1827
1828        let live_dir = TempDir::new().unwrap();
1829        let archive_dir = TempDir::new().unwrap();
1830
1831        // Seed alice with 50 events spread across 60 days.
1832        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        // 30-day TTL + cold-tier archive.
1855        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        // Live storage: only events within the 30-day window.
1878        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        // Archive: contains the dropped events. Walk the archive root
1885        // and load any archive.alice.* file we find.
1886        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        // Sum events across archive files; total live + archived
1907        // must equal the original 50 (no events lost in the pipeline).
1908        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        // Crash-safety contract: a failing archive must NOT delete
1922        // originals. We use a custom ArchiveTarget that always
1923        // returns Err to simulate an outage.
1924        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        // Count files before. The compaction pipeline should leave
1947        // them all on disk after the failed archive.
1948        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        // Originals still on disk — every event still queryable.
1998        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        // If retention drops zero events (e.g. tenant has no TTL),
2016        // the archive target must NOT be called. We assert by using
2017        // an archive that panics on call.
2018        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        // Default retention → alice has no TTL → no events dropped.
2055        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        // Ensure the tenant scan doesn't pick up __system or hidden
2070        // directories — they're internal, not real tenants.
2071        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}