Skip to main content

allsource_core/infrastructure/persistence/
storage.rs

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