Skip to main content

allsource_core/infrastructure/persistence/
storage.rs

1#[path = "storage_feed.rs"]
2mod feed;
3#[path = "storage_retained_entity.rs"]
4mod retained_entity;
5
6use super::{
7    archive_budget::{ArchiveReadBudget, ArchiveReadLimits},
8    archive_output::{
9        ArchiveOutput, PublishedPart, pending_marker, pending_part, recover_pending_outputs,
10    },
11    event_codec::{
12        self, ENTITY_ID_COLUMN, VALID_FROM_COLUMN, VALID_TO_COLUMN, VERSION_COLUMN, event_schema,
13    },
14    version_manifest::{ResolvedVersion, VersionManifest},
15};
16use crate::{
17    domain::entities::Event,
18    error::{AllSourceError, Result},
19    infrastructure::memory::ledger::{Owner, Tally},
20};
21use arrow::{
22    array::{Array, TimestampMicrosecondArray},
23    datatypes::Schema,
24    record_batch::RecordBatch,
25};
26use std::{
27    collections::HashMap,
28    fs::{self, File},
29    path::{Path, PathBuf},
30    sync::{
31        Arc, Mutex,
32        atomic::{AtomicU64, Ordering},
33    },
34    time::{Duration, Instant},
35};
36
37/// Bytes of JSON text a decoded batch holds, read from the Arrow string
38/// buffers rather than re-serialising each event.
39///
40/// This is what the archive budget charges. Parquet's declared uncompressed
41/// size is a different quantity, and the one that does not run out.
42pub(super) fn decoded_text_bytes(batch: &RecordBatch) -> u64 {
43    ["payload", "metadata"]
44        .iter()
45        .filter_map(|name| {
46            let column = batch.schema().index_of(name).ok()?;
47            batch
48                .column(column)
49                .as_any()
50                .downcast_ref::<arrow::array::StringArray>()
51        })
52        .map(|values| values.value_data().len() as u64)
53        .sum()
54}
55
56/// `None` when the file predates the column.
57fn optional_timestamp_column<'a>(
58    batch: &'a RecordBatch,
59    name: &str,
60) -> Result<Option<&'a TimestampMicrosecondArray>> {
61    let Ok(index) = batch.schema().index_of(name) else {
62        return Ok(None);
63    };
64    batch
65        .column(index)
66        .as_any()
67        .downcast_ref::<TimestampMicrosecondArray>()
68        .map(Some)
69        .ok_or_else(|| AllSourceError::StorageError(format!("Invalid {name} column")))
70}
71
72fn valid_time_at(
73    column: Option<&TimestampMicrosecondArray>,
74    row: usize,
75) -> Result<Option<chrono::DateTime<chrono::Utc>>> {
76    match column {
77        Some(values) if values.is_valid(row) => {
78            chrono::DateTime::from_timestamp_micros(values.value(row))
79                .map(Some)
80                .ok_or_else(|| AllSourceError::StorageError("Invalid valid time".to_string()))
81        }
82        _ => Ok(None),
83    }
84}
85
86/// Default batch size for Parquet writes (10,000 events as per US-023)
87pub const DEFAULT_BATCH_SIZE: usize = 10_000;
88
89/// Default flush timeout in milliseconds
90pub const DEFAULT_FLUSH_TIMEOUT_MS: u64 = 5_000;
91
92/// Names a flushed archive file's stem from its tenant and flush time. The
93/// archive output still appends its own unique suffix, so the stem only has to
94/// order files; the heap replay supplies one so flush order is reproducible.
95#[derive(Clone)]
96pub struct FileNamer(Arc<dyn Fn(&str, chrono::DateTime<chrono::Utc>) -> String + Send + Sync>);
97
98impl FileNamer {
99    pub fn new(
100        name: impl Fn(&str, chrono::DateTime<chrono::Utc>) -> String + Send + Sync + 'static,
101    ) -> Self {
102        Self(Arc::new(name))
103    }
104}
105
106impl std::fmt::Debug for FileNamer {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        f.write_str("FileNamer")
109    }
110}
111
112/// Configuration for ParquetStorage batch processing
113#[derive(Debug, Clone)]
114pub struct ParquetStorageConfig {
115    /// Batch size before automatic flush (default: 10,000)
116    pub batch_size: usize,
117    /// Timeout before flushing partial batch (default: 5 seconds)
118    pub flush_timeout: Duration,
119    /// Compression codec for Parquet files
120    pub compression: parquet::basic::Compression,
121    /// Flush file stem; `None` names files `events-<time>-<uuid>`.
122    pub file_namer: Option<FileNamer>,
123}
124
125impl Default for ParquetStorageConfig {
126    fn default() -> Self {
127        Self {
128            batch_size: DEFAULT_BATCH_SIZE,
129            flush_timeout: Duration::from_millis(DEFAULT_FLUSH_TIMEOUT_MS),
130            compression: parquet::basic::Compression::SNAPPY,
131            file_namer: None,
132        }
133    }
134}
135
136impl ParquetStorageConfig {
137    /// High-throughput configuration optimized for large batch writes
138    pub fn high_throughput() -> Self {
139        Self {
140            batch_size: 50_000,
141            flush_timeout: Duration::from_secs(10),
142            compression: parquet::basic::Compression::SNAPPY,
143            file_namer: None,
144        }
145    }
146
147    /// Low-latency configuration for smaller, more frequent writes
148    pub fn low_latency() -> Self {
149        Self {
150            batch_size: 1_000,
151            flush_timeout: Duration::from_secs(1),
152            compression: parquet::basic::Compression::SNAPPY,
153            file_namer: None,
154        }
155    }
156}
157
158/// Statistics for batch write operations
159#[derive(Debug, Clone, Default)]
160pub struct BatchWriteStats {
161    /// Total batches written
162    pub batches_written: u64,
163    /// Total events written
164    pub events_written: u64,
165    /// Total bytes written
166    pub bytes_written: u64,
167    /// Average batch size
168    pub avg_batch_size: f64,
169    /// Events per second (throughput)
170    pub events_per_sec: f64,
171    /// Total write time in nanoseconds
172    pub total_write_time_ns: u64,
173    /// Number of timeout-triggered flushes
174    pub timeout_flushes: u64,
175    /// Number of size-triggered flushes
176    pub size_flushes: u64,
177}
178
179/// Result of a batch write operation
180#[derive(Debug, Clone)]
181pub struct BatchWriteResult {
182    /// Number of events written
183    pub events_written: usize,
184    /// Number of batches flushed to disk
185    pub batches_flushed: usize,
186    /// Total duration of the write operation
187    pub duration: Duration,
188    /// Write throughput in events per second
189    pub events_per_sec: f64,
190}
191
192/// Parquet-based persistent storage for events with batch processing
193///
194/// Features:
195/// - Configurable batch size (default: 10,000 events per US-023)
196/// - Timeout-based flushing for partial batches
197/// - Thread-safe batch accumulation
198/// - SNAPPY compression for efficient storage
199/// - Automatic flush on shutdown via Drop
200pub struct ParquetStorage {
201    /// Base directory for storing parquet files
202    storage_dir: PathBuf,
203
204    /// Buffered events keyed by tenant_id. Each tenant accumulates its own
205    /// batch and flushes independently into its partition under
206    /// `storage_dir/<tenant_id>/<yyyy-mm>/`. Single outer mutex protects the
207    /// whole map: lookup is O(1), tenant cardinality is low (single digits
208    /// today; bounded by Step 3's cache budget later), so contention is
209    /// fine. We keep the mutex held only for the push, not for disk I/O —
210    /// flush takes ownership of a tenant's batch via remove() and writes
211    /// after the lock is released.
212    current_batches: Mutex<HashMap<String, Vec<Event>>>,
213    /// Heap of the batched events until their flush succeeds (`storage.pending`).
214    pending: Tally,
215
216    /// Configuration
217    config: ParquetStorageConfig,
218
219    /// Schema for Arrow/Parquet
220    schema: Arc<Schema>,
221
222    /// Last flush timestamp for timeout tracking
223    last_flush_time: Mutex<Instant>,
224
225    /// Statistics tracking
226    batches_written: AtomicU64,
227    events_written: AtomicU64,
228    bytes_written: AtomicU64,
229    total_write_time_ns: AtomicU64,
230    timeout_flushes: AtomicU64,
231    size_flushes: AtomicU64,
232}
233
234impl ParquetStorage {
235    /// Create a new ParquetStorage with default configuration (10,000 event batches)
236    pub fn new(storage_dir: impl AsRef<Path>) -> Result<Self> {
237        Self::with_config(storage_dir, ParquetStorageConfig::default())
238    }
239
240    /// Create a new ParquetStorage with custom configuration
241    pub fn with_config(
242        storage_dir: impl AsRef<Path>,
243        config: ParquetStorageConfig,
244    ) -> Result<Self> {
245        Self::open(storage_dir, config, true)
246    }
247
248    pub(crate) fn open_existing(storage_dir: impl AsRef<Path>) -> Result<Self> {
249        Self::open(storage_dir, ParquetStorageConfig::default(), false)
250    }
251
252    fn open(
253        storage_dir: impl AsRef<Path>,
254        config: ParquetStorageConfig,
255        recover: bool,
256    ) -> Result<Self> {
257        let storage_dir = storage_dir.as_ref().to_path_buf();
258
259        if recover {
260            fs::create_dir_all(&storage_dir).map_err(|e| {
261                AllSourceError::StorageError(format!("Failed to create storage directory: {e}"))
262            })?;
263        } else if !storage_dir.is_dir() {
264            return Err(AllSourceError::StorageError(
265                "Existing storage directory is unavailable".into(),
266            ));
267        }
268
269        let schema = event_schema();
270
271        let storage = Self {
272            storage_dir,
273            current_batches: Mutex::new(HashMap::new()),
274            pending: Tally::new(Owner::StoragePending),
275            config,
276            schema,
277            last_flush_time: Mutex::new(Instant::now()),
278            batches_written: AtomicU64::new(0),
279            events_written: AtomicU64::new(0),
280            bytes_written: AtomicU64::new(0),
281            total_write_time_ns: AtomicU64::new(0),
282            timeout_flushes: AtomicU64::new(0),
283            size_flushes: AtomicU64::new(0),
284        };
285
286        // Boot-time crash recovery: heal *.parquet.tmp files from
287        // crashed atomic writes (snapshot/compaction or, post-#166-fix,
288        // checkpoint flushes) and quarantine any 0-byte *.parquet files
289        // left over from pre-fix checkpoint crashes (issue #166).
290        if recover {
291            match storage.cleanup_partial_writes() {
292                Ok(0) => {}
293                Ok(n) => tracing::warn!(
294                    "cleanup_partial_writes acted on {n} crash-detritus file(s) on boot — \
295                 see preceding logs for per-file detail"
296                ),
297                Err(e) => tracing::error!("cleanup_partial_writes failed on boot: {e}"),
298            }
299        }
300
301        Ok(storage)
302    }
303
304    /// Create storage with legacy batch size (1000) for backward compatibility
305    #[deprecated(note = "Use new() or with_config() instead - default batch size is now 10,000")]
306    pub fn with_legacy_batch_size(storage_dir: impl AsRef<Path>) -> Result<Self> {
307        Self::with_config(
308            storage_dir,
309            ParquetStorageConfig {
310                batch_size: 1000,
311                ..Default::default()
312            },
313        )
314    }
315
316    /// Add an event to the current batch
317    ///
318    /// Events are routed to a per-tenant batch keyed by `event.tenant_id_str()`.
319    /// A tenant's batch is buffered until any of:
320    /// - That tenant's batch hits the configured `batch_size` (default 10,000)
321    ///   — flushes only that tenant, not the whole world
322    /// - The flush timeout elapses — flushes every tenant with pending data
323    /// - `flush()` is called explicitly
324    /// - The process shuts down
325    #[cfg_attr(feature = "hotpath", hotpath::measure)]
326    pub fn append_event(&self, event: Event) -> Result<()> {
327        let tenant = event.tenant_id_str().to_string();
328        self.pending.add(event.resident_bytes());
329        let should_flush_tenant = {
330            let mut batches = self.current_batches.lock().unwrap();
331            let entry = batches.entry(tenant.clone()).or_default();
332            entry.push(event);
333            entry.len() >= self.config.batch_size
334        };
335
336        if should_flush_tenant {
337            self.size_flushes.fetch_add(1, Ordering::Relaxed);
338            self.flush_tenant(&tenant)?;
339        }
340
341        Ok(())
342    }
343
344    /// Add multiple events to the batch (optimized batch insertion)
345    ///
346    /// Preferred entry point for high-throughput ingestion. Events are
347    /// grouped by tenant under a single mutex acquisition and any tenant
348    /// that crosses `batch_size` is flushed on the spot.
349    #[cfg_attr(feature = "hotpath", hotpath::measure)]
350    pub fn batch_write(&self, events: Vec<Event>) -> Result<BatchWriteResult> {
351        let start = Instant::now();
352        let event_count = events.len();
353
354        // Pre-group by tenant to keep the lock window short — one acquire,
355        // one extend per tenant, decide which tenants are over threshold.
356        let mut grouped: HashMap<String, Vec<Event>> = HashMap::new();
357        for event in events {
358            self.pending.add(event.resident_bytes());
359            grouped
360                .entry(event.tenant_id_str().to_string())
361                .or_default()
362                .push(event);
363        }
364
365        let mut tenants_to_flush: Vec<String> = Vec::new();
366        {
367            let mut batches = self.current_batches.lock().unwrap();
368            for (tenant, mut new_events) in grouped {
369                let entry = batches.entry(tenant.clone()).or_default();
370                entry.append(&mut new_events);
371                if entry.len() >= self.config.batch_size {
372                    tenants_to_flush.push(tenant);
373                }
374            }
375        }
376
377        let mut batches_flushed = 0;
378        for tenant in tenants_to_flush {
379            self.size_flushes.fetch_add(1, Ordering::Relaxed);
380            self.flush_tenant(&tenant)?;
381            batches_flushed += 1;
382        }
383
384        let duration = start.elapsed();
385
386        Ok(BatchWriteResult {
387            events_written: event_count,
388            batches_flushed,
389            duration,
390            events_per_sec: event_count as f64 / duration.as_secs_f64(),
391        })
392    }
393
394    /// Check if a timeout-based flush is needed and perform it
395    ///
396    /// Call this periodically (e.g., from a background task) to ensure
397    /// partial batches are flushed within the configured timeout. When
398    /// triggered, every tenant with pending events flushes — the timer is
399    /// global, not per-tenant, so a slow-trickle tenant doesn't get
400    /// stranded waiting for its own batch to fill.
401    #[cfg_attr(feature = "hotpath", hotpath::measure)]
402    pub fn check_timeout_flush(&self) -> Result<bool> {
403        let should_flush = {
404            let last_flush = self.last_flush_time.lock().unwrap();
405            let batches = self.current_batches.lock().unwrap();
406            let any_pending = batches.values().any(|v| !v.is_empty());
407            any_pending && last_flush.elapsed() >= self.config.flush_timeout
408        };
409
410        if should_flush {
411            self.timeout_flushes.fetch_add(1, Ordering::Relaxed);
412            self.flush()?;
413            Ok(true)
414        } else {
415            Ok(false)
416        }
417    }
418
419    /// Flush every tenant's pending batch to its partition.
420    ///
421    /// Thread-safe: callable from any thread. A snapshot of which tenants
422    /// have pending data is taken under a short lock; each tenant is then
423    /// flushed individually with its own lock cycle, so disk I/O for one
424    /// tenant doesn't block writes against another.
425    #[cfg_attr(feature = "hotpath", hotpath::measure)]
426    pub fn flush(&self) -> Result<()> {
427        let tenants: Vec<String> = {
428            let batches = self.current_batches.lock().unwrap();
429            batches
430                .iter()
431                .filter(|(_, v)| !v.is_empty())
432                .map(|(k, _)| k.clone())
433                .collect()
434        };
435        if tenants.is_empty() {
436            return Ok(());
437        }
438        for tenant in tenants {
439            self.flush_tenant(&tenant)?;
440        }
441        Ok(())
442    }
443
444    /// Call while holding exclusive access to the storage owner: a shared
445    /// access check alone cannot exclude a batch already drained by a flush.
446    pub(crate) fn has_pending_tenant_events(&self, tenant_id: &str) -> bool {
447        self.current_batches
448            .lock()
449            .unwrap()
450            .get(tenant_id)
451            .is_some_and(|events| !events.is_empty())
452    }
453
454    /// Flush a single tenant's pending events into its partition file.
455    ///
456    /// File path: `storage_dir/<sanitized_tenant_id>/<yyyy-mm>/events-<ts>-<uuid>.parquet`.
457    /// `<yyyy-mm>` is taken from the wall-clock at flush time (matching the
458    /// pre-tenant filename's timestamp semantics) rather than from
459    /// individual event timestamps — keeps each flush to a single output
460    /// file even when buffered events span months.
461    ///
462    /// The file is written atomically via `write_record_batch_atomic`:
463    /// crash mid-write leaves a `.parquet.tmp` file (cleaned on next boot)
464    /// rather than a 0-byte `.parquet` file with the final name. Issue
465    /// #166 — pre-fix, a SIGKILL inside this function bricked subsequent
466    /// loads because `load_all_events` aborted on the first unreadable
467    /// file.
468    fn flush_tenant(&self, tenant_id: &str) -> Result<()> {
469        let events_to_write = {
470            let mut batches = self.current_batches.lock().unwrap();
471            match batches.get_mut(tenant_id) {
472                Some(v) if !v.is_empty() => std::mem::take(v),
473                _ => return Ok(()),
474            }
475        };
476
477        let batch_count = events_to_write.len();
478        let start = Instant::now();
479
480        let written = self.write_tenant_events(tenant_id, &events_to_write);
481        let parts = match written {
482            Ok(written) => written,
483            Err(e) => {
484                // The WAL may be retired by the next successful checkpoint, so
485                // dropping these here would make the failure permanent (#287).
486                let mut batches = self.current_batches.lock().unwrap();
487                let pending = batches.entry(tenant_id.to_string()).or_default();
488                let arrived_during_write = std::mem::replace(pending, events_to_write);
489                pending.extend(arrived_during_write);
490                return Err(e);
491            }
492        };
493
494        let duration = start.elapsed();
495        self.pending
496            .sub(events_to_write.iter().map(Event::resident_bytes).sum());
497
498        // Only after the events are durable. A manifest naming a file whose
499        // write failed would authorise a version nothing on disk supports;
500        // one that misses a written file is healed by the next resolve, which
501        // folds any file the manifest does not name.
502        let mut offset = 0;
503        for part in &parts {
504            let rows = usize::try_from(part.metadata.file_metadata().num_rows())
505                .map_err(|_| AllSourceError::StorageError("Invalid archive output rows".into()))?;
506            if let Err(error) = self.record_flushed_versions(
507                tenant_id,
508                &part.path,
509                &events_to_write[offset..offset + rows],
510            ) {
511                tracing::warn!(tenant_id, %error, "could not update tenant version manifest");
512            }
513            offset += rows;
514        }
515
516        self.batches_written.fetch_add(1, Ordering::Relaxed);
517        self.events_written
518            .fetch_add(batch_count as u64, Ordering::Relaxed);
519        let bytes = parts
520            .iter()
521            .flat_map(|part| part.metadata.row_groups())
522            .map(|group| group.total_byte_size() as u64)
523            .sum();
524        self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
525        self.total_write_time_ns
526            .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed);
527
528        {
529            let mut last_flush = self.last_flush_time.lock().unwrap();
530            *last_flush = Instant::now();
531        }
532
533        tracing::info!(
534            "Wrote {} events for tenant={} to {} files in {:?}",
535            batch_count,
536            tenant_id,
537            parts.len(),
538            duration
539        );
540
541        Ok(())
542    }
543
544    fn write_tenant_events(&self, tenant_id: &str, events: &[Event]) -> Result<Vec<PublishedPart>> {
545        let record_batch = self.events_to_record_batch(events)?;
546
547        let now = chrono::Utc::now();
548        let partition_dir = partition_path_for_tenant(&self.storage_dir, tenant_id, now)?;
549        fs::create_dir_all(&partition_dir).map_err(|e| {
550            AllSourceError::StorageError(format!(
551                "Failed to create tenant partition {}: {e}",
552                partition_dir.display()
553            ))
554        })?;
555        let file_stem = match &self.config.file_namer {
556            Some(FileNamer(name)) => name(tenant_id, now),
557            None => format!(
558                "events-{}-{}",
559                now.format("%Y%m%d-%H%M%S%3f"),
560                uuid::Uuid::new_v4().as_simple()
561            ),
562        };
563
564        tracing::info!(
565            "Flushing {} events for tenant={} to {}/{}.parquet",
566            events.len(),
567            tenant_id,
568            partition_dir.display(),
569            file_stem
570        );
571
572        let mut output = ArchiveOutput::new(
573            &partition_dir,
574            &file_stem,
575            self.config.compression,
576            ArchiveReadLimits::default().max_file_bytes,
577            true,
578        )?;
579        output.stage(&record_batch)?;
580        output.publish()
581    }
582
583    /// Write a single record batch atomically to
584    /// `<partition_dir>/<file_stem>.parquet`, returning the final path
585    /// and the parquet writer's metadata (used for byte-size metrics by
586    /// the checkpoint flush path).
587    ///
588    /// Crash-safety contract — same four steps as `write_atomic_parquet`:
589    /// 1. Write to `<final_path>.tmp` first.
590    /// 2. fsync the .tmp file so the data is durably on disk.
591    /// 3. Rename `.tmp` → final name (atomic POSIX rename).
592    /// 4. fsync the parent directory so the rename survives crash.
593    ///
594    /// Caller is responsible for choosing `partition_dir` (and creating
595    /// it). On any failure mid-way, the `.tmp` file gets cleaned up by
596    /// `cleanup_partial_writes` on next boot. The final file appears
597    /// atomically — readers either see the old state (no file) or the
598    /// complete new file, never a half-written one.
599    fn write_record_batch_atomic(
600        &self,
601        partition_dir: &Path,
602        file_stem: &str,
603        record_batch: &RecordBatch,
604    ) -> Result<(PathBuf, parquet::file::metadata::ParquetMetaData)> {
605        let mut output = ArchiveOutput::new(
606            partition_dir,
607            file_stem,
608            self.config.compression,
609            ArchiveReadLimits::default().max_file_bytes,
610            false,
611        )?;
612        output.stage(record_batch)?;
613        let part = output
614            .publish()?
615            .pop()
616            .ok_or_else(|| AllSourceError::StorageError("Archive output missing".into()))?;
617        Ok((part.path, part.metadata))
618    }
619
620    /// Atomically write `events` to a Parquet file under the tenant's
621    /// partition. Step 4 of the sustainable data strategy uses this to
622    /// emit per-tenant snapshot/compaction files (`snapshot.<tenant>.<from>-<to>`)
623    /// without risking partial files on crash.
624    ///
625    /// Crash-safety contract:
626    /// 1. Write to `<final_path>.tmp` first.
627    /// 2. fsync the .tmp file so the data is durably on disk.
628    /// 3. Rename `.tmp` → final name (atomic POSIX rename).
629    /// 4. fsync the parent directory so the rename is durable.
630    ///
631    /// On any failure mid-way, the .tmp file gets cleaned up by
632    /// `cleanup_partial_writes` on next boot. The final file appears
633    /// atomically — readers either see the old state (no file) or
634    /// the complete new file, never a half-written one.
635    ///
636    /// `file_stem` is the filename without extension or partition path
637    /// — caller-controlled so the snapshot naming convention
638    /// (`snapshot.<tenant>.<from>-<to>`) lives in the compaction layer,
639    /// not here. The `.parquet` extension is appended automatically.
640    ///
641    /// Returns the final (post-rename) path so the caller can
642    /// confirm the file landed where expected.
643    pub fn write_atomic_parquet(
644        &self,
645        tenant_id: &str,
646        file_stem: &str,
647        events: &[Event],
648    ) -> Result<PathBuf> {
649        if events.is_empty() {
650            return Err(AllSourceError::StorageError(
651                "write_atomic_parquet called with empty event slice".to_string(),
652            ));
653        }
654        // Anchor partition by the earliest event's month — keeps the
655        // file in the same yyyy-mm bucket as the data it represents.
656        // Callers that span multiple months can use the earliest
657        // event's month and trust the recursive walker to find it.
658        let anchor_ts = events
659            .iter()
660            .map(|e| e.timestamp)
661            .min()
662            .unwrap_or_else(chrono::Utc::now);
663        let partition_dir = partition_path_for_tenant(&self.storage_dir, tenant_id, anchor_ts)?;
664        fs::create_dir_all(&partition_dir).map_err(|e| {
665            AllSourceError::StorageError(format!(
666                "Failed to create tenant partition {}: {e}",
667                partition_dir.display()
668            ))
669        })?;
670
671        let record_batch = self.events_to_record_batch(events)?;
672        let (final_path, _meta) =
673            self.write_record_batch_atomic(&partition_dir, file_stem, &record_batch)?;
674
675        tracing::info!(
676            tenant_id = tenant_id,
677            file = %final_path.display(),
678            event_count = events.len(),
679            "wrote atomic snapshot file"
680        );
681
682        Ok(final_path)
683    }
684
685    pub(crate) fn write_atomic_parquet_parts(
686        &self,
687        tenant_id: &str,
688        file_stem: &str,
689        events: &[Event],
690    ) -> Result<Vec<PathBuf>> {
691        if events.is_empty() {
692            return Err(AllSourceError::StorageError(
693                "Cannot archive empty events".into(),
694            ));
695        }
696        let anchor = events
697            .iter()
698            .map(|event| event.timestamp)
699            .min()
700            .ok_or_else(|| AllSourceError::StorageError("Cannot archive empty events".into()))?;
701        let directory = partition_path_for_tenant(&self.storage_dir, tenant_id, anchor)?;
702        fs::create_dir_all(&directory).map_err(|error| {
703            AllSourceError::StorageError(format!("Failed to create archive partition: {error}"))
704        })?;
705        let batch = self.events_to_record_batch(events)?;
706        let mut output = ArchiveOutput::new(
707            &directory,
708            file_stem,
709            self.config.compression,
710            ArchiveReadLimits::default().max_file_bytes,
711            true,
712        )?;
713        output.stage(&batch)?;
714        Ok(output
715            .publish()?
716            .into_iter()
717            .map(|part| part.path)
718            .collect())
719    }
720
721    /// Sweep the storage tree for crash detritus and heal it on boot.
722    /// Called on boot from `ParquetStorage::new` so every cold start
723    /// starts clean. Two kinds of leftovers are handled:
724    ///
725    /// 1. **`*.parquet.tmp` files** — a snapshot or flush write that
726    ///    crashed between fsync and rename. Safe to delete: the data is
727    ///    either still in the WAL (for checkpoint flushes) or in the
728    ///    constituent raw files (for snapshot/compaction, which only
729    ///    deletes the inputs AFTER the rename succeeds). Either way, the
730    ///    failed write will be retried.
731    ///
732    /// 2. **0-byte `*.parquet` files** — issue #166. Pre-fix releases
733    ///    (≤ 0.20.0 for the checkpoint path) wrote directly to the
734    ///    final filename, so SIGKILL between `File::create` and the
735    ///    first flush left a 0-byte `events-*.parquet` that bricked
736    ///    every subsequent load. Rather than delete, we rename to
737    ///    `<original>.parquet.corrupt-<unix-ts>` so an operator can
738    ///    inspect/forensicate before destroying the evidence — most
739    ///    will just `rm` after seeing the size.
740    ///
741    /// Returns the total number of files acted on, for boot-log
742    /// observability.
743    pub fn cleanup_partial_writes(&self) -> Result<usize> {
744        let mut acted = 0usize;
745        let mut stack: Vec<PathBuf> = vec![self.storage_dir.clone()];
746        while let Some(dir) = stack.pop() {
747            acted += recover_pending_outputs(&dir)?;
748            let Ok(entries) = fs::read_dir(&dir) else {
749                continue;
750            };
751            for entry in entries.flatten() {
752                let path = entry.path();
753                let Ok(ft) = entry.file_type() else { continue };
754                if ft.is_dir() {
755                    stack.push(path);
756                    continue;
757                }
758                if !ft.is_file() {
759                    continue;
760                }
761                let path_str = path.to_string_lossy();
762                if path_str.ends_with(".parquet.tmp") {
763                    match fs::remove_file(&path) {
764                        Ok(()) => {
765                            tracing::warn!(
766                                file = %path.display(),
767                                "cleaned up orphan snapshot tmp file (crash recovery)"
768                            );
769                            acted += 1;
770                        }
771                        Err(e) => {
772                            tracing::error!(
773                                file = %path.display(),
774                                "failed to remove orphan snapshot tmp file: {e}"
775                            );
776                        }
777                    }
778                } else if path_str.ends_with(".parquet")
779                    && fs::metadata(&path).is_ok_and(|m| m.len() == 0)
780                {
781                    // Issue #166: pre-fix checkpoint write left a 0-byte
782                    // .parquet file with the final name on crash. Quarantine
783                    // (rename) rather than delete — operator can inspect.
784                    let ts = chrono::Utc::now().timestamp();
785                    let quarantine_path = path.with_extension(format!("parquet.corrupt-{ts}"));
786                    match fs::rename(&path, &quarantine_path) {
787                        Ok(()) => {
788                            tracing::error!(
789                                from = %path.display(),
790                                to = %quarantine_path.display(),
791                                "quarantined 0-byte parquet file (issue #166 pre-fix crash). \
792                                 Operator: inspect and rm if not needed."
793                            );
794                            acted += 1;
795                        }
796                        Err(e) => {
797                            tracing::error!(
798                                file = %path.display(),
799                                "failed to quarantine 0-byte parquet file: {e}"
800                            );
801                        }
802                    }
803                }
804            }
805        }
806        Ok(acted)
807    }
808
809    /// Force flush any remaining events (for shutdown handling).
810    ///
811    /// Sums pending counts across every tenant's batch so the caller can
812    /// log "we flushed N events on shutdown" without caring about
813    /// per-tenant breakdown.
814    #[cfg_attr(feature = "hotpath", hotpath::measure)]
815    pub fn flush_on_shutdown(&self) -> Result<usize> {
816        let total_pending: usize = {
817            let batches = self.current_batches.lock().unwrap();
818            batches.values().map(Vec::len).sum()
819        };
820
821        if total_pending > 0 {
822            tracing::info!(
823                "Shutdown: flushing {} pending events across all tenants",
824                total_pending
825            );
826            self.flush()?;
827        }
828
829        Ok(total_pending)
830    }
831
832    /// Get batch write statistics
833    pub fn batch_stats(&self) -> BatchWriteStats {
834        let batches = self.batches_written.load(Ordering::Relaxed);
835        let events = self.events_written.load(Ordering::Relaxed);
836        let bytes = self.bytes_written.load(Ordering::Relaxed);
837        let time_ns = self.total_write_time_ns.load(Ordering::Relaxed);
838
839        let time_secs = time_ns as f64 / 1_000_000_000.0;
840
841        BatchWriteStats {
842            batches_written: batches,
843            events_written: events,
844            bytes_written: bytes,
845            avg_batch_size: if batches > 0 {
846                events as f64 / batches as f64
847            } else {
848                0.0
849            },
850            events_per_sec: if time_secs > 0.0 {
851                events as f64 / time_secs
852            } else {
853                0.0
854            },
855            total_write_time_ns: time_ns,
856            timeout_flushes: self.timeout_flushes.load(Ordering::Relaxed),
857            size_flushes: self.size_flushes.load(Ordering::Relaxed),
858        }
859    }
860
861    /// Total pending events across all tenant batches.
862    pub fn pending_count(&self) -> usize {
863        self.current_batches
864            .lock()
865            .unwrap()
866            .values()
867            .map(Vec::len)
868            .sum()
869    }
870
871    /// Get configured batch size
872    pub fn batch_size(&self) -> usize {
873        self.config.batch_size
874    }
875
876    /// Get configured flush timeout
877    pub fn flush_timeout(&self) -> Duration {
878        self.config.flush_timeout
879    }
880
881    fn events_to_record_batch(&self, events: &[Event]) -> Result<RecordBatch> {
882        event_codec::events_to_record_batch(&self.schema, events)
883    }
884
885    /// Load events from all Parquet files under the storage directory.
886    ///
887    /// Walks the tree recursively so both layouts work: legacy flat
888    /// (`storage_dir/events-*.parquet`) and the tenant-partitioned tree
889    /// introduced by the data-strategy work (`storage_dir/<tenant>/<yyyy-mm>/
890    /// events-*.parquet`). The two coexist on disk during migration.
891    #[cfg_attr(feature = "hotpath", hotpath::measure)]
892    pub fn load_all_events(&self) -> Result<Vec<Event>> {
893        let parquet_files = find_parquet_files_recursive(&self.storage_dir)?;
894
895        let mut all_events = Vec::with_capacity(parquet_files.len() * self.config.batch_size);
896        let mut skipped = 0usize;
897        for file_path in parquet_files {
898            tracing::info!("Loading events from {}", file_path.display());
899            let tenant_id = tenant_id_from_path(&self.storage_dir, &file_path);
900            // Issue #166: a single corrupt/0-byte parquet file (crash mid-write
901            // on pre-fix releases) would propagate up and abort the whole load,
902            // bricking access to every healthy file alongside it. Log and skip
903            // instead so one bad file can't take the rest down.
904            match self.load_events_from_file(&file_path, &tenant_id) {
905                Ok(file_events) => all_events.extend(file_events),
906                Err(e) => {
907                    tracing::error!(
908                        file = %file_path.display(),
909                        error = %e,
910                        "Skipping unreadable parquet file — other files will still load. \
911                         Likely a 0-byte or truncated file from an unclean shutdown; \
912                         inspect and remove manually after confirming."
913                    );
914                    skipped += 1;
915                }
916            }
917        }
918
919        if skipped > 0 {
920            tracing::warn!(
921                "Loaded {} events from storage; skipped {} unreadable file(s)",
922                all_events.len(),
923                skipped
924            );
925        } else {
926            tracing::info!("Loaded {} total events from storage", all_events.len());
927        }
928
929        Ok(all_events)
930    }
931
932    /// Load events from a single Parquet file. `tenant_id` is the value to
933    /// stamp onto each loaded event — derived from the file's location in
934    /// the tree by `load_all_events`. The Parquet schema doesn't include
935    /// tenant_id today (path is the source of truth), so this is how
936    /// per-tenant identity survives the round trip.
937    #[cfg_attr(feature = "hotpath", hotpath::measure)]
938    fn load_events_from_file(&self, file_path: &Path, tenant_id: &str) -> Result<Vec<Event>> {
939        self.load_events_from_file_with_budget(file_path, tenant_id, None)
940    }
941
942    fn load_events_from_file_with_budget(
943        &self,
944        file_path: &Path,
945        tenant_id: &str,
946        mut budget: Option<&mut ArchiveReadBudget>,
947    ) -> Result<Vec<Event>> {
948        use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
949
950        if let Some(budget) = budget.as_deref() {
951            budget.check()?;
952        }
953        let file = File::open(file_path).map_err(|e| {
954            AllSourceError::StorageError(format!("Failed to open parquet file: {e}"))
955        })?;
956
957        if let Some(budget) = budget.as_deref_mut() {
958            let metadata = file.metadata().map_err(|error| {
959                AllSourceError::StorageError(format!("Failed to inspect archive file: {error}"))
960            })?;
961            budget.compressed(metadata.len())?;
962        }
963        let mut builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
964        if let Some(budget) = budget.as_deref_mut() {
965            // Rows are charged up front from metadata, so an oversized file is
966            // refused before a single page is decoded. Bytes are charged per
967            // batch below, where the decoded size is known rather than guessed.
968            for group in builder.metadata().row_groups() {
969                budget.rows(group.num_rows())?;
970            }
971            builder = builder.with_batch_size(256);
972        }
973        let reader = builder.build()?;
974
975        let mut events = Vec::new();
976
977        for batch in reader {
978            if let Some(budget) = budget.as_deref() {
979                budget.check()?;
980            }
981            let batch = batch?;
982            if let Some(budget) = budget.as_deref_mut() {
983                budget.decoded_payload(decoded_text_bytes(&batch))?;
984            }
985            let batch_events = self.record_batch_to_events(&batch, tenant_id)?;
986            events.extend(batch_events);
987        }
988
989        if let Some(budget) = budget {
990            budget.check()?;
991        }
992
993        Ok(events)
994    }
995
996    /// Every event for one entity, read straight out of `tenant_id`'s
997    /// archive without making the tenant resident.
998    ///
999    /// Peak memory is this entity's own events plus one batch. That is the
1000    /// difference that matters: hydrating the tenant to answer a question
1001    /// about one entity costs the tenant's whole history, and the largest
1002    /// production tenant does not fit in the machine (gh#321).
1003    ///
1004    /// Row groups whose `entity_id` statistics exclude the target are not
1005    /// decoded. A row group with no usable statistics is decoded, so an
1006    /// archive written without them still answers correctly; the bounds that
1007    /// are present are exact, which `write_atomic_parquet` pins.
1008    ///
1009    /// Unreadable files are skipped, matching the tolerant query policy: a
1010    /// corrupt file must not brick every read for the tenant. The count of
1011    /// skipped files is returned so a caller can say the answer is partial.
1012    pub fn load_entity_events_for_tenant(
1013        &self,
1014        tenant_id: &str,
1015        entity_id: &str,
1016    ) -> Result<(Vec<Event>, usize)> {
1017        let files = self.list_parquet_files_for_tenant(tenant_id)?;
1018        let mut events = Vec::new();
1019        let mut skipped = 0usize;
1020        for file_path in &files {
1021            match self.load_entity_events_from_file(file_path, tenant_id, entity_id) {
1022                Ok(matches) => events.extend(matches),
1023                Err(error) => {
1024                    tracing::error!(
1025                        tenant_id = tenant_id,
1026                        file = %file_path.display(),
1027                        error = %error,
1028                        "Unreadable parquet file in entity-scoped archive read"
1029                    );
1030                    skipped += 1;
1031                }
1032            }
1033        }
1034        tracing::info!(
1035            tenant_id = tenant_id,
1036            entity_id = entity_id,
1037            file_count = files.len(),
1038            matched = events.len(),
1039            skipped_files = skipped,
1040            "entity-scoped archive read complete"
1041        );
1042        Ok((events, skipped))
1043    }
1044
1045    /// One entity's events from one archive file, decoding only the row
1046    /// groups whose statistics admit it.
1047    fn load_entity_events_from_file(
1048        &self,
1049        file_path: &Path,
1050        tenant_id: &str,
1051        entity_id: &str,
1052    ) -> Result<Vec<Event>> {
1053        use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
1054
1055        let file = File::open(file_path).map_err(|error| unreadable(file_path, error))?;
1056        let builder =
1057            ParquetRecordBatchReaderBuilder::try_new(file).map_err(|e| unreadable(file_path, e))?;
1058        let needle = entity_id.as_bytes();
1059        let groups: Vec<usize> = builder
1060            .metadata()
1061            .row_groups()
1062            .iter()
1063            .enumerate()
1064            .filter(|(_, group)| row_group_may_hold_entity(group, needle))
1065            .map(|(index, _)| index)
1066            .collect();
1067        if groups.is_empty() {
1068            return Ok(Vec::new());
1069        }
1070
1071        let reader = builder
1072            .with_row_groups(groups)
1073            .with_batch_size(256)
1074            .build()
1075            .map_err(|error| unreadable(file_path, error))?;
1076
1077        let mut events = Vec::new();
1078        for batch in reader {
1079            let batch = batch.map_err(|error| unreadable(file_path, error))?;
1080            // An admitted row group holds rows for other entities too —
1081            // statistics bound a group, they do not select rows.
1082            for event in self.record_batch_to_events(&batch, tenant_id)? {
1083                if event.entity_id_str() == entity_id {
1084                    events.push(event);
1085                }
1086            }
1087        }
1088        Ok(events)
1089    }
1090
1091    /// Public wrapper around the internal single-file loader. Used
1092    /// by the per-tenant compaction (Step 4) which needs to read a
1093    /// specific candidate set rather than the whole tenant subtree.
1094    /// Caller passes the tenant_id explicitly because the schema
1095    /// doesn't carry it.
1096    pub fn load_events_from_file_path(
1097        &self,
1098        file_path: &Path,
1099        tenant_id: &str,
1100    ) -> Result<Vec<Event>> {
1101        self.load_events_from_file(file_path, tenant_id)
1102    }
1103
1104    /// Convert Arrow RecordBatch back to events. `tenant_id` is stamped onto
1105    /// each reconstructed event — the schema doesn't carry it today, so the
1106    /// caller passes the value derived from the file path.
1107    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1108    fn record_batch_to_events(&self, batch: &RecordBatch, tenant_id: &str) -> Result<Vec<Event>> {
1109        crate::infrastructure::memory::ledger::resident()
1110            .record_rows_decoded(batch.num_rows() as u64);
1111        let event_ids = batch
1112            .column(0)
1113            .as_any()
1114            .downcast_ref::<arrow::array::StringArray>()
1115            .ok_or_else(|| AllSourceError::StorageError("Invalid event_id column".to_string()))?;
1116
1117        let event_types = batch
1118            .column(1)
1119            .as_any()
1120            .downcast_ref::<arrow::array::StringArray>()
1121            .ok_or_else(|| AllSourceError::StorageError("Invalid event_type column".to_string()))?;
1122
1123        let entity_ids = batch
1124            .column(2)
1125            .as_any()
1126            .downcast_ref::<arrow::array::StringArray>()
1127            .ok_or_else(|| AllSourceError::StorageError("Invalid entity_id column".to_string()))?;
1128
1129        let payloads = batch
1130            .column(3)
1131            .as_any()
1132            .downcast_ref::<arrow::array::StringArray>()
1133            .ok_or_else(|| AllSourceError::StorageError("Invalid payload column".to_string()))?;
1134
1135        let timestamps = batch
1136            .column(4)
1137            .as_any()
1138            .downcast_ref::<TimestampMicrosecondArray>()
1139            .ok_or_else(|| AllSourceError::StorageError("Invalid timestamp column".to_string()))?;
1140
1141        let metadatas = batch
1142            .column(5)
1143            .as_any()
1144            .downcast_ref::<arrow::array::StringArray>()
1145            .ok_or_else(|| AllSourceError::StorageError("Invalid metadata column".to_string()))?;
1146
1147        let versions = batch
1148            .column(6)
1149            .as_any()
1150            .downcast_ref::<arrow::array::UInt64Array>()
1151            .ok_or_else(|| AllSourceError::StorageError("Invalid version column".to_string()))?;
1152
1153        let valid_froms = optional_timestamp_column(batch, VALID_FROM_COLUMN)?;
1154        let valid_tos = optional_timestamp_column(batch, VALID_TO_COLUMN)?;
1155
1156        let mut events = Vec::new();
1157
1158        for i in 0..batch.num_rows() {
1159            let id = uuid::Uuid::parse_str(event_ids.value(i))
1160                .map_err(|e| AllSourceError::StorageError(format!("Invalid UUID: {e}")))?;
1161
1162            let timestamp = chrono::DateTime::from_timestamp_micros(timestamps.value(i))
1163                .ok_or_else(|| AllSourceError::StorageError("Invalid timestamp".to_string()))?;
1164
1165            let metadata = if metadatas.is_null(i) {
1166                None
1167            } else {
1168                Some(serde_json::from_str(metadatas.value(i))?)
1169            };
1170
1171            let mut event = Event::reconstruct_from_strings(
1172                id,
1173                event_types.value(i).to_string(),
1174                entity_ids.value(i).to_string(),
1175                tenant_id.to_string(),
1176                serde_json::from_str(payloads.value(i))?,
1177                timestamp,
1178                metadata,
1179                versions.value(i) as i64,
1180            );
1181            event.valid_from = valid_time_at(valid_froms, i)?;
1182            event.valid_to = valid_time_at(valid_tos, i)?;
1183
1184            events.push(event);
1185        }
1186
1187        Ok(events)
1188    }
1189
1190    /// List all Parquet file paths under the storage directory, sorted by
1191    /// the relative path so files in the same partition stay grouped.
1192    ///
1193    /// Used by the replication catch-up protocol to stream snapshot files
1194    /// to followers that are too far behind for WAL-only catch-up.
1195    pub fn list_parquet_files(&self) -> Result<Vec<PathBuf>> {
1196        find_parquet_files_recursive(&self.storage_dir)
1197    }
1198
1199    /// The tenant a Parquet file belongs to, read from its place in the tree.
1200    pub fn tenant_id_for_file(&self, file_path: &Path) -> String {
1201        tenant_id_from_path(&self.storage_dir, file_path)
1202    }
1203
1204    /// List Parquet files belonging to a single tenant — i.e. only files
1205    /// under `<storage_dir>/<tenant>/...`. Legacy flat-layout files at the
1206    /// root are intentionally excluded; the migration tool moves them under
1207    /// `default/` so once it has run a `tenant=default` query sees them.
1208    ///
1209    /// Returns an empty vec when the tenant subtree doesn't exist (no data
1210    /// for that tenant yet). Returns an error only if `tenant_id` fails the
1211    /// path-safety whitelist.
1212    ///
1213    /// This is the building block for tenant-scoped reads: the caller knows
1214    /// which files might contain the tenant's data without opening any of
1215    /// the others.
1216    pub fn list_parquet_files_for_tenant(&self, tenant_id: &str) -> Result<Vec<PathBuf>> {
1217        let safe = sanitize_tenant_id_for_path(tenant_id)?;
1218        let tenant_root = self.storage_dir.join(safe);
1219        if !tenant_root.is_dir() {
1220            return Ok(Vec::new());
1221        }
1222        find_parquet_files_recursive(&tenant_root)
1223    }
1224
1225    /// Compressed bytes `tenant_id`'s archive occupies on disk, and the
1226    /// number of files holding them.
1227    ///
1228    /// Read before a cold load to decide whether the tenant can be made
1229    /// resident at all. Unreadable entries are skipped rather than failing
1230    /// the call: an under-count makes the decision more permissive, and this
1231    /// figure only ever gates work that the headroom check re-verifies as it
1232    /// proceeds.
1233    pub fn tenant_archive_bytes(&self, tenant_id: &str) -> Result<(u64, usize)> {
1234        let files = self.list_parquet_files_for_tenant(tenant_id)?;
1235        let count = files.len();
1236        let bytes = files
1237            .iter()
1238            .filter_map(|path| std::fs::metadata(path).ok())
1239            .map(|metadata| metadata.len())
1240            .sum();
1241        Ok((bytes, count))
1242    }
1243
1244    fn list_complete_tenant_archive(
1245        &self,
1246        tenant_id: &str,
1247        budget: &mut ArchiveReadBudget,
1248    ) -> Result<Vec<PathBuf>> {
1249        budget.check()?;
1250        let safe = sanitize_tenant_id_for_path(tenant_id)?;
1251        let root = self.storage_dir.join(safe);
1252        match fs::symlink_metadata(&root) {
1253            Ok(metadata) if metadata.is_dir() => {
1254                find_parquet_files_recursive_with_integrity(&root, Some(budget))
1255            }
1256            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
1257            _ => Err(AllSourceError::StorageError(
1258                "Cannot verify conditional version: tenant archive is not an accessible directory"
1259                    .into(),
1260            )),
1261        }
1262    }
1263
1264    /// Load only the events belonging to `tenant_id`, walking just that
1265    /// tenant's subtree on disk. The full-storage loader
1266    /// (`load_all_events`) opens every Parquet file regardless of tenant;
1267    /// this one only opens files under `<storage_dir>/<tenant>/`.
1268    ///
1269    /// Returns an empty vec when the tenant has no on-disk data. Returns
1270    /// an error if the tenant_id fails the path-safety whitelist or listing
1271    /// fails. Individual unreadable files are logged and skipped for queries;
1272    /// this tolerant result cannot establish a complete version for OCC.
1273    ///
1274    /// This is the read-side complement to per-tenant flushing. It's the
1275    /// foundation Step 2 (lazy per-tenant load on demand) needs: a way to
1276    /// hydrate one tenant without paying the cost of loading every other
1277    /// tenant's data into memory.
1278    ///
1279    /// Tenant identity for loaded events comes from the file path, the
1280    /// same as `load_all_events` — `record_batch_to_events` stamps the
1281    /// passed `tenant_id` onto every reconstructed event.
1282    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1283    pub fn load_events_for_tenant(&self, tenant_id: &str) -> Result<Vec<Event>> {
1284        self.load_events_for_tenant_with_integrity(tenant_id, None)
1285            .map(|(events, _complete)| events)
1286    }
1287
1288    /// Highest persisted version of one entity in `tenant_id`'s archive,
1289    /// answered from the tenant's version manifest.
1290    ///
1291    /// The manifest holds a version per entity and names the files it was
1292    /// folded from, so only files it does not name have to be read. In steady
1293    /// state that is the handful flushed since the last resolve; for a tenant
1294    /// with no manifest yet it is every file, which is the one-time cost of
1295    /// building it.
1296    ///
1297    /// Returns [`ResolvedVersion::Incomplete`] rather than a version when the
1298    /// budget runs out with files still unaccounted for. The files folded
1299    /// before that point are persisted, so the next attempt resumes instead of
1300    /// restarting: the manifest is its own cursor. A partial answer is never
1301    /// returned as a version, because understating one would let the next
1302    /// conditional write reuse a version already on disk.
1303    pub(crate) fn resolve_entity_version(
1304        &self,
1305        tenant_id: &str,
1306        entity_id: &str,
1307        budget: &mut ArchiveReadBudget,
1308    ) -> Result<ResolvedVersion> {
1309        let files = self.list_complete_tenant_archive(tenant_id, budget)?;
1310        let tenant_dir = self
1311            .storage_dir
1312            .join(sanitize_tenant_id_for_path(tenant_id)?);
1313        let mut manifest = VersionManifest::load(&tenant_dir).unwrap_or_default();
1314
1315        let outstanding: Vec<PathBuf> = files
1316            .into_iter()
1317            .filter(|path| {
1318                manifest_key(&tenant_dir, path).is_none_or(|key| !manifest.covered.contains(&key))
1319            })
1320            .collect();
1321
1322        if outstanding.is_empty() {
1323            return Ok(ResolvedVersion::Complete(manifest.version_of(entity_id)));
1324        }
1325
1326        let mut folded = 0usize;
1327        let mut exhausted = None;
1328        for path in &outstanding {
1329            // Enumeration already charged each file against `max_files`.
1330            if let Err(error) = self.fold_entity_versions(path, &mut manifest.entities, budget) {
1331                exhausted = Some(error);
1332                break;
1333            }
1334            if let Some(key) = manifest_key(&tenant_dir, path) {
1335                manifest.covered.insert(key);
1336            }
1337            folded += 1;
1338        }
1339
1340        // Resumability depends on this outliving the attempt that earned it.
1341        if folded > 0 {
1342            manifest.store(&tenant_dir)?;
1343        }
1344
1345        if let Some(error) = exhausted {
1346            let remaining = outstanding.len() - folded;
1347            // A budget that expired is a capacity limit and the caller may
1348            // retry; anything else (a corrupt file, an unreadable column) is
1349            // not going to resolve itself and has to surface.
1350            if is_budget_exhaustion(&error) {
1351                return Ok(ResolvedVersion::Incomplete {
1352                    remaining,
1353                    reason: error.to_string(),
1354                });
1355            }
1356            return Err(error);
1357        }
1358
1359        Ok(ResolvedVersion::Complete(manifest.version_of(entity_id)))
1360    }
1361
1362    /// Record the versions of events just flushed to `file`, so a later
1363    /// conditional write does not have to read them back.
1364    pub(crate) fn record_flushed_versions(
1365        &self,
1366        tenant_id: &str,
1367        file: &Path,
1368        events: &[Event],
1369    ) -> Result<()> {
1370        let tenant_dir = self
1371            .storage_dir
1372            .join(sanitize_tenant_id_for_path(tenant_id)?);
1373        let Some(key) = manifest_key(&tenant_dir, file) else {
1374            return Ok(());
1375        };
1376        let mut manifest = VersionManifest::load(&tenant_dir).unwrap_or_default();
1377        manifest.observe_file(&key, events);
1378        manifest.store(&tenant_dir)
1379    }
1380
1381    /// Fold every entity's highest version out of one archive file.
1382    ///
1383    /// Every column is decoded, so a corrupt row group fails here exactly as
1384    /// it would during a full load: a version read from an archive that cannot
1385    /// be read through is not a version worth trusting. What this avoids is
1386    /// the part that costs memory rather than CPU — no payload is parsed into
1387    /// a `serde_json::Value` and no `Event` outlives its batch, so peak heap
1388    /// is one batch, not the file's whole contents.
1389    fn fold_entity_versions(
1390        &self,
1391        file_path: &Path,
1392        versions: &mut HashMap<String, u64>,
1393        budget: &mut ArchiveReadBudget,
1394    ) -> Result<()> {
1395        use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
1396
1397        budget.check()?;
1398        let file = File::open(file_path).map_err(|e| {
1399            AllSourceError::StorageError(format!("Failed to open parquet file: {e}"))
1400        })?;
1401        let file_len = file
1402            .metadata()
1403            .map_err(|error| {
1404                AllSourceError::StorageError(format!("Failed to inspect archive file: {error}"))
1405            })?
1406            .len();
1407        budget.compressed(file_len)?;
1408
1409        let builder = ParquetRecordBatchReaderBuilder::try_new(file)
1410            .map_err(|error| unreadable(file_path, error))?;
1411
1412        // Only entity_id and version outlive a batch; the rest is decoded to
1413        // prove the file readable, then dropped.
1414        for group in builder.metadata().row_groups() {
1415            let retained: i64 = [ENTITY_ID_COLUMN, VERSION_COLUMN]
1416                .iter()
1417                .map(|&column| group.column(column).uncompressed_size())
1418                .sum();
1419            budget.decoded_metadata(group.num_rows(), retained)?;
1420        }
1421
1422        let reader = builder
1423            .with_batch_size(1024)
1424            .build()
1425            .map_err(|error| unreadable(file_path, error))?;
1426
1427        for batch in reader {
1428            budget.check()?;
1429            let batch = batch.map_err(|error| unreadable(file_path, error))?;
1430            let entity_ids = batch
1431                .column(ENTITY_ID_COLUMN)
1432                .as_any()
1433                .downcast_ref::<arrow::array::StringArray>()
1434                .ok_or_else(|| {
1435                    AllSourceError::StorageError("Invalid entity_id column".to_string())
1436                })?;
1437            let row_versions = batch
1438                .column(VERSION_COLUMN)
1439                .as_any()
1440                .downcast_ref::<arrow::array::UInt64Array>()
1441                .ok_or_else(|| {
1442                    AllSourceError::StorageError("Invalid version column".to_string())
1443                })?;
1444
1445            for i in 0..batch.num_rows() {
1446                let version = row_versions.value(i);
1447                versions
1448                    .entry(entity_ids.value(i).to_string())
1449                    .and_modify(|current| *current = (*current).max(version))
1450                    .or_insert(version);
1451            }
1452        }
1453
1454        Ok(())
1455    }
1456
1457    pub(crate) fn load_events_for_tenant_with_integrity(
1458        &self,
1459        tenant_id: &str,
1460        budget: Option<&mut ArchiveReadBudget>,
1461    ) -> Result<(Vec<Event>, bool)> {
1462        let mut events = Vec::new();
1463        let complete = self.for_each_tenant_file_events(tenant_id, budget, |batch| {
1464            events.extend(batch);
1465            Ok(())
1466        })?;
1467        Ok((events, complete))
1468    }
1469
1470    /// Visit `tenant_id`'s archive one file at a time, handing each file's
1471    /// events to `visit`.
1472    ///
1473    /// Peak memory is one file's events rather than the tenant's history,
1474    /// which is what separates this from collecting the lot: a caller that
1475    /// splices events into a longer-lived structure would otherwise hold the
1476    /// whole archive twice at once, and the largest production tenant does
1477    /// not fit in the machine even once (gh#321).
1478    ///
1479    /// `visit` returning `Err` aborts the walk. Returns whether the archive
1480    /// was read completely, which only strict enumeration can certify.
1481    pub(crate) fn for_each_tenant_file_events(
1482        &self,
1483        tenant_id: &str,
1484        mut budget: Option<&mut ArchiveReadBudget>,
1485        mut visit: impl FnMut(Vec<Event>) -> Result<()>,
1486    ) -> Result<bool> {
1487        let require_complete = budget.is_some();
1488        let parquet_files = if let Some(budget) = budget.as_deref_mut() {
1489            self.list_complete_tenant_archive(tenant_id, budget)?
1490        } else {
1491            self.list_parquet_files_for_tenant(tenant_id)?
1492        };
1493        tracing::info!(
1494            tenant_id = tenant_id,
1495            file_count = parquet_files.len(),
1496            "load_events_for_tenant: walking tenant subtree only"
1497        );
1498
1499        let mut visited = 0usize;
1500        let mut skipped = 0usize;
1501        for file_path in parquet_files {
1502            tracing::debug!(
1503                tenant_id = tenant_id,
1504                file = %file_path.display(),
1505                "load_events_for_tenant: opening file"
1506            );
1507            // Issue #166: same defensive log-and-skip as load_all_events.
1508            // The lazy-load path can hit a corrupt file just as easily as
1509            // boot can — failing the whole tenant load on one bad file
1510            // would brick every query for that tenant.
1511            match self.load_events_from_file_with_budget(
1512                &file_path,
1513                tenant_id,
1514                budget.as_deref_mut(),
1515            ) {
1516                Ok(file_events) => {
1517                    visited += file_events.len();
1518                    visit(file_events)?;
1519                }
1520                Err(e) => {
1521                    tracing::error!(
1522                        tenant_id = tenant_id,
1523                        file = %file_path.display(),
1524                        error = %e,
1525                        require_complete,
1526                        "Unreadable parquet file in tenant subtree"
1527                    );
1528                    skipped += 1;
1529                    if require_complete {
1530                        if let Some(budget) = budget.as_deref() {
1531                            budget.check()?;
1532                        }
1533                        if is_budget_exhaustion(&e) {
1534                            return Err(e);
1535                        }
1536                        return Err(AllSourceError::StorageError(format!(
1537                            "Cannot verify conditional version from incomplete archive: {e}"
1538                        )));
1539                    }
1540                }
1541            }
1542        }
1543
1544        tracing::info!(
1545            tenant_id = tenant_id,
1546            event_count = visited,
1547            skipped_files = skipped,
1548            "load_events_for_tenant: complete"
1549        );
1550        // Tolerant enumeration may omit unreadable directories or entries.
1551        // Only strict enumeration can certify the retained archive for OCC.
1552        Ok(require_complete && skipped == 0)
1553    }
1554
1555    /// Get the storage directory path.
1556    pub fn storage_dir(&self) -> &Path {
1557        &self.storage_dir
1558    }
1559
1560    /// One-shot migration of flat-layout files into the tenant-partitioned
1561    /// tree. Run with Core stopped (no concurrent writes).
1562    ///
1563    /// Walks `storage_dir`'s top level (non-recursive) for the legacy
1564    /// `events-*.parquet` files. For each one it loads the events,
1565    /// regroups them by (tenant_id, yyyy-mm) — events from a flat file
1566    /// take the path-derived "default" tenant, since pre-partitioning
1567    /// data carried no tenant in its on-disk form — writes a fresh
1568    /// Parquet under the corresponding partition directory, and deletes
1569    /// the original flat file once the new file is closed.
1570    ///
1571    /// `dry_run = true` reports what would happen without touching disk.
1572    /// Run dry first; production data deserves the rehearsal.
1573    ///
1574    /// Crash safety: this writes the new partition file before deleting
1575    /// the flat file, so a crash between the two leaves both on disk.
1576    /// The recursive loader (`load_all_events`) will then return both,
1577    /// duplicating those events on next boot. Mitigation: stop Core
1578    /// before running, and re-run the migration after any crash so the
1579    /// flat file gets deleted. A future commit can add atomic rename +
1580    /// fsync semantics; for the one-time migration the stop-Core
1581    /// constraint is enough.
1582    pub fn migrate_flat_layout(&self, dry_run: bool) -> Result<MigrationReport> {
1583        let flat_files = list_flat_layout_files(&self.storage_dir)?;
1584        let mut report = MigrationReport {
1585            dry_run,
1586            ..Default::default()
1587        };
1588
1589        for flat_file in flat_files {
1590            // Pre-partition events used path-derived tenant. For flat-layout
1591            // files that's always "default" (`tenant_id_from_path` falls back
1592            // to "default" for single-component paths).
1593            let events = self.load_events_from_file(&flat_file, "default")?;
1594            report.flat_files_seen += 1;
1595
1596            if events.is_empty() {
1597                // Stale empty file (zero rows). Just remove it.
1598                if !dry_run {
1599                    fs::remove_file(&flat_file).map_err(|e| {
1600                        AllSourceError::StorageError(format!(
1601                            "Failed to remove empty flat file {}: {e}",
1602                            flat_file.display()
1603                        ))
1604                    })?;
1605                }
1606                report.flat_files_removed += 1;
1607                continue;
1608            }
1609
1610            // Group by (tenant, yyyy-mm-from-event-timestamp). The
1611            // partition month tracks the event's wall-clock time so that
1612            // post-migration the layout reflects when data happened, not
1613            // when migration ran. Step 4 (per-tenant snapshots) and Step
1614            // 5 (retention) will key on that.
1615            let mut groups: HashMap<(String, String), Vec<Event>> = HashMap::new();
1616            for event in events {
1617                let key = (
1618                    event.tenant_id_str().to_string(),
1619                    event.timestamp().format("%Y-%m").to_string(),
1620                );
1621                groups.entry(key).or_default().push(event);
1622            }
1623
1624            for ((tenant, yyyy_mm), group_events) in groups {
1625                let count = group_events.len();
1626                if !dry_run {
1627                    let safe_tenant = sanitize_tenant_id_for_path(&tenant)?;
1628                    let target_dir = self.storage_dir.join(safe_tenant).join(&yyyy_mm);
1629                    fs::create_dir_all(&target_dir).map_err(|e| {
1630                        AllSourceError::StorageError(format!(
1631                            "Failed to create partition {}: {e}",
1632                            target_dir.display()
1633                        ))
1634                    })?;
1635                    let filename = format!(
1636                        "events-{}-{}.parquet",
1637                        chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"),
1638                        uuid::Uuid::new_v4().as_simple()
1639                    );
1640                    let record_batch = self.events_to_record_batch(&group_events)?;
1641                    let mut output = ArchiveOutput::new(
1642                        &target_dir,
1643                        filename.trim_end_matches(".parquet"),
1644                        self.config.compression,
1645                        ArchiveReadLimits::default().max_file_bytes,
1646                        true,
1647                    )?;
1648                    output.stage(&record_batch)?;
1649                    report.partitions_written += output.publish()?.len();
1650                }
1651                report.events_migrated += count;
1652            }
1653
1654            if !dry_run {
1655                fs::remove_file(&flat_file).map_err(|e| {
1656                    AllSourceError::StorageError(format!(
1657                        "Failed to remove flat file {} after migration: {e}",
1658                        flat_file.display()
1659                    ))
1660                })?;
1661                report.flat_files_removed += 1;
1662            }
1663        }
1664
1665        Ok(report)
1666    }
1667
1668    /// Get storage statistics
1669    pub fn stats(&self) -> Result<StorageStats> {
1670        let parquet_files = find_parquet_files_recursive(&self.storage_dir)?;
1671        let mut total_size_bytes = 0u64;
1672        for path in &parquet_files {
1673            if let Ok(metadata) = fs::metadata(path) {
1674                total_size_bytes += metadata.len();
1675            }
1676        }
1677
1678        let current_batch_size: usize = self
1679            .current_batches
1680            .lock()
1681            .unwrap()
1682            .values()
1683            .map(Vec::len)
1684            .sum();
1685
1686        Ok(StorageStats {
1687            total_files: parquet_files.len(),
1688            total_size_bytes,
1689            storage_dir: self.storage_dir.clone(),
1690            current_batch_size,
1691        })
1692    }
1693}
1694
1695/// Validate a tenant ID for use as a filesystem path component.
1696///
1697/// Whitelist: ASCII letters, digits, `-`, `_`, `.` — covers UUIDs, the
1698/// hyphen-and-lowercase tenant strings the onboarding flow produces, and
1699/// the `system` tenant the heartbeat emitter uses. Rejects empty input,
1700/// any path separator (`/`, `\`), and any "..". The whitelist is the
1701/// primary defence against path traversal; the explicit ".." check is
1702/// belt-and-braces in case the whitelist ever loosens.
1703///
1704/// Length capped at 128 bytes — comfortably above the 36-byte UUID and
1705/// the longest onboarding tenant the system has produced, well below
1706/// every common filesystem's NAME_MAX (typically 255).
1707fn sanitize_tenant_id_for_path(tenant_id: &str) -> Result<&str> {
1708    if tenant_id.is_empty() {
1709        return Err(AllSourceError::StorageError(
1710            "tenant_id is empty (cannot derive partition path)".to_string(),
1711        ));
1712    }
1713    if tenant_id.len() > 128 {
1714        return Err(AllSourceError::StorageError(format!(
1715            "tenant_id is too long for partition path: {} bytes (max 128)",
1716            tenant_id.len()
1717        )));
1718    }
1719    if tenant_id == "." || tenant_id == ".." {
1720        return Err(AllSourceError::StorageError(format!(
1721            "tenant_id {tenant_id:?} is reserved"
1722        )));
1723    }
1724    for c in tenant_id.chars() {
1725        let ok = c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.';
1726        if !ok {
1727            return Err(AllSourceError::StorageError(format!(
1728                "tenant_id {tenant_id:?} contains disallowed character {c:?} for partition path"
1729            )));
1730        }
1731    }
1732    Ok(tenant_id)
1733}
1734
1735/// A damaged archive must refuse a conditional write as a storage failure,
1736/// not surface the decoder's own error type to the caller.
1737fn unreadable(path: &Path, error: impl std::fmt::Display) -> AllSourceError {
1738    AllSourceError::StorageError(format!(
1739        "Cannot verify conditional version from {}: {error}",
1740        path.display()
1741    ))
1742}
1743
1744/// Whether a row group's `entity_id` statistics permit `needle`.
1745///
1746/// Absent statistics, or present ones with no usable bounds, read as "maybe"
1747/// and the group is decoded. The failure to avoid is the other direction: a
1748/// group wrongly excluded makes a present event look missing, and nothing
1749/// downstream can tell that apart from the entity genuinely having no such
1750/// event.
1751///
1752/// Byte-wise comparison matches Parquet's own ordering for a UTF-8 column,
1753/// so these bounds are compared the way the writer established them.
1754fn row_group_may_hold_entity(
1755    group: &parquet::file::metadata::RowGroupMetaData,
1756    needle: &[u8],
1757) -> bool {
1758    let Some(statistics) = group.column(ENTITY_ID_COLUMN).statistics() else {
1759        return true;
1760    };
1761    let (Some(min), Some(max)) = (statistics.min_bytes_opt(), statistics.max_bytes_opt()) else {
1762        return true;
1763    };
1764    min <= needle && needle <= max
1765}
1766
1767/// How an archive file is named inside its tenant's manifest.
1768///
1769/// Relative to the tenant directory, so the manifest survives the data
1770/// directory being moved or mounted at a different path. `None` for a path
1771/// outside the tenant directory, which is then simply never marked covered.
1772fn manifest_key(tenant_dir: &Path, file: &Path) -> Option<String> {
1773    Some(
1774        file.strip_prefix(tenant_dir)
1775            .ok()?
1776            .to_string_lossy()
1777            .into_owned(),
1778    )
1779}
1780
1781/// Whether an error is the budget refusing more work rather than the archive
1782/// being unreadable. Only the former is worth retrying.
1783fn is_budget_exhaustion(error: &AllSourceError) -> bool {
1784    matches!(error, AllSourceError::ArchiveBudgetExceeded { .. })
1785}
1786
1787/// Resolve the directory a flush should write into for `(tenant, when)`.
1788///
1789/// Returns `<root>/<tenant>/<yyyy-mm>/`. Caller is responsible for
1790/// `create_dir_all`-ing the result before opening files in it.
1791fn partition_path_for_tenant(
1792    root: &Path,
1793    tenant_id: &str,
1794    when: chrono::DateTime<chrono::Utc>,
1795) -> Result<PathBuf> {
1796    let safe = sanitize_tenant_id_for_path(tenant_id)?;
1797    Ok(root.join(safe).join(when.format("%Y-%m").to_string()))
1798}
1799
1800/// Reverse of `partition_path_for_tenant` — given a parquet file's full
1801/// path and the storage root, return the tenant_id stored in the path.
1802///
1803/// Tenant-partitioned shape: `<root>/<tenant>/<yyyy-mm>/events-*.parquet`
1804/// → first component after root is the tenant.
1805///
1806/// Legacy flat shape: `<root>/events-*.parquet` → no tenant in path, fall
1807/// back to `"default"` so events written before the partitioning change
1808/// keep loading with their original (and only ever) tenant identity.
1809fn tenant_id_from_path(root: &Path, file_path: &Path) -> String {
1810    let Ok(rel) = file_path.strip_prefix(root) else {
1811        return "default".to_string();
1812    };
1813    let mut comps = rel.components();
1814    let first = comps.next();
1815    let next = comps.next();
1816    match (first, next) {
1817        // Two or more components: <tenant>/<rest>... → tenant
1818        (Some(std::path::Component::Normal(tenant)), Some(_)) => {
1819            tenant.to_string_lossy().into_owned()
1820        }
1821        // Single component (the parquet file itself): legacy flat layout.
1822        _ => "default".to_string(),
1823    }
1824}
1825
1826/// List Parquet files at the top level of `root` only — i.e. the legacy
1827/// flat-layout files. Used by the one-shot migration tool to find data
1828/// that needs moving into the tenant-partitioned tree. The opposite of
1829/// `find_parquet_files_recursive`: stops at the first directory level so
1830/// already-partitioned data isn't included.
1831fn list_flat_layout_files(root: &Path) -> Result<Vec<PathBuf>> {
1832    let entries = fs::read_dir(root).map_err(|e| {
1833        AllSourceError::StorageError(format!("Failed to read storage directory: {e}"))
1834    })?;
1835    let mut out: Vec<PathBuf> = entries
1836        .filter_map(std::result::Result::ok)
1837        .filter_map(|entry| {
1838            let ft = entry.file_type().ok()?;
1839            if !ft.is_file() {
1840                return None;
1841            }
1842            let path = entry.path();
1843            if path.extension().and_then(|s| s.to_str()) == Some("parquet") {
1844                Some(path)
1845            } else {
1846                None
1847            }
1848        })
1849        .collect();
1850    out.sort();
1851    Ok(out)
1852}
1853
1854/// Recursively collect all `*.parquet` files under `root`, sorted by path so
1855/// callers see a deterministic, tenant-grouped order.
1856///
1857/// Existence rationale: the storage layout is moving from a flat
1858/// `storage_dir/events-*.parquet` pile to a tenant-partitioned tree of the
1859/// shape `storage_dir/<tenant>/<yyyy-mm>/events-*.parquet`. During the
1860/// migration both shapes coexist, so every code path that asks "what
1861/// parquet files do we have?" needs to walk subdirectories. Symlinks are
1862/// not followed — the storage tree is mounted from a single volume and
1863/// chasing symlinks invites cycles.
1864fn find_parquet_files_recursive(root: &Path) -> Result<Vec<PathBuf>> {
1865    find_parquet_files_recursive_with_integrity(root, None)
1866}
1867
1868fn find_parquet_files_recursive_with_integrity(
1869    root: &Path,
1870    mut budget: Option<&mut ArchiveReadBudget>,
1871) -> Result<Vec<PathBuf>> {
1872    let require_complete = budget.is_some();
1873    let mut out = Vec::new();
1874    let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
1875
1876    while let Some(dir) = stack.pop() {
1877        if let Some(budget) = budget.as_deref() {
1878            budget.check()?;
1879        }
1880        let entries = match fs::read_dir(&dir) {
1881            Ok(e) => e,
1882            // Root must exist (we created it in `new`); subdirectories may
1883            // race a delete from compaction. Tolerant reads skip those;
1884            // strict reads cannot certify history after enumeration failed.
1885            Err(e) if dir == root || require_complete => {
1886                return Err(AllSourceError::StorageError(format!(
1887                    "Failed to read storage directory: {e}"
1888                )));
1889            }
1890            Err(_) => continue,
1891        };
1892
1893        for entry in entries {
1894            if let Some(budget) = budget.as_deref_mut() {
1895                budget.entry()?;
1896            }
1897            let entry = match entry {
1898                Ok(entry) => entry,
1899                Err(error) if require_complete => {
1900                    return Err(AllSourceError::StorageError(format!(
1901                        "Failed to enumerate complete archive: {error}"
1902                    )));
1903                }
1904                Err(_) => continue,
1905            };
1906            let path = entry.path();
1907            if pending_marker(&path) && require_complete {
1908                return Err(AllSourceError::StorageError(
1909                    "Archive output publication incomplete".into(),
1910                ));
1911            }
1912            // Use file_type() rather than metadata() so symlinks don't get
1913            // followed by accident (metadata() resolves symlinks, file_type()
1914            // doesn't).
1915            let ft = match entry.file_type() {
1916                Ok(file_type) => file_type,
1917                Err(error) if require_complete => {
1918                    return Err(AllSourceError::StorageError(format!(
1919                        "Failed to inspect complete archive entry: {error}"
1920                    )));
1921                }
1922                Err(_) => continue,
1923            };
1924            if ft.is_dir() {
1925                stack.push(path);
1926            } else if ft.is_file() && pending_part(&path) {
1927                if require_complete {
1928                    return Err(AllSourceError::StorageError(
1929                        "Archive output publication incomplete".into(),
1930                    ));
1931                }
1932            } else if ft.is_file()
1933                && path
1934                    .extension()
1935                    .and_then(|ext| ext.to_str())
1936                    .is_some_and(|ext| ext == "parquet")
1937            {
1938                if let Some(budget) = budget.as_deref_mut() {
1939                    budget.file()?;
1940                }
1941                out.push(path);
1942            }
1943        }
1944    }
1945
1946    out.sort();
1947    if let Some(budget) = budget {
1948        budget.check()?;
1949    }
1950    Ok(out)
1951}
1952
1953impl Drop for ParquetStorage {
1954    fn drop(&mut self) {
1955        // Ensure any remaining events are flushed on shutdown
1956        if let Err(e) = self.flush_on_shutdown() {
1957            tracing::error!("Failed to flush events on drop: {}", e);
1958        }
1959    }
1960}
1961
1962/// Outcome of a `migrate_flat_layout` run.
1963#[derive(Debug, Default, Clone, serde::Serialize)]
1964pub struct MigrationReport {
1965    /// Whether the run was a rehearsal (no disk changes).
1966    pub dry_run: bool,
1967    /// Number of legacy flat-layout files discovered.
1968    pub flat_files_seen: usize,
1969    /// Number of legacy flat files deleted (always 0 when `dry_run`).
1970    pub flat_files_removed: usize,
1971    /// Number of new partition files written under the tenant tree.
1972    pub partitions_written: usize,
1973    /// Total events copied into the new tree (counted in dry-run too).
1974    pub events_migrated: usize,
1975}
1976
1977#[derive(Debug, serde::Serialize)]
1978pub struct StorageStats {
1979    pub total_files: usize,
1980    pub total_size_bytes: u64,
1981    pub storage_dir: PathBuf,
1982    pub current_batch_size: usize,
1983}
1984
1985#[cfg(test)]
1986mod tests {
1987    use super::*;
1988    use arrow::datatypes::{DataType, Field, TimeUnit};
1989    use serde_json::json;
1990    use std::sync::Arc;
1991    use tempfile::TempDir;
1992
1993    fn create_test_event(entity_id: &str) -> Event {
1994        Event::reconstruct_from_strings(
1995            uuid::Uuid::new_v4(),
1996            "test.event".to_string(),
1997            entity_id.to_string(),
1998            "default".to_string(),
1999            json!({
2000                "test": "data",
2001                "value": 42
2002            }),
2003            chrono::Utc::now(),
2004            None,
2005            1,
2006        )
2007    }
2008
2009    #[test]
2010    fn valid_time_round_trips_through_parquet() {
2011        let temp_dir = TempDir::new().unwrap();
2012        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2013        let valid_from = chrono::DateTime::from_timestamp_micros(1_700_000_000_123_456).unwrap();
2014        let valid_to = chrono::DateTime::from_timestamp_micros(1_700_000_900_000_001).unwrap();
2015
2016        let mut event = create_test_event("entity-valid");
2017        event.valid_from = Some(valid_from);
2018        event.valid_to = Some(valid_to);
2019        let mut open_ended = create_test_event("entity-open");
2020        open_ended.valid_from = Some(valid_from);
2021        storage.append_event(event).unwrap();
2022        storage.append_event(open_ended).unwrap();
2023        storage.flush().unwrap();
2024
2025        let mut loaded = storage.load_all_events().unwrap();
2026        loaded.sort_by(|a, b| a.entity_id_str().cmp(b.entity_id_str()));
2027        assert_eq!(loaded.len(), 2);
2028        assert_eq!(loaded[0].entity_id_str(), "entity-open");
2029        assert_eq!(loaded[0].valid_from, Some(valid_from));
2030        assert_eq!(loaded[0].valid_to, None);
2031        assert_eq!(loaded[1].valid_from, Some(valid_from));
2032        assert_eq!(loaded[1].valid_to, Some(valid_to));
2033    }
2034
2035    /// A file written before `valid_from` / `valid_to` existed: seven columns,
2036    /// the old names and types, nothing appended.
2037    #[test]
2038    fn a_parquet_file_without_valid_time_columns_reads_back_unset() {
2039        use arrow::array::{StringArray, TimestampMicrosecondArray, UInt64Array};
2040        use parquet::arrow::ArrowWriter;
2041
2042        let temp_dir = TempDir::new().unwrap();
2043        let path = temp_dir.path().join("pre-valid-time.parquet");
2044        let ids = [
2045            uuid::Uuid::new_v4().to_string(),
2046            uuid::Uuid::new_v4().to_string(),
2047        ];
2048        let timestamps = [1_700_000_000_000_000_i64, 1_700_000_100_000_000_i64];
2049        let schema = Arc::new(Schema::new(vec![
2050            Field::new("event_id", DataType::Utf8, false),
2051            Field::new("event_type", DataType::Utf8, false),
2052            Field::new("entity_id", DataType::Utf8, false),
2053            Field::new("payload", DataType::Utf8, false),
2054            Field::new(
2055                "timestamp",
2056                DataType::Timestamp(TimeUnit::Microsecond, None),
2057                false,
2058            ),
2059            Field::new("metadata", DataType::Utf8, true),
2060            Field::new("version", DataType::UInt64, false),
2061        ]));
2062        let batch = RecordBatch::try_new(
2063            schema.clone(),
2064            vec![
2065                Arc::new(StringArray::from(vec![ids[0].as_str(), ids[1].as_str()])),
2066                Arc::new(StringArray::from(vec!["test.event", "test.event"])),
2067                Arc::new(StringArray::from(vec!["entity-a", "entity-b"])),
2068                Arc::new(StringArray::from(vec!["{}", "{}"])),
2069                Arc::new(TimestampMicrosecondArray::from(timestamps.to_vec())),
2070                Arc::new(StringArray::from(vec![None::<&str>, None])),
2071                Arc::new(UInt64Array::from(vec![1_u64, 2])),
2072            ],
2073        )
2074        .unwrap();
2075        let mut writer = ArrowWriter::try_new(File::create(&path).unwrap(), schema, None).unwrap();
2076        writer.write(&batch).unwrap();
2077        writer.close().unwrap();
2078
2079        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2080        let loaded = storage
2081            .load_events_from_file_path(&path, "default")
2082            .unwrap();
2083
2084        assert_eq!(loaded.len(), 2);
2085        assert_eq!(loaded[0].id.to_string(), ids[0]);
2086        assert_eq!(loaded[0].timestamp.timestamp_micros(), timestamps[0]);
2087        assert_eq!(loaded[0].valid_from, None);
2088        assert_eq!(loaded[0].valid_to, None);
2089        assert_eq!(loaded[1].valid_from, None);
2090        assert_eq!(loaded[1].valid_to, None);
2091    }
2092
2093    #[test]
2094    fn test_parquet_storage_write_read() {
2095        let temp_dir = TempDir::new().unwrap();
2096        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2097
2098        // Add events
2099        for i in 0..10 {
2100            let event = create_test_event(&format!("entity-{i}"));
2101            storage.append_event(event).unwrap();
2102        }
2103
2104        // Flush to disk
2105        storage.flush().unwrap();
2106
2107        // Load back
2108        let loaded_events = storage.load_all_events().unwrap();
2109        assert_eq!(loaded_events.len(), 10);
2110    }
2111
2112    #[test]
2113    fn test_storage_stats() {
2114        let temp_dir = TempDir::new().unwrap();
2115        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2116
2117        // Add and flush events
2118        for i in 0..5 {
2119            storage
2120                .append_event(create_test_event(&format!("entity-{i}")))
2121                .unwrap();
2122        }
2123        storage.flush().unwrap();
2124
2125        let stats = storage.stats().unwrap();
2126        assert_eq!(stats.total_files, 1);
2127        assert!(stats.total_size_bytes > 0);
2128    }
2129
2130    #[test]
2131    fn test_default_batch_size() {
2132        let temp_dir = TempDir::new().unwrap();
2133        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2134
2135        // Default batch size should be 10,000 as per US-023
2136        assert_eq!(storage.batch_size(), DEFAULT_BATCH_SIZE);
2137        assert_eq!(storage.batch_size(), 10_000);
2138    }
2139
2140    #[test]
2141    fn test_custom_config() {
2142        let temp_dir = TempDir::new().unwrap();
2143        let config = ParquetStorageConfig {
2144            batch_size: 5_000,
2145            flush_timeout: Duration::from_secs(2),
2146            compression: parquet::basic::Compression::SNAPPY,
2147            file_namer: None,
2148        };
2149        let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2150
2151        assert_eq!(storage.batch_size(), 5_000);
2152        assert_eq!(storage.flush_timeout(), Duration::from_secs(2));
2153    }
2154
2155    #[test]
2156    fn test_batch_write() {
2157        let temp_dir = TempDir::new().unwrap();
2158        let config = ParquetStorageConfig {
2159            batch_size: 100, // Small batch for testing
2160            ..Default::default()
2161        };
2162        let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2163
2164        // 250 events for a single tenant. With per-tenant flush, when the
2165        // tenant's pending batch crosses batch_size we drain the whole
2166        // tenant in one flush — not chunk at exactly batch_size like the
2167        // old global-batch path did. So 250 events triggers exactly one
2168        // size-flush (the appender pushes all 250 onto the tenant's batch
2169        // under one lock, sees length >= 100, schedules a flush which
2170        // drains everything). 0 left pending.
2171        let events: Vec<Event> = (0..250)
2172            .map(|i| create_test_event(&format!("entity-{i}")))
2173            .collect();
2174
2175        let result = storage.batch_write(events).unwrap();
2176        assert_eq!(result.events_written, 250);
2177        assert_eq!(result.batches_flushed, 1);
2178        assert_eq!(storage.pending_count(), 0);
2179
2180        // Manual flush is a no-op since nothing's pending.
2181        storage.flush().unwrap();
2182
2183        // All 250 events round-trip through the tenant-partitioned tree.
2184        let loaded = storage.load_all_events().unwrap();
2185        assert_eq!(loaded.len(), 250);
2186    }
2187
2188    #[test]
2189    fn test_auto_flush_on_batch_size() {
2190        let temp_dir = TempDir::new().unwrap();
2191        let config = ParquetStorageConfig {
2192            batch_size: 10, // Very small for testing
2193            ..Default::default()
2194        };
2195        let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2196
2197        // Add 15 events - should auto-flush at 10
2198        for i in 0..15 {
2199            storage
2200                .append_event(create_test_event(&format!("entity-{i}")))
2201                .unwrap();
2202        }
2203
2204        // Should have 5 pending, 10 written
2205        assert_eq!(storage.pending_count(), 5);
2206
2207        let stats = storage.batch_stats();
2208        assert_eq!(stats.events_written, 10);
2209        assert_eq!(stats.batches_written, 1);
2210        assert_eq!(stats.size_flushes, 1);
2211    }
2212
2213    #[test]
2214    fn test_flush_on_shutdown() {
2215        let temp_dir = TempDir::new().unwrap();
2216        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2217
2218        // Add some events without reaching batch size
2219        for i in 0..5 {
2220            storage
2221                .append_event(create_test_event(&format!("entity-{i}")))
2222                .unwrap();
2223        }
2224
2225        assert_eq!(storage.pending_count(), 5);
2226
2227        // Manually trigger shutdown flush
2228        let flushed = storage.flush_on_shutdown().unwrap();
2229        assert_eq!(flushed, 5);
2230        assert_eq!(storage.pending_count(), 0);
2231
2232        // Verify events are persisted
2233        let loaded = storage.load_all_events().unwrap();
2234        assert_eq!(loaded.len(), 5);
2235    }
2236
2237    #[test]
2238    fn test_thread_safe_writes() {
2239        let temp_dir = TempDir::new().unwrap();
2240        let config = ParquetStorageConfig {
2241            batch_size: 100,
2242            ..Default::default()
2243        };
2244        let storage = Arc::new(ParquetStorage::with_config(temp_dir.path(), config).unwrap());
2245
2246        let events_per_thread = 50;
2247        let thread_count = 4;
2248
2249        std::thread::scope(|s| {
2250            for t in 0..thread_count {
2251                let storage_ref = Arc::clone(&storage);
2252                s.spawn(move || {
2253                    for i in 0..events_per_thread {
2254                        let event = create_test_event(&format!("thread-{t}-entity-{i}"));
2255                        storage_ref.append_event(event).unwrap();
2256                    }
2257                });
2258            }
2259        });
2260
2261        // Flush remaining
2262        storage.flush().unwrap();
2263
2264        // All events should be written
2265        let loaded = storage.load_all_events().unwrap();
2266        assert_eq!(loaded.len(), events_per_thread * thread_count);
2267    }
2268
2269    #[test]
2270    fn test_batch_stats() {
2271        let temp_dir = TempDir::new().unwrap();
2272        let config = ParquetStorageConfig {
2273            batch_size: 50,
2274            ..Default::default()
2275        };
2276        let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2277
2278        // 100 events, single tenant, batch_size=50. Per-tenant flush
2279        // drains the whole tenant on the first size trigger, so this
2280        // produces exactly one size-flush and one batches_written event
2281        // (vs. the pre-tenant world's two).
2282        let events: Vec<Event> = (0..100)
2283            .map(|i| create_test_event(&format!("entity-{i}")))
2284            .collect();
2285
2286        storage.batch_write(events).unwrap();
2287
2288        let stats = storage.batch_stats();
2289        assert_eq!(stats.batches_written, 1);
2290        assert_eq!(stats.events_written, 100);
2291        assert!(stats.avg_batch_size > 0.0);
2292        assert!(stats.events_per_sec > 0.0);
2293        assert_eq!(stats.size_flushes, 1);
2294    }
2295
2296    #[test]
2297    fn test_config_presets() {
2298        let high_throughput = ParquetStorageConfig::high_throughput();
2299        assert_eq!(high_throughput.batch_size, 50_000);
2300        assert_eq!(high_throughput.flush_timeout, Duration::from_secs(10));
2301
2302        let low_latency = ParquetStorageConfig::low_latency();
2303        assert_eq!(low_latency.batch_size, 1_000);
2304        assert_eq!(low_latency.flush_timeout, Duration::from_secs(1));
2305
2306        let default = ParquetStorageConfig::default();
2307        assert_eq!(default.batch_size, DEFAULT_BATCH_SIZE);
2308        assert_eq!(default.batch_size, 10_000);
2309    }
2310
2311    /// Benchmark: Compare single-event writes vs batch writes
2312    /// Run with: cargo test --release -- --ignored test_batch_write_throughput
2313    #[test]
2314    #[ignore]
2315    fn test_batch_write_throughput() {
2316        let temp_dir = TempDir::new().unwrap();
2317        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2318
2319        let event_count = 50_000;
2320
2321        // Benchmark batch write
2322        let events: Vec<Event> = (0..event_count)
2323            .map(|i| create_test_event(&format!("entity-{i}")))
2324            .collect();
2325
2326        let start = std::time::Instant::now();
2327        let result = storage.batch_write(events).unwrap();
2328        storage.flush().unwrap(); // Flush any remaining
2329        let batch_duration = start.elapsed();
2330
2331        let batch_stats = storage.batch_stats();
2332
2333        println!("\n=== Parquet Batch Write Performance (BATCH_SIZE=10,000) ===");
2334        println!("Events: {event_count}");
2335        println!("Duration: {batch_duration:?}");
2336        println!("Events/sec: {:.0}", result.events_per_sec);
2337        println!("Batches written: {}", batch_stats.batches_written);
2338        println!("Avg batch size: {:.0}", batch_stats.avg_batch_size);
2339        println!("Bytes written: {} KB", batch_stats.bytes_written / 1024);
2340
2341        // Target: Batch writes should achieve at least 100K events/sec in release mode
2342        // This represents 40%+ improvement over single-event writes
2343        assert!(
2344            result.events_per_sec > 10_000.0,
2345            "Batch write throughput too low: {:.0} events/sec (expected >10K in debug, >100K in release)",
2346            result.events_per_sec
2347        );
2348    }
2349
2350    /// Benchmark: Single-event write baseline (for comparison)
2351    #[test]
2352    #[ignore]
2353    fn test_single_event_write_baseline() {
2354        let temp_dir = TempDir::new().unwrap();
2355        let config = ParquetStorageConfig {
2356            batch_size: 1, // Force flush after each event
2357            ..Default::default()
2358        };
2359        let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2360
2361        let event_count = 1_000; // Fewer events since this is slow
2362
2363        let start = std::time::Instant::now();
2364        for i in 0..event_count {
2365            let event = create_test_event(&format!("entity-{i}"));
2366            storage.append_event(event).unwrap();
2367        }
2368        let duration = start.elapsed();
2369
2370        let events_per_sec = f64::from(event_count) / duration.as_secs_f64();
2371
2372        println!("\n=== Single-Event Write Baseline ===");
2373        println!("Events: {event_count}");
2374        println!("Duration: {duration:?}");
2375        println!("Events/sec: {events_per_sec:.0}");
2376
2377        // This should be significantly slower than batch writes
2378        // Used as a baseline to demonstrate 40%+ improvement
2379    }
2380
2381    // -----------------------------------------------------------------
2382    // Tests for the recursive parquet walker (Step 1, commit #1: read-side
2383    // bidirectional layout support — see SUSTAINABLE_DATA_STRATEGY.md).
2384    // -----------------------------------------------------------------
2385
2386    /// Helper: write a tiny placeholder parquet file at an arbitrary path so
2387    /// the walker has something concrete to find. We only care that the
2388    /// walker discovers the path, not that the file is loadable here — the
2389    /// load path is exercised by the existing read tests.
2390    fn touch_parquet(path: &Path) {
2391        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2392        std::fs::write(path, b"").unwrap();
2393    }
2394
2395    #[test]
2396    fn test_walker_finds_files_in_flat_layout() {
2397        let temp_dir = TempDir::new().unwrap();
2398        let root = temp_dir.path();
2399        touch_parquet(&root.join("events-20260101-120000000-aaaa.parquet"));
2400        touch_parquet(&root.join("events-20260101-130000000-bbbb.parquet"));
2401
2402        let mut found = find_parquet_files_recursive(root).unwrap();
2403        found.sort();
2404        assert_eq!(found.len(), 2);
2405        assert!(
2406            found[0]
2407                .file_name()
2408                .unwrap()
2409                .to_str()
2410                .unwrap()
2411                .starts_with("events-"),
2412            "expected events-* file, got {found:?}"
2413        );
2414    }
2415
2416    #[test]
2417    fn test_walker_finds_files_in_tenant_partitioned_tree() {
2418        let temp_dir = TempDir::new().unwrap();
2419        let root = temp_dir.path();
2420        // Tenant-partitioned shape: storage_dir/<tenant>/<yyyy-mm>/events-*.parquet
2421        touch_parquet(&root.join("tenant-a/2026-01/events-20260101-120000000-aaaa.parquet"));
2422        touch_parquet(&root.join("tenant-a/2026-02/events-20260201-120000000-bbbb.parquet"));
2423        touch_parquet(&root.join("tenant-b/2026-01/events-20260103-120000000-cccc.parquet"));
2424
2425        let found = find_parquet_files_recursive(root).unwrap();
2426        assert_eq!(found.len(), 3);
2427        // Sort places tenant-a files before tenant-b — that's the
2428        // tenant-grouping the docs claim.
2429        assert!(found[0].to_str().unwrap().contains("tenant-a"));
2430        assert!(found[1].to_str().unwrap().contains("tenant-a"));
2431        assert!(found[2].to_str().unwrap().contains("tenant-b"));
2432    }
2433
2434    #[test]
2435    fn test_walker_handles_mixed_legacy_and_partitioned_layouts() {
2436        // The migration window: some tenants have been moved into the tree,
2437        // some flat files still sit at the root. The walker must surface
2438        // both so load_all_events sees every event regardless of where it
2439        // currently lives.
2440        let temp_dir = TempDir::new().unwrap();
2441        let root = temp_dir.path();
2442        touch_parquet(&root.join("events-legacy-aaaa.parquet"));
2443        touch_parquet(&root.join("tenant-a/2026-01/events-new-bbbb.parquet"));
2444
2445        let found = find_parquet_files_recursive(root).unwrap();
2446        assert_eq!(found.len(), 2);
2447    }
2448
2449    #[test]
2450    fn test_walker_ignores_non_parquet_files() {
2451        let temp_dir = TempDir::new().unwrap();
2452        let root = temp_dir.path();
2453        std::fs::write(root.join("README.md"), b"hello").unwrap();
2454        std::fs::write(root.join("events.json"), b"[]").unwrap();
2455        touch_parquet(&root.join("events-20260101-120000000-aaaa.parquet"));
2456        // Files that just happen to have "parquet" in the name but no
2457        // .parquet extension stay out — extension-only filter, no name match.
2458        std::fs::write(root.join("not-a-parquet-file.bin"), b"").unwrap();
2459
2460        let found = find_parquet_files_recursive(root).unwrap();
2461        assert_eq!(found.len(), 1);
2462        assert_eq!(
2463            found[0].extension().and_then(|s| s.to_str()),
2464            Some("parquet")
2465        );
2466    }
2467
2468    /// Build an event whose tenant_id and entity_id we control, so tests
2469    /// can verify per-tenant routing without depending on the helper that
2470    /// hardcodes "default".
2471    fn event_with_tenant(tenant: &str, entity_id: &str) -> Event {
2472        Event::reconstruct_from_strings(
2473            uuid::Uuid::new_v4(),
2474            "test.event".to_string(),
2475            entity_id.to_string(),
2476            tenant.to_string(),
2477            json!({"k": "v"}),
2478            chrono::Utc::now(),
2479            None,
2480            1,
2481        )
2482    }
2483
2484    #[test]
2485    fn test_flush_writes_into_per_tenant_partition() {
2486        // End-to-end check that the new write path produces
2487        // <root>/<tenant>/<yyyy-mm>/events-*.parquet — no flat file at the
2488        // root, no cross-tenant mixing.
2489        let temp_dir = TempDir::new().unwrap();
2490        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2491
2492        for i in 0..3 {
2493            storage
2494                .append_event(event_with_tenant("default", &format!("entity-{i}")))
2495                .unwrap();
2496        }
2497        storage.flush().unwrap();
2498
2499        let parquet_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
2500        assert_eq!(parquet_files.len(), 1);
2501
2502        let rel = parquet_files[0]
2503            .strip_prefix(temp_dir.path())
2504            .unwrap()
2505            .to_string_lossy()
2506            .into_owned();
2507        // Path shape: default/<yyyy-mm>/events-*.parquet
2508        let parts: Vec<&str> = rel.split(std::path::MAIN_SEPARATOR).collect();
2509        assert_eq!(parts.len(), 3, "expected tenant/yyyy-mm/file, got {rel}");
2510        assert_eq!(parts[0], "default");
2511        // yyyy-mm is two digits dash four — loose check, exact month
2512        // varies with wall-clock at test runtime.
2513        assert!(
2514            parts[1].len() == 7 && parts[1].as_bytes()[4] == b'-',
2515            "expected yyyy-mm, got {}",
2516            parts[1]
2517        );
2518        assert!(parts[2].starts_with("events-") && parts[2].ends_with(".parquet"));
2519
2520        let loaded = storage.load_all_events().unwrap();
2521        assert_eq!(loaded.len(), 3);
2522    }
2523
2524    #[test]
2525    fn test_multiple_tenants_get_isolated_subtrees() {
2526        // Per-tenant flush must not mix tenants into the same Parquet file
2527        // and must put each tenant under its own subdirectory.
2528        let temp_dir = TempDir::new().unwrap();
2529        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2530
2531        for i in 0..2 {
2532            storage
2533                .append_event(event_with_tenant("alice", &format!("a-{i}")))
2534                .unwrap();
2535        }
2536        for i in 0..3 {
2537            storage
2538                .append_event(event_with_tenant("bob", &format!("b-{i}")))
2539                .unwrap();
2540        }
2541        storage.flush().unwrap();
2542
2543        let alice_subtree = temp_dir.path().join("alice");
2544        let bob_subtree = temp_dir.path().join("bob");
2545        assert!(alice_subtree.is_dir(), "alice should have its own subtree");
2546        assert!(bob_subtree.is_dir(), "bob should have its own subtree");
2547
2548        let alice_files = find_parquet_files_recursive(&alice_subtree).unwrap();
2549        let bob_files = find_parquet_files_recursive(&bob_subtree).unwrap();
2550        assert_eq!(alice_files.len(), 1);
2551        assert_eq!(bob_files.len(), 1);
2552
2553        // Loaded events keep their tenant_id — round-trip preserves which
2554        // tenant each event belonged to.
2555        let loaded = storage.load_all_events().unwrap();
2556        let (alice_count, bob_count) =
2557            loaded
2558                .iter()
2559                .fold((0, 0), |(a, b), e| match e.tenant_id_str() {
2560                    "alice" => (a + 1, b),
2561                    "bob" => (a, b + 1),
2562                    _ => (a, b),
2563                });
2564        assert_eq!(alice_count, 2);
2565        assert_eq!(bob_count, 3);
2566    }
2567
2568    #[test]
2569    fn test_size_flush_only_drains_full_tenant() {
2570        // When one tenant exactly hits batch_size, only that tenant
2571        // flushes; the other tenant keeps its events buffered. Prevents
2572        // one noisy tenant from causing fragmented writes for everyone.
2573        let temp_dir = TempDir::new().unwrap();
2574        let config = ParquetStorageConfig {
2575            batch_size: 5,
2576            ..Default::default()
2577        };
2578        let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2579
2580        // Alice: 5 events → on the 5th, len == batch_size triggers flush
2581        // which drains all 5. Alice ends empty.
2582        for i in 0..5 {
2583            storage
2584                .append_event(event_with_tenant("alice", &format!("a-{i}")))
2585                .unwrap();
2586        }
2587        // Bob: 2 events → still under threshold, stays pending.
2588        for i in 0..2 {
2589            storage
2590                .append_event(event_with_tenant("bob", &format!("b-{i}")))
2591                .unwrap();
2592        }
2593
2594        assert_eq!(
2595            storage.pending_count(),
2596            2,
2597            "only bob's 2 events should be pending"
2598        );
2599
2600        let parquet_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
2601        assert_eq!(parquet_files.len(), 1, "only alice should have flushed");
2602        assert!(
2603            parquet_files[0]
2604                .to_string_lossy()
2605                .contains(&format!("alice{}", std::path::MAIN_SEPARATOR)),
2606            "expected alice partition, got {}",
2607            parquet_files[0].display()
2608        );
2609    }
2610
2611    #[test]
2612    fn test_tenant_id_from_path_recovers_tenant_for_partitioned_files() {
2613        let root = Path::new("/data/storage");
2614        let f = Path::new("/data/storage/alice/2026-04/events-20260426-120000000-aaaa.parquet");
2615        assert_eq!(tenant_id_from_path(root, f), "alice");
2616    }
2617
2618    #[test]
2619    fn test_tenant_id_from_path_falls_back_to_default_for_legacy_flat_layout() {
2620        let root = Path::new("/data/storage");
2621        let f = Path::new("/data/storage/events-20260426-120000000-aaaa.parquet");
2622        // Legacy single-component path. Pre-tenant data was always
2623        // commingled with tenant=default, so default is the right fallback.
2624        assert_eq!(tenant_id_from_path(root, f), "default");
2625    }
2626
2627    #[test]
2628    fn test_sanitize_tenant_id_for_path_accepts_safe_inputs() {
2629        for ok in [
2630            "default",
2631            "system",
2632            "1e6b2d1c-2f64-4441-9cf9-42f2e451aa17",
2633            "onboard-diagnostic-160-at-example-com",
2634            "tenant_with_underscore",
2635            "v1.0",
2636        ] {
2637            assert!(
2638                sanitize_tenant_id_for_path(ok).is_ok(),
2639                "{ok:?} should be accepted"
2640            );
2641        }
2642    }
2643
2644    #[test]
2645    fn test_sanitize_tenant_id_for_path_rejects_unsafe_inputs() {
2646        for bad in [
2647            "",         // empty
2648            "..",       // parent traversal
2649            ".",        // current dir
2650            "foo/bar",  // path separator
2651            "foo\\bar", // windows-style separator
2652            "foo bar",  // whitespace
2653            "foo\nbar", // newline
2654            "foo\0bar", // null byte
2655            "tenant?",  // shell glob char
2656            "tenant*",  // shell glob char
2657        ] {
2658            assert!(
2659                sanitize_tenant_id_for_path(bad).is_err(),
2660                "{bad:?} should be rejected"
2661            );
2662        }
2663
2664        // Length cap.
2665        let too_long = "a".repeat(129);
2666        assert!(sanitize_tenant_id_for_path(&too_long).is_err());
2667    }
2668
2669    #[test]
2670    fn test_partition_path_for_tenant_shape() {
2671        let root = Path::new("/data");
2672        let when = chrono::DateTime::parse_from_rfc3339("2026-04-26T12:00:00Z")
2673            .unwrap()
2674            .with_timezone(&chrono::Utc);
2675        let path = partition_path_for_tenant(root, "alice", when).unwrap();
2676        assert_eq!(path, Path::new("/data/alice/2026-04"));
2677    }
2678
2679    #[test]
2680    fn test_append_event_rejects_unsafe_tenant_at_flush() {
2681        // Defence in depth: even if some upstream forgets to validate, the
2682        // sanitizer in flush_tenant catches it. Since append doesn't write
2683        // synchronously, the bad tenant is rejected on the first flush
2684        // attempt. We test that flush surfaces an error rather than
2685        // silently writing somewhere weird.
2686        let temp_dir = TempDir::new().unwrap();
2687        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2688
2689        // append accepts whatever tenant_id the event carries — domain
2690        // construction would normally reject this, but if it slipped
2691        // through, flush should refuse to derive a path from it.
2692        storage
2693            .append_event(event_with_tenant("../escape", "e-0"))
2694            .unwrap();
2695        let result = storage.flush();
2696        assert!(result.is_err(), "flush should reject unsafe tenant_id");
2697        let msg = format!("{}", result.unwrap_err());
2698        assert!(
2699            msg.contains("disallowed character") || msg.contains("reserved"),
2700            "expected sanitization error message, got: {msg}"
2701        );
2702    }
2703
2704    // -----------------------------------------------------------------
2705    // Tenant-pruned read tests (Step 1, commit #4).
2706    // -----------------------------------------------------------------
2707
2708    #[test]
2709    fn test_load_events_for_tenant_only_walks_target_subtree() {
2710        // Seed three tenants with distinct event counts. Loading one
2711        // tenant must return only that tenant's events — and the file
2712        // list helper must report only that tenant's files (the strong
2713        // form of "didn't open the others").
2714        let temp_dir = TempDir::new().unwrap();
2715        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2716
2717        for i in 0..2 {
2718            storage
2719                .append_event(event_with_tenant("alice", &format!("a-{i}")))
2720                .unwrap();
2721        }
2722        for i in 0..3 {
2723            storage
2724                .append_event(event_with_tenant("bob", &format!("b-{i}")))
2725                .unwrap();
2726        }
2727        for i in 0..1 {
2728            storage
2729                .append_event(event_with_tenant("carol", &format!("c-{i}")))
2730                .unwrap();
2731        }
2732        storage.flush().unwrap();
2733
2734        let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
2735        assert_eq!(alice_files.len(), 1);
2736        assert!(
2737            alice_files[0]
2738                .to_string_lossy()
2739                .contains(&format!("alice{}", std::path::MAIN_SEPARATOR)),
2740            "expected alice file, got {}",
2741            alice_files[0].display()
2742        );
2743        // The pruned listing must NOT include any bob/carol files — this
2744        // is the property Step 2 will rely on to avoid loading every
2745        // tenant's data on a single-tenant query.
2746        for f in &alice_files {
2747            let s = f.to_string_lossy();
2748            assert!(!s.contains("bob"), "alice listing leaked bob file: {s}");
2749            assert!(!s.contains("carol"), "alice listing leaked carol file: {s}");
2750        }
2751
2752        let alice_events = storage.load_events_for_tenant("alice").unwrap();
2753        assert_eq!(alice_events.len(), 2);
2754        for e in &alice_events {
2755            assert_eq!(e.tenant_id_str(), "alice");
2756        }
2757
2758        let bob_events = storage.load_events_for_tenant("bob").unwrap();
2759        assert_eq!(bob_events.len(), 3);
2760        for e in &bob_events {
2761            assert_eq!(e.tenant_id_str(), "bob");
2762        }
2763
2764        let carol_events = storage.load_events_for_tenant("carol").unwrap();
2765        assert_eq!(carol_events.len(), 1);
2766        assert_eq!(carol_events[0].tenant_id_str(), "carol");
2767    }
2768
2769    #[test]
2770    fn test_load_events_for_tenant_returns_empty_when_subtree_missing() {
2771        // Querying a tenant that has never written must not error — it's
2772        // a normal "no data" case, not a misconfiguration. Important for
2773        // first-query latency on a fresh tenant.
2774        let temp_dir = TempDir::new().unwrap();
2775        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2776
2777        // Seed only alice so the storage_dir isn't empty (rule out the
2778        // empty-dir trivial case).
2779        storage
2780            .append_event(event_with_tenant("alice", "a-0"))
2781            .unwrap();
2782        storage.flush().unwrap();
2783
2784        let files = storage
2785            .list_parquet_files_for_tenant("nobody-here")
2786            .unwrap();
2787        assert!(files.is_empty());
2788
2789        let events = storage.load_events_for_tenant("nobody-here").unwrap();
2790        assert!(events.is_empty());
2791    }
2792
2793    #[test]
2794    fn test_load_events_for_tenant_rejects_unsafe_tenant_id() {
2795        // Path traversal must fail at the API boundary, not after disk
2796        // reads. Same whitelist as the write path.
2797        let temp_dir = TempDir::new().unwrap();
2798        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2799
2800        for unsafe_tid in ["..", "a/b", "a\\b", "", "a..b/.."] {
2801            let result = storage.load_events_for_tenant(unsafe_tid);
2802            assert!(
2803                result.is_err(),
2804                "tenant_id {unsafe_tid:?} should have been rejected"
2805            );
2806        }
2807    }
2808
2809    #[test]
2810    fn test_load_events_for_tenant_ignores_legacy_flat_layout_files() {
2811        // Flat-layout files at the storage root predate partitioning. A
2812        // tenant-scoped load must not pick them up — the migration tool
2813        // is what relocates them under default/. Until it runs, those
2814        // files are invisible to per-tenant queries (correct behavior:
2815        // the system has no way to tell which tenant they belong to
2816        // beyond "default", and pretending otherwise would mis-attribute
2817        // them).
2818        let temp_dir = TempDir::new().unwrap();
2819        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2820
2821        // Seed a flat-layout file (relocates default/<yyyy-mm>/ → root).
2822        let _flat = seed_flat_layout_file(&storage, 4);
2823
2824        // Querying default returns nothing — the flat file at the root
2825        // isn't under default/.
2826        let default_events = storage.load_events_for_tenant("default").unwrap();
2827        assert!(
2828            default_events.is_empty(),
2829            "tenant-scoped load must not pick up flat-layout files; got {} events",
2830            default_events.len()
2831        );
2832
2833        // Sanity: the full loader still sees them via the recursive walk.
2834        let all_events = storage.load_all_events().unwrap();
2835        assert_eq!(all_events.len(), 4);
2836    }
2837
2838    // -----------------------------------------------------------------
2839    // Atomic snapshot write tests (Step 4, commit #1).
2840    // -----------------------------------------------------------------
2841
2842    #[test]
2843    fn test_write_atomic_parquet_emits_file_under_tenant_partition() {
2844        // Happy path: write 3 events for tenant alice, get back a
2845        // path under <root>/alice/<yyyy-mm>/. The .tmp file should
2846        // be gone (rename completed); the final file readable via
2847        // load_events_for_tenant.
2848        let temp_dir = TempDir::new().unwrap();
2849        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2850
2851        let events: Vec<Event> = (0..3)
2852            .map(|i| event_with_tenant("alice", &format!("a-{i}")))
2853            .collect();
2854
2855        let final_path = storage
2856            .write_atomic_parquet("alice", "snapshot.alice.range", &events)
2857            .unwrap();
2858
2859        // Path shape: <root>/alice/<yyyy-mm>/snapshot.alice.range.parquet
2860        let rel = final_path
2861            .strip_prefix(temp_dir.path())
2862            .unwrap()
2863            .to_string_lossy()
2864            .into_owned();
2865        let parts: Vec<&str> = rel.split(std::path::MAIN_SEPARATOR).collect();
2866        assert_eq!(parts.len(), 3, "expected tenant/yyyy-mm/file, got {rel}");
2867        assert_eq!(parts[0], "alice");
2868        assert_eq!(parts[2], "snapshot.alice.range.parquet");
2869
2870        // Final file must exist; .tmp must NOT.
2871        assert!(final_path.is_file());
2872        let tmp = final_path.with_extension("parquet.tmp");
2873        assert!(
2874            !tmp.exists(),
2875            "tmp should have been renamed away; still at {}",
2876            tmp.display()
2877        );
2878
2879        // Loadable via the tenant loader.
2880        let loaded = storage.load_events_for_tenant("alice").unwrap();
2881        assert_eq!(loaded.len(), 3);
2882    }
2883
2884    #[test]
2885    fn test_write_atomic_parquet_rejects_empty_events() {
2886        let temp_dir = TempDir::new().unwrap();
2887        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2888        let result = storage.write_atomic_parquet("alice", "snap", &[]);
2889        assert!(result.is_err());
2890    }
2891
2892    #[test]
2893    fn test_write_atomic_parquet_rejects_unsafe_tenant() {
2894        let temp_dir = TempDir::new().unwrap();
2895        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2896        let events = [event_with_tenant("alice", "e-0")];
2897        for unsafe_tid in ["..", "a/b", ""] {
2898            let result = storage.write_atomic_parquet(unsafe_tid, "snap", &events);
2899            assert!(
2900                result.is_err(),
2901                "unsafe tenant_id {unsafe_tid:?} should have been rejected"
2902            );
2903        }
2904    }
2905
2906    #[test]
2907    fn test_cleanup_partial_writes_removes_orphan_tmps() {
2908        // Simulate a crashed mid-snapshot: pretend we have a leftover
2909        // events-x.parquet.tmp file in a tenant partition. Cleanup
2910        // must delete it without touching real .parquet files.
2911        let temp_dir = TempDir::new().unwrap();
2912        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2913
2914        // Seed a real parquet via a normal flush, so we have one
2915        // legit file we don't want to delete.
2916        for i in 0..2 {
2917            storage
2918                .append_event(event_with_tenant("alice", &format!("a-{i}")))
2919                .unwrap();
2920        }
2921        storage.flush().unwrap();
2922        let real_files_before = find_parquet_files_recursive(temp_dir.path()).unwrap();
2923        assert_eq!(real_files_before.len(), 1);
2924
2925        // Manufacture an orphan .tmp file in alice's partition.
2926        let alice_subtree = temp_dir.path().join("alice");
2927        let orphan_dir = real_files_before[0].parent().unwrap();
2928        let orphan_path = orphan_dir.join("snapshot.alice.crashed.parquet.tmp");
2929        std::fs::write(&orphan_path, b"fake partial parquet").unwrap();
2930        assert!(orphan_path.is_file());
2931
2932        // And one nested deeper, just to confirm recursion.
2933        let nested_dir = alice_subtree.join("2099-01");
2934        std::fs::create_dir_all(&nested_dir).unwrap();
2935        let nested_orphan = nested_dir.join("events-x.parquet.tmp");
2936        std::fs::write(&nested_orphan, b"junk").unwrap();
2937
2938        let removed = storage.cleanup_partial_writes().unwrap();
2939        assert_eq!(removed, 2, "two orphan tmps should have been cleaned");
2940        assert!(!orphan_path.exists());
2941        assert!(!nested_orphan.exists());
2942
2943        // Real parquet untouched.
2944        let real_files_after = find_parquet_files_recursive(temp_dir.path()).unwrap();
2945        assert_eq!(real_files_after, real_files_before);
2946    }
2947
2948    #[test]
2949    fn test_cleanup_partial_writes_quarantines_zero_byte_parquet() {
2950        // Issue #166 regression: a pre-fix checkpoint crash left a 0-byte
2951        // events-*.parquet file with the FINAL extension (no .tmp). The
2952        // cleanup pass must rename it aside rather than delete, so an
2953        // operator can inspect.
2954        let temp_dir = TempDir::new().unwrap();
2955        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2956
2957        // Seed a real parquet alongside, to confirm we don't molest healthy data.
2958        for i in 0..2 {
2959            storage
2960                .append_event(event_with_tenant("alice", &format!("a-{i}")))
2961                .unwrap();
2962        }
2963        storage.flush().unwrap();
2964        let healthy_files_before = find_parquet_files_recursive(temp_dir.path()).unwrap();
2965        assert_eq!(healthy_files_before.len(), 1);
2966        let healthy_file = &healthy_files_before[0];
2967        let healthy_dir = healthy_file.parent().unwrap();
2968
2969        // Drop a 0-byte parquet next to the healthy one (the issue's failure mode).
2970        let bricked = healthy_dir.join("events-bricked-deadbeef.parquet");
2971        std::fs::write(&bricked, b"").unwrap();
2972        assert_eq!(std::fs::metadata(&bricked).unwrap().len(), 0);
2973
2974        let acted = storage.cleanup_partial_writes().unwrap();
2975        assert_eq!(acted, 1, "only the 0-byte file should have been acted on");
2976
2977        // 0-byte file is gone from its original name, but a quarantined
2978        // sibling exists.
2979        assert!(!bricked.exists(), "0-byte file should have been renamed");
2980        let quarantined: Vec<_> = std::fs::read_dir(healthy_dir)
2981            .unwrap()
2982            .flatten()
2983            .map(|e| e.path())
2984            .filter(|p| {
2985                p.file_name()
2986                    .and_then(|n| n.to_str())
2987                    .is_some_and(|n| n.starts_with("events-bricked-deadbeef.parquet.corrupt-"))
2988            })
2989            .collect();
2990        assert_eq!(
2991            quarantined.len(),
2992            1,
2993            "expected one .parquet.corrupt-<ts> sibling"
2994        );
2995
2996        // Healthy file untouched.
2997        assert!(
2998            healthy_file.exists(),
2999            "healthy parquet must not be molested"
3000        );
3001    }
3002
3003    #[test]
3004    fn test_load_all_events_skips_zero_byte_parquet() {
3005        // Issue #166 defensive layer: a single bad file must not abort
3006        // the whole load. With t-d8b1's match-and-continue, the healthy
3007        // events still come back and the bad file is logged-and-skipped.
3008        let temp_dir = TempDir::new().unwrap();
3009        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3010
3011        // Two healthy events, flushed.
3012        for i in 0..2 {
3013            storage
3014                .append_event(event_with_tenant("alice", &format!("a-{i}")))
3015                .unwrap();
3016        }
3017        storage.flush().unwrap();
3018
3019        // Now drop a 0-byte parquet alongside (sneaking it in AFTER
3020        // construction so cleanup_partial_writes doesn't rename it
3021        // before we get to test the load path).
3022        let healthy_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
3023        let bricked = healthy_files[0]
3024            .parent()
3025            .unwrap()
3026            .join("events-bricked-cafef00d.parquet");
3027        std::fs::write(&bricked, b"").unwrap();
3028
3029        let loaded = storage.load_all_events().unwrap();
3030        assert_eq!(
3031            loaded.len(),
3032            2,
3033            "all healthy events should still load despite the 0-byte file"
3034        );
3035    }
3036
3037    #[test]
3038    fn test_load_events_for_tenant_skips_zero_byte_parquet() {
3039        // Same defensive layer for the lazy-load path. A bad file in
3040        // the tenant subtree must not poison subsequent queries.
3041        let temp_dir = TempDir::new().unwrap();
3042        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3043
3044        for i in 0..3 {
3045            storage
3046                .append_event(event_with_tenant("alice", &format!("a-{i}")))
3047                .unwrap();
3048        }
3049        storage.flush().unwrap();
3050
3051        let healthy = find_parquet_files_recursive(temp_dir.path()).unwrap();
3052        let bricked = healthy[0]
3053            .parent()
3054            .unwrap()
3055            .join("events-bricked-feedface.parquet");
3056        std::fs::write(&bricked, b"").unwrap();
3057
3058        let events = storage.load_events_for_tenant("alice").unwrap();
3059        assert_eq!(events.len(), 3, "lazy load must skip the 0-byte file");
3060    }
3061
3062    #[test]
3063    fn test_flush_tenant_leaves_no_zero_byte_parquet_after_normal_flush() {
3064        // Direct verification of t-c1d3: a successful flush_tenant
3065        // leaves exactly one healthy *.parquet — no .tmp survivors,
3066        // no 0-byte files.
3067        let temp_dir = TempDir::new().unwrap();
3068        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3069
3070        for i in 0..5 {
3071            storage
3072                .append_event(event_with_tenant("alice", &format!("a-{i}")))
3073                .unwrap();
3074        }
3075        storage.flush().unwrap();
3076
3077        let mut tmp_count = 0;
3078        let mut zero_byte_count = 0;
3079        let mut healthy_count = 0;
3080        let mut stack = vec![temp_dir.path().to_path_buf()];
3081        while let Some(d) = stack.pop() {
3082            for entry in std::fs::read_dir(&d).unwrap().flatten() {
3083                let p = entry.path();
3084                if p.is_dir() {
3085                    stack.push(p);
3086                    continue;
3087                }
3088                let name = p.file_name().unwrap().to_string_lossy().into_owned();
3089                if name.ends_with(".parquet.tmp") {
3090                    tmp_count += 1;
3091                } else if name.ends_with(".parquet") {
3092                    if std::fs::metadata(&p).unwrap().len() == 0 {
3093                        zero_byte_count += 1;
3094                    } else {
3095                        healthy_count += 1;
3096                    }
3097                }
3098            }
3099        }
3100        assert_eq!(tmp_count, 0, ".parquet.tmp survivors after flush");
3101        assert_eq!(zero_byte_count, 0, "0-byte .parquet survivors after flush");
3102        assert_eq!(healthy_count, 1, "expected exactly one healthy parquet");
3103    }
3104
3105    #[test]
3106    fn test_new_calls_cleanup_partial_writes_on_boot() {
3107        // Drop a stale .tmp into a directory, then construct a
3108        // fresh ParquetStorage on it. The constructor must clean
3109        // it up.
3110        let temp_dir = TempDir::new().unwrap();
3111        let stale = temp_dir.path().join("orphan.parquet.tmp");
3112        std::fs::write(&stale, b"crash detritus").unwrap();
3113        assert!(stale.is_file());
3114
3115        let _storage = ParquetStorage::new(temp_dir.path()).unwrap();
3116        assert!(
3117            !stale.exists(),
3118            "stale tmp should have been cleaned by ParquetStorage::new"
3119        );
3120    }
3121
3122    // -----------------------------------------------------------------
3123    // Migration tests (Step 1, commit #3: flat → tenant-tree migration).
3124    // -----------------------------------------------------------------
3125
3126    /// Helper: produce a flat-layout Parquet file at the storage root,
3127    /// matching what pre-#2 deploys wrote. Uses the existing flush path
3128    /// briefly and then relocates the resulting file from
3129    /// default/<yyyy-mm>/ back up to the root, simulating the legacy
3130    /// state.
3131    fn seed_flat_layout_file(storage: &ParquetStorage, count: usize) -> PathBuf {
3132        for i in 0..count {
3133            storage
3134                .append_event(create_test_event(&format!("entity-{i}")))
3135                .unwrap();
3136        }
3137        storage.flush().unwrap();
3138
3139        // create_test_event uses tenant="default", so the just-flushed file
3140        // landed under <root>/default/<yyyy-mm>/. Find the newest file in
3141        // that subtree to avoid picking up files from other tenants seeded
3142        // by the test before us.
3143        let default_subtree = storage.storage_dir().join("default");
3144        let candidates = find_parquet_files_recursive(&default_subtree).unwrap();
3145        assert!(
3146            !candidates.is_empty(),
3147            "seed expected at least one file under default/"
3148        );
3149        let src = candidates.into_iter().max().unwrap();
3150
3151        let dst = storage.storage_dir().join(src.file_name().unwrap());
3152        std::fs::rename(&src, &dst).unwrap();
3153        // Best-effort cleanup of the now-empty intermediate dirs so the
3154        // migration tool only sees the flat file. (`remove_dir` succeeds
3155        // only on empty dirs, which is exactly the safety we want here.)
3156        if let Some(month_dir) = src.parent() {
3157            let _ = std::fs::remove_dir(month_dir);
3158            if let Some(tenant_dir) = month_dir.parent() {
3159                let _ = std::fs::remove_dir(tenant_dir);
3160            }
3161        }
3162        dst
3163    }
3164
3165    #[test]
3166    fn test_migrate_flat_layout_dry_run_touches_nothing() {
3167        let temp_dir = TempDir::new().unwrap();
3168        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3169        let flat = seed_flat_layout_file(&storage, 7);
3170        assert!(flat.is_file(), "test setup: flat file should exist");
3171
3172        let report = storage.migrate_flat_layout(true).unwrap();
3173        assert!(report.dry_run);
3174        assert_eq!(report.flat_files_seen, 1);
3175        assert_eq!(report.events_migrated, 7);
3176        assert_eq!(report.flat_files_removed, 0);
3177        assert_eq!(report.partitions_written, 0);
3178        assert!(
3179            flat.is_file(),
3180            "flat file must still be present after dry run"
3181        );
3182    }
3183
3184    #[test]
3185    fn test_migrate_flat_layout_moves_events_into_default_tree_and_removes_flat() {
3186        let temp_dir = TempDir::new().unwrap();
3187        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3188        let flat = seed_flat_layout_file(&storage, 5);
3189
3190        let report = storage.migrate_flat_layout(false).unwrap();
3191        assert!(!report.dry_run);
3192        assert_eq!(report.flat_files_seen, 1);
3193        assert_eq!(report.flat_files_removed, 1);
3194        assert_eq!(report.events_migrated, 5);
3195        assert!(report.partitions_written >= 1);
3196        assert!(
3197            !flat.exists(),
3198            "flat file should be deleted after migration"
3199        );
3200
3201        let post = find_parquet_files_recursive(temp_dir.path()).unwrap();
3202        assert!(
3203            post.iter().all(|p| {
3204                let rel = p
3205                    .strip_prefix(temp_dir.path())
3206                    .unwrap()
3207                    .to_string_lossy()
3208                    .into_owned();
3209                rel.starts_with(&format!("default{}", std::path::MAIN_SEPARATOR))
3210            }),
3211            "all migrated files should be under default/"
3212        );
3213
3214        let loaded = storage.load_all_events().unwrap();
3215        assert_eq!(loaded.len(), 5);
3216    }
3217
3218    #[test]
3219    fn test_migrate_flat_layout_is_idempotent_when_re_run_after_completion() {
3220        let temp_dir = TempDir::new().unwrap();
3221        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3222        let _flat = seed_flat_layout_file(&storage, 4);
3223
3224        let first = storage.migrate_flat_layout(false).unwrap();
3225        assert_eq!(first.events_migrated, 4);
3226
3227        // Second run sees no flat files at the root, so it's a no-op —
3228        // events do not duplicate even if an operator runs the tool twice.
3229        let second = storage.migrate_flat_layout(false).unwrap();
3230        assert_eq!(second.flat_files_seen, 0);
3231        assert_eq!(second.events_migrated, 0);
3232        assert_eq!(second.flat_files_removed, 0);
3233
3234        let loaded = storage.load_all_events().unwrap();
3235        assert_eq!(loaded.len(), 4, "rerun must not duplicate or lose events");
3236    }
3237
3238    #[test]
3239    fn test_migrate_flat_layout_ignores_already_partitioned_data() {
3240        // Mixed state: a tenant tree already exists alongside one flat file.
3241        // Migration must touch only the flat file.
3242        let temp_dir = TempDir::new().unwrap();
3243        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3244
3245        for i in 0..3 {
3246            storage
3247                .append_event(event_with_tenant("alice", &format!("a-{i}")))
3248                .unwrap();
3249        }
3250        storage.flush().unwrap();
3251
3252        let _flat = seed_flat_layout_file(&storage, 2);
3253
3254        let report = storage.migrate_flat_layout(false).unwrap();
3255        assert_eq!(report.flat_files_seen, 1, "only the flat file is in scope");
3256        assert_eq!(report.events_migrated, 2);
3257
3258        let alice_files = find_parquet_files_recursive(&temp_dir.path().join("alice")).unwrap();
3259        assert_eq!(alice_files.len(), 1, "alice's tree must be untouched");
3260
3261        let loaded = storage.load_all_events().unwrap();
3262        assert_eq!(loaded.len(), 5);
3263        let alice_count = loaded
3264            .iter()
3265            .filter(|e| e.tenant_id_str() == "alice")
3266            .count();
3267        let default_count = loaded
3268            .iter()
3269            .filter(|e| e.tenant_id_str() == "default")
3270            .count();
3271        assert_eq!(alice_count, 3);
3272        assert_eq!(default_count, 2);
3273    }
3274
3275    #[test]
3276    fn test_migrate_flat_layout_with_no_flat_files_is_a_clean_noop() {
3277        let temp_dir = TempDir::new().unwrap();
3278        let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3279        let report = storage.migrate_flat_layout(false).unwrap();
3280        assert_eq!(report.flat_files_seen, 0);
3281        assert_eq!(report.events_migrated, 0);
3282    }
3283}