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