Skip to main content

allsource_core/infrastructure/persistence/
storage.rs

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