Skip to main content

allsource_core/infrastructure/persistence/
storage.rs

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