Skip to main content

allsource_core/infrastructure/persistence/
storage.rs

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