Skip to main content

allsource_core/infrastructure/persistence/
compaction.rs

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
24/// Carries the last sweep's completion time across restarts.
25///
26/// A pass scheduled against process uptime never runs on a service that
27/// restarts more often than its interval, and leaves no evidence either way
28/// (gh#321).
29const 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
38/// Manages Parquet file compaction for optimal storage and query performance.
39///
40/// Step 4 of the sustainable data strategy moved compaction from a
41/// global-stream pass to a per-tenant pass. Each invocation iterates
42/// the tenants discovered under `<storage_dir>/<tenant>/...` and
43/// emits a `snapshot.<tenant>.<from>-<to>.parquet` per qualifying
44/// chunk. Snapshot files are written atomically (tmp + rename) and
45/// their constituent raw files are removed only after the rename
46/// succeeds — so a mid-compaction crash leaves data intact.
47pub struct CompactionManager {
48    /// Directory where Parquet files are stored
49    storage_dir: PathBuf,
50
51    /// Configuration
52    config: CompactionConfig,
53
54    /// Statistics
55    stats: Arc<RwLock<CompactionStats>>,
56
57    /// Last compaction time
58    last_compaction: Arc<RwLock<Option<DateTime<Utc>>>>,
59
60    /// Tenant the previous sweep stopped after.
61    ///
62    /// A sweep has a time budget and visits tenants in a stable order, so
63    /// without a cursor the tenants sorting last never get reached while
64    /// there is a backlog — and the worst offender is not usually the one
65    /// that sorts first. Each sweep resumes after this one.
66    sweep_cursor: Arc<RwLock<Option<String>>>,
67
68    /// Whether the last sweep stopped with tenants still unvisited.
69    ///
70    /// A paused sweep has a backlog waiting on it, so the next one is
71    /// scheduled at the settle delay rather than a full interval. Draining a
72    /// backlog one pass per interval is how fragmentation outruns compaction.
73    last_sweep_paused: Arc<RwLock<bool>>,
74}
75
76/// Filename prefix that marks a file as already-compacted output.
77///
78/// A snapshot is a candidate again while it is still smaller than
79/// `small_file_threshold`, so a pass that can only reach part of a tenant
80/// merges its own earlier output upward instead of leaving a snapshot per
81/// pass behind. Excluding them unconditionally traded one fragmentation
82/// rate for a slower one: the tenant in gh#321 takes ~7 new files an hour,
83/// which is a snapshot an hour, forever.
84const SNAPSHOT_PREFIX: &str = "snapshot.";
85
86#[derive(Debug, Clone)]
87pub struct CompactionConfig {
88    /// Minimum number of files to trigger compaction
89    pub min_files_to_compact: usize,
90
91    /// Target size for compacted files (in bytes)
92    pub target_file_size: usize,
93
94    /// Maximum size for a single compacted file (in bytes)
95    pub max_file_size: usize,
96
97    /// Minimum file size to consider for compaction (small files)
98    pub small_file_threshold: usize,
99
100    /// Compressed input bytes one snapshot may be built from.
101    ///
102    /// A group's events are all resident at once, and decoding this archive
103    /// shape costs roughly 16× its on-disk size, so this is the term that
104    /// bounds a compaction pass's peak memory. A tenant whose candidates
105    /// exceed it is compacted into several snapshots instead of one.
106    pub max_input_bytes_per_snapshot: u64,
107
108    /// Input files one snapshot may be built from, bounding footer opens and
109    /// path bookkeeping independently of how small the files are.
110    pub max_input_files_per_snapshot: usize,
111
112    /// Wall-clock budget for one compaction sweep. Checked between groups,
113    /// so a sweep overruns by at most one group.
114    ///
115    /// A backlog is resumed on the next tick rather than drained in one
116    /// pass: the first sweep over an uncompacted tenant has as many groups
117    /// as the tenant has, and an unbounded sweep would hold CPU and disk
118    /// for as long as that takes.
119    pub max_pass_seconds: u64,
120
121    /// Time interval between automatic compactions (in seconds)
122    pub compaction_interval_seconds: u64,
123
124    /// Enable automatic background compaction
125    pub auto_compact: bool,
126
127    /// Compaction strategy
128    pub strategy: CompactionStrategy,
129
130    /// Per-tenant retention TTLs (Step 5 of the sustainable data
131    /// strategy). Applied during the same compaction pass — events
132    /// older than `now - ttl` for that tenant are dropped from the
133    /// snapshot output and the originals are removed. Default
134    /// honors the bead: tenant `system` keeps 30 days; everyone
135    /// else keeps forever.
136    pub retention: RetentionConfig,
137
138    /// Optional cold-tier archive. When set, events that would be
139    /// dropped by retention are archived to this target BEFORE the
140    /// originals are deleted. A failed archive aborts the
141    /// compaction pass — originals stay on disk and the next run
142    /// retries. Default `None` preserves the pre-cold-tier behavior:
143    /// retention deletes outright. See
144    /// `infrastructure::persistence::cold_tier`.
145    pub archive: Option<Arc<dyn ArchiveTarget>>,
146}
147
148/// Per-tenant retention configuration. Look up a TTL via
149/// `ttl_for(tenant_id)`; `None` means "keep forever" for that
150/// tenant.
151///
152/// The default rule (from the bead): the CP heartbeat tenant
153/// (`system`) defaults to 30 days. The CP emits ~69k heartbeat
154/// events/day; without retention this grows unbounded for data
155/// that has no audit value past the dashboard window. Other
156/// tenants default to no TTL — user data stays put unless the
157/// owner opts in.
158///
159/// Per-tenant overrides win over `default_ttl`; "no entry" falls
160/// back to `default_ttl`.
161#[derive(Debug, Clone)]
162pub struct RetentionConfig {
163    /// Default TTL when no per-tenant override exists. `None` = keep forever.
164    pub default_ttl: Option<Duration>,
165    /// Per-tenant overrides. `Some(None)` would mean "explicitly no
166    /// TTL"; the API uses `Option<Duration>` directly so an entry
167    /// can record an explicit "keep forever" decision distinct
168    /// from "no entry".
169    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    /// Effective TTL for `tenant_id`. Returns `None` if the tenant
185    /// has no TTL (keep forever).
186    ///
187    /// Lookup order:
188    /// 1. Per-tenant entry → that value (whether Some or explicit None).
189    /// 2. No entry → fall back to `default_ttl`.
190    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    /// Override the TTL for a specific tenant. Use `None` to mean
198    /// "keep forever for this tenant".
199    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,    // 128 MB
209            max_file_size: 256 * 1024 * 1024,       // 256 MB
210            small_file_threshold: 10 * 1024 * 1024, // 10 MB
211            max_input_bytes_per_snapshot: 32 * 1024 * 1024, // 32 MiB ≈ 512 MiB resident
212            max_input_files_per_snapshot: 2000,
213            max_pass_seconds: 240,
214            compaction_interval_seconds: 3600, // 1 hour
215            auto_compact: true,
216            strategy: CompactionStrategy::SizeBased,
217            retention: RetentionConfig::default(),
218            archive: None,
219        }
220    }
221}
222
223impl CompactionConfig {
224    /// Build a config from the relevant env vars:
225    /// - `ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS`: per-pass cadence
226    ///   (default 3600).
227    /// - `ALLSOURCE_RETENTION_SYSTEM_DAYS`: TTL for the `system`
228    ///   tenant in days (default 30).
229    /// - `ALLSOURCE_COMPACTION_INPUT_BYTES`: compressed input bytes per
230    ///   snapshot, which bounds a pass's peak memory (default 32 MiB).
231    ///
232    /// Unparseable values log a warning and fall back to defaults
233    /// — boot doesn't fail.
234    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    /// Override `max_input_bytes_per_snapshot`. Zero is rejected: it would
244    /// make every file its own group and rewrite the tenant file-for-file.
245    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    /// Attach a cold-tier archive from `ALLSOURCE_COLD_STORAGE_URL`
264    /// (`s3://bucket/prefix`). Unset or empty leaves `archive` as `None`,
265    /// which is the default: retention deletes without archiving.
266    ///
267    /// A URL that is set but unusable is a hard error, not a warning. Every
268    /// other env var here falls back to a default because a wrong interval
269    /// costs a slow pass; this one decides whether events are copied somewhere
270    /// before compaction deletes the originals, so degrading to "no archive"
271    /// would turn an operator's typo into silent data loss.
272    #[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    /// Testable variant of `from_env`. Production calls `from_env`;
304    /// tests pass explicit values.
305    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                // Zero days means keep forever, not "expire everything now".
325                // The literal reading would have this variable delete the
326                // tenant's entire history, which is not what an operator
327                // reaching for a smaller number is asking for, and there is
328                // no other way to express "no TTL" through the environment:
329                // leaving the variable unset falls back to the 30-day
330                // default rather than disabling it.
331                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    /// Backwards-compatible single-arg variant for existing
354    /// callers that only set the snapshot interval.
355    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    /// Compact based on file size (default)
364    SizeBased,
365    /// Compact based on file age
366    TimeBased,
367    /// Compact all files into one
368    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/// Information about a Parquet file candidate for compaction
383#[derive(Debug, Clone)]
384struct FileInfo {
385    path: PathBuf,
386    size: u64,
387    created: DateTime<Utc>,
388}
389
390impl CompactionManager {
391    /// Create a new compaction manager
392    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                // Treating this as "never swept" schedules one promptly, which
422                // is the safe direction: the cost is a redundant pass.
423                tracing::warn!("Unreadable compaction state, treating as never swept: {e}");
424                None
425            }
426        }
427    }
428
429    /// When the last sweep finished, across restarts.
430    pub fn last_compaction(&self) -> Option<DateTime<Utc>> {
431        *self.last_compaction.read()
432    }
433
434    /// Whether the last sweep left tenants unvisited, across restarts.
435    pub fn last_sweep_paused(&self) -> bool {
436        *self.last_sweep_paused.read()
437    }
438
439    /// How long to wait before the next sweep.
440    ///
441    /// An overdue or never-run sweep is scheduled after `settle` rather than
442    /// after a full interval, so a process restarting more often than its
443    /// interval still compacts. `settle` keeps a boot-time sweep off WAL
444    /// recovery's disk.
445    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    /// Record a completed sweep in memory and on disk.
461    ///
462    /// A failed write must not fail the sweep: the pass did happen, and the
463    /// next boot re-running one costs a redundant pass, not correctness.
464    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    /// List all Parquet files in the storage directory
480    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        // Sort by creation time (oldest first)
520        files.sort_by_key(|f| f.created);
521
522        Ok(files)
523    }
524
525    /// Identify files that should be compacted based on strategy
526    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    /// Select small files for compaction
535    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        // Only compact if we have enough small files
543        if small_files.len() >= self.config.min_files_to_compact {
544            small_files
545        } else {
546            Vec::new()
547        }
548    }
549
550    /// Select old files for time-based compaction
551    fn select_old_files(&self, files: &[FileInfo]) -> Vec<FileInfo> {
552        let now = Utc::now();
553        let age_threshold = chrono::Duration::hours(24); // Files older than 24 hours
554
555        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    /// Check if compaction should run
569    #[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, // Never compacted
578            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    /// Perform compaction across every discovered tenant.
586    ///
587    /// Iterates the tenants under `<storage_dir>/<tenant>/...`, calls
588    /// `compact_tenant` for each, and aggregates the results. Step 4
589    /// of the sustainable data strategy: per-tenant compaction
590    /// instead of global, keyed off the per-tenant directory tree
591    /// Step 1 introduced.
592    ///
593    /// Errors compacting one tenant are logged but don't abort the
594    /// pass — other tenants still get compacted. The aggregate
595    /// result reflects what actually completed.
596    ///
597    /// The sweep stops starting work once `max_pass_seconds` is spent and
598    /// resumes on the next tick. Tenants are visited in a stable order, so a
599    /// sweep that runs out of budget always leaves the same tail — the
600    /// per-pass bound is on time, and progress comes from the files each
601    /// group removes.
602    #[cfg_attr(feature = "hotpath", hotpath::measure)]
603    pub fn compact(&self) -> Result<CompactionResult> {
604        self.compact_until(None)
605    }
606
607    /// Where the next sweep will start, or `None` before the first one.
608    ///
609    /// Diagnostic: a cursor that never moves off one tenant means that
610    /// tenant's backlog is larger than a single pass's budget.
611    pub fn sweep_cursor(&self) -> Option<String> {
612        self.sweep_cursor.read().clone()
613    }
614
615    /// [`Self::compact`] with an explicit deadline in place of the one
616    /// `max_pass_seconds` derives.
617    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            // Still a sweep that happened. Leaving `last_compaction` unset
625            // would have `should_compact` answer yes on every tick, so an
626            // empty store would be swept continuously.
627            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        // The first tenant this sweep did not finish. The next sweep starts
638        // there, so a tenant paused half way is resumed rather than waiting
639        // a full rotation, and a tenant never reached is reached next.
640        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        // Everything finished: start the next sweep where this one did, so a
666        // steady state keeps visiting tenants in one stable order.
667        *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    /// Compact one tenant's event files into snapshot files under that
705    /// tenant's partition.
706    ///
707    /// Per-tenant pipeline:
708    /// 1. List `<storage>/<tenant>/...*.parquet`, keeping an existing
709    ///    `snapshot.*` only while it is still under
710    ///    `small_file_threshold` so partial passes merge upward.
711    /// 2. Apply the configured strategy (size / time / full) to
712    ///    pick candidates.
713    /// 3. Split the candidates into groups bounded by
714    ///    `max_input_bytes_per_snapshot` and
715    ///    `max_input_files_per_snapshot`, and compact each group on its
716    ///    own. One group's events are resident at a time, so a tenant's
717    ///    size sets how many snapshots a pass writes, never how much
718    ///    memory it needs.
719    ///
720    /// Each group is independently crash-safe: its snapshot is renamed
721    /// into place before any of its own inputs is deleted, and a crash
722    /// between groups leaves the earlier groups compacted and the later
723    /// ones untouched.
724    pub fn compact_tenant(&self, tenant_id: &str) -> Result<CompactionResult> {
725        self.compact_tenant_until(tenant_id, None)
726    }
727
728    /// `compact_tenant` with a sweep deadline. Checked between groups, so the
729    /// tenant's remaining groups are left for the next tick rather than
730    /// abandoned mid-group — a group either publishes its snapshot and
731    /// deletes its inputs or does neither.
732    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    /// `compact_tenant_until`, also reporting whether every group ran.
742    ///
743    /// The sweep needs that answer to place its cursor: a tenant paused on
744    /// the budget has to be the next sweep's first call.
745    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                // A snapshot that already reached the threshold is finished
846                // output: re-reading it would rewrite the whole tenant every
847                // pass for no reduction in file count.
848                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        // Oldest first, so each group covers a contiguous time range and the
881        // snapshots a pass writes do not interleave.
882        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        // A group that fails does not stop the others. One unreadable file
896        // otherwise blocks its whole tenant from ever compacting, and the
897        // groups that have nothing wrong with them are what reduce the file
898        // count. The failure is still returned, so a caller cannot read a
899        // partial sweep as a clean one.
900        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    /// Split candidates into groups no larger than the configured input
940    /// bounds. A single file over the byte bound is its own group — refusing
941    /// it would leave it uncompactable forever.
942    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    /// Compact one bounded group of this tenant's files into a single
965    /// snapshot. Only this group's events are resident.
966    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        // Each file is read individually rather than through
986        // load_events_for_tenant so only the candidate set is picked up —
987        // concurrent writes that produced new files since enumeration are
988        // deferred to the next interval (AC #6).
989        let mut events = Vec::new();
990        for fi in candidates {
991            // Recover tenant from path so loaded events keep
992            // their identity (Step 1's path-as-tenant-source).
993            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            // Every selected input must be readable before any retention,
1005            // archive, snapshot or deletion step can run. Skipping a failed
1006            // input would later delete it as if its contents were preserved.
1007            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        // Apply retention (Step 5). Drop events older than the
1027        // tenant's TTL before they get rewritten into the
1028        // snapshot. The originals get deleted at the end of the
1029        // happy path either way, so dropped events go away with
1030        // the same crash-safe guarantee as the rest of the
1031        // compaction pipeline (snapshot rename completes BEFORE
1032        // any original is deleted; AC #6).
1033        //
1034        // Cold-tier (sustainability): when an `archive` target is
1035        // configured, dropped events are written to it BEFORE this
1036        // function deletes any original file. A failed archive
1037        // returns `Err`, originals stay on disk, and the next
1038        // compaction pass retries — same crash-safety contract as
1039        // the snapshot path. Without an archive, retention behaves
1040        // exactly as before (delete outright).
1041        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            // Partition: drained = events past TTL, kept = events to keep.
1047            // Using drain_filter would be simpler but it's unstable;
1048            // partition + reassign keeps events: Vec<Event> with the
1049            // kept slice in original order.
1050            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        // Edge case: every event aged out. Skip the snapshot
1092        // write and just delete originals — the data is gone by
1093        // design. Delete-without-snapshot is safe here because
1094        // every event we'd have written to the snapshot was
1095        // already past its TTL, and the input files live under
1096        // the tenant's partition with nothing else relying on
1097        // them.
1098        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        // Filename: snapshot.<tenant>.<from>-<to>.<nanos> with
1127        // filesystem-safe ISO-basic timestamps (no colons). The nanosecond
1128        // discriminator keeps two snapshots covering the same range from
1129        // sharing a path: a snapshot can itself be an input, so a colliding
1130        // stem would have the write land on a file the delete below removes.
1131        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        // Delete inputs AFTER the snapshot is durably renamed. AC #6: a
1150        // snapshot-write failure short-circuits via the `?` above, so inputs
1151        // stay on disk and events remain queryable until the next pass.
1152        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    /// Reorder `tenants` so the sweep begins at the cursor, wrapping around.
1186    ///
1187    /// The cursor names the tenant to start at, not the one last finished: a
1188    /// tenant paused on the time budget has to be the next sweep's first
1189    /// call, or its remaining groups wait a full rotation. A cursor naming a
1190    /// tenant that no longer exists falls back to the start.
1191    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    /// Discover tenant ids by scanning `<storage_dir>/<X>/` for
1205    /// directories. The migration tool's flat-layout files at the
1206    /// root are not picked up — Step 1 #3's migration moves them
1207    /// under `default/`.
1208    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                // Skip the system metadata subtree (Core's own
1221                // event-sourced repos) and any hidden folders.
1222                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    /// Get compaction statistics
1233    pub fn stats(&self) -> CompactionStats {
1234        (*self.stats.read()).clone()
1235    }
1236
1237    /// Get configuration
1238    pub fn config(&self) -> &CompactionConfig {
1239        &self.config
1240    }
1241
1242    /// Trigger manual compaction
1243    #[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/// Result of a compaction operation
1306#[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
1315/// Format a UTC timestamp as a filename-safe ISO-8601 basic-form
1316/// string: `2026-04-27T134567Z` — no colons, no fractional second.
1317/// Used for the `<from>-<to>` portion of snapshot filenames so
1318/// they're portable across filesystems. `pub(super)` so the
1319/// cold-tier archive can reuse the same naming convention.
1320pub(super) fn format_iso_basic(t: DateTime<Utc>) -> String {
1321    t.format("%Y-%m-%dT%H%M%SZ").to_string()
1322}
1323
1324/// Background compaction task
1325pub struct CompactionTask {
1326    manager: Arc<CompactionManager>,
1327    interval: Duration,
1328}
1329
1330impl CompactionTask {
1331    /// Create a new background compaction task
1332    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    /// Run the compaction task in a loop
1340    #[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        // Should compact on first check (never compacted)
1480        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, // 1 MB
1488            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, // 500 KB
1498                created: Utc::now(),
1499            },
1500            FileInfo {
1501                path: PathBuf::from("small2.parquet"),
1502                size: 600_000, // 600 KB
1503                created: Utc::now(),
1504            },
1505            FileInfo {
1506                path: PathBuf::from("large.parquet"),
1507                size: 10_000_000, // 10 MB
1508                created: Utc::now(),
1509            },
1510        ];
1511
1512        let selected = manager.select_files_for_compaction(&files);
1513        assert_eq!(selected.len(), 2); // Only the 2 small files
1514    }
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, // Need 3 files
1597            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); // Not enough small files
1617    }
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); // Only the 2 old files
1650    }
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); // Not enough old files
1678    }
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); // All files selected
1704    }
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        // Task created successfully
1768    }
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        // Create non-parquet files
1787        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()); // No parquet files
1792    }
1793
1794    // -----------------------------------------------------------------
1795    // Per-tenant compaction tests (Step 4, commit #2).
1796    // -----------------------------------------------------------------
1797
1798    fn ingest_and_flush_per_call(storage_dir: &std::path::Path, tenant: &str, count: usize) {
1799        // Each ingested batch produces one parquet file when its
1800        // ParquetStorage is dropped, giving us multiple raw files
1801        // per tenant for the strategy filter to pick up.
1802        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        // Seed 4 raw files for alice.
1829        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        // After: zero raw files, exactly one snapshot.* file under
1844        // alice's subtree.
1845        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        // No tmp files left behind.
1865        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        // Loaded events round-trip correctly.
1873        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        // Seed alice with 4 raw files, run compaction → 1 snapshot.
1883        // Run compaction AGAIN: the snapshot is excluded from the
1884        // candidate set, no qualifying raw files remain, the second
1885        // pass is a no-op.
1886        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        // Still exactly one file on disk for alice.
1903        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        // 1 file < min_files_to_compact (default 3) → nothing happens.
1911        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        // Raw file untouched.
1919        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        // Two tenants each with enough raw files. compact() must
1936        // produce one snapshot per tenant.
1937        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        // Bead's integration test: ingest 100 events spanning 60
1965        // days, run compaction with 30-day TTL, only the last
1966        // 30 days remain queryable.
1967        let temp_dir = TempDir::new().unwrap();
1968
1969        // Seed alice with 100 events, timestamps spread across
1970        // 60 days. We can't backdate via ingest (timestamp = now()
1971        // in domain), so write parquet directly via flush of
1972        // back-dated events.
1973        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
1974        let now = Utc::now();
1975        for i in 0..100 {
1976            // Day 0 = 60 days ago; day 99 ≈ now. Spreads evenly.
1977            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            // Every 10 events get a fresh storage to produce a
1991            // separate file (so compaction has multiple files
1992            // to merge).
1993            if i % 10 == 9 {
1994                storage.flush().unwrap();
1995            }
1996        }
1997        storage.flush().unwrap();
1998
1999        // 30-day TTL for alice via per-tenant override.
2000        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        // Re-load to confirm the dropped events are gone.
2020        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        // Every loaded event must be within the 30-day window
2025        // (with a generous fudge for test-clock drift).
2026        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        // alice has no override → falls through to default_ttl
2040        // which is None. All events kept regardless of age.
2041        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        // Default RetentionConfig: alice has no entry, default_ttl = None.
2064        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        // The system tenant's 30-day TTL is the bead's headline
2078        // requirement. Default config without any overrides
2079        // should already enforce it.
2080        let cfg = RetentionConfig::default();
2081        let ttl = cfg.ttl_for("system").unwrap();
2082        assert_eq!(ttl.as_secs(), 30 * 24 * 3600);
2083        // No override for arbitrary tenants → keep forever.
2084        assert!(cfg.ttl_for("acme").is_none());
2085    }
2086
2087    #[test]
2088    fn test_retention_drops_all_events_deletes_originals_without_snapshot() {
2089        // Edge case: every event is past the TTL. We delete the
2090        // raw files and emit no snapshot — there's nothing to
2091        // write. Tenant ends with zero files on disk.
2092        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); // originals were deleted
2126
2127        // Tenant subtree has zero parquet files now.
2128        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        // AC #7-#8: simulate "crash mid-snapshot" by manually
2136        // dropping a tmp file in the partition, then asserting
2137        // a fresh ParquetStorage::new boot cleans it up and the
2138        // raw files (which would still be present in a real
2139        // mid-rename crash) remain queryable.
2140        let temp_dir = TempDir::new().unwrap();
2141
2142        // Seed alice with raw files.
2143        ingest_and_flush_per_call(temp_dir.path(), "alice", 3);
2144
2145        // Locate alice's partition dir.
2146        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        // Simulate the crash state: write a partial .tmp file as
2151        // if write_atomic_parquet had crashed mid-rename.
2152        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        // Reboot — ParquetStorage::new triggers cleanup_partial_writes.
2157        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        // Raw files survived; events queryable.
2164        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        // Cold-tier integration: when retention drops events AND an
2171        // archive target is configured, the dropped events end up
2172        // in the archive root before originals are removed. This is
2173        // the load-bearing property — without archive-before-delete
2174        // the cold tier would silently lose data on retention runs.
2175        use crate::infrastructure::persistence::cold_tier::LocalFsArchive;
2176
2177        let live_dir = TempDir::new().unwrap();
2178        let archive_dir = TempDir::new().unwrap();
2179
2180        // Seed alice with 50 events spread across 60 days.
2181        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        // 30-day TTL + cold-tier archive.
2204        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        // Live storage: only events within the 30-day window.
2227        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        // Archive: contains the dropped events. Walk the archive root
2234        // and load any archive.alice.* file we find.
2235        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        // Sum events across archive files; total live + archived
2256        // must equal the original 50 (no events lost in the pipeline).
2257        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        // Crash-safety contract: a failing archive must NOT delete
2271        // originals. We use a custom ArchiveTarget that always
2272        // returns Err to simulate an outage.
2273        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        // Count files before. The compaction pipeline should leave
2296        // them all on disk after the failed archive.
2297        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        // Originals still on disk — every event still queryable.
2347        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        // If retention drops zero events (e.g. tenant has no TTL),
2365        // the archive target must NOT be called. We assert by using
2366        // an archive that panics on call.
2367        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        // Default retention → alice has no TTL → no events dropped.
2404        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        // Ensure the tenant scan doesn't pick up __system or hidden
2419        // directories — they're internal, not real tenants.
2420        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}