1#[path = "storage_feed.rs"]
2mod feed;
3#[path = "storage_retained_entity.rs"]
4mod retained_entity;
5
6use super::{
7 archive_budget::{ArchiveReadBudget, ArchiveReadLimits},
8 archive_output::{
9 ArchiveOutput, PublishedPart, pending_marker, pending_part, recover_pending_outputs,
10 },
11 event_codec::{
12 self, ENTITY_ID_COLUMN, VALID_FROM_COLUMN, VALID_TO_COLUMN, VERSION_COLUMN, event_schema,
13 },
14 version_manifest::{ResolvedVersion, VersionManifest},
15};
16use crate::{
17 domain::entities::Event,
18 error::{AllSourceError, Result},
19 infrastructure::memory::ledger::{Owner, Tally},
20};
21use arrow::{
22 array::{Array, TimestampMicrosecondArray},
23 datatypes::Schema,
24 record_batch::RecordBatch,
25};
26use std::{
27 collections::HashMap,
28 fs::{self, File},
29 path::{Path, PathBuf},
30 sync::{
31 Arc, Mutex,
32 atomic::{AtomicU64, Ordering},
33 },
34 time::{Duration, Instant},
35};
36
37pub(super) fn decoded_text_bytes(batch: &RecordBatch) -> u64 {
43 ["payload", "metadata"]
44 .iter()
45 .filter_map(|name| {
46 let column = batch.schema().index_of(name).ok()?;
47 batch
48 .column(column)
49 .as_any()
50 .downcast_ref::<arrow::array::StringArray>()
51 })
52 .map(|values| values.value_data().len() as u64)
53 .sum()
54}
55
56fn optional_timestamp_column<'a>(
58 batch: &'a RecordBatch,
59 name: &str,
60) -> Result<Option<&'a TimestampMicrosecondArray>> {
61 let Ok(index) = batch.schema().index_of(name) else {
62 return Ok(None);
63 };
64 batch
65 .column(index)
66 .as_any()
67 .downcast_ref::<TimestampMicrosecondArray>()
68 .map(Some)
69 .ok_or_else(|| AllSourceError::StorageError(format!("Invalid {name} column")))
70}
71
72fn valid_time_at(
73 column: Option<&TimestampMicrosecondArray>,
74 row: usize,
75) -> Result<Option<chrono::DateTime<chrono::Utc>>> {
76 match column {
77 Some(values) if values.is_valid(row) => {
78 chrono::DateTime::from_timestamp_micros(values.value(row))
79 .map(Some)
80 .ok_or_else(|| AllSourceError::StorageError("Invalid valid time".to_string()))
81 }
82 _ => Ok(None),
83 }
84}
85
86pub const DEFAULT_BATCH_SIZE: usize = 10_000;
88
89pub const DEFAULT_FLUSH_TIMEOUT_MS: u64 = 5_000;
91
92#[derive(Clone)]
96pub struct FileNamer(Arc<dyn Fn(&str, chrono::DateTime<chrono::Utc>) -> String + Send + Sync>);
97
98impl FileNamer {
99 pub fn new(
100 name: impl Fn(&str, chrono::DateTime<chrono::Utc>) -> String + Send + Sync + 'static,
101 ) -> Self {
102 Self(Arc::new(name))
103 }
104}
105
106impl std::fmt::Debug for FileNamer {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.write_str("FileNamer")
109 }
110}
111
112#[derive(Debug, Clone)]
114pub struct ParquetStorageConfig {
115 pub batch_size: usize,
117 pub flush_timeout: Duration,
119 pub compression: parquet::basic::Compression,
121 pub file_namer: Option<FileNamer>,
123}
124
125impl Default for ParquetStorageConfig {
126 fn default() -> Self {
127 Self {
128 batch_size: DEFAULT_BATCH_SIZE,
129 flush_timeout: Duration::from_millis(DEFAULT_FLUSH_TIMEOUT_MS),
130 compression: parquet::basic::Compression::SNAPPY,
131 file_namer: None,
132 }
133 }
134}
135
136impl ParquetStorageConfig {
137 pub fn high_throughput() -> Self {
139 Self {
140 batch_size: 50_000,
141 flush_timeout: Duration::from_secs(10),
142 compression: parquet::basic::Compression::SNAPPY,
143 file_namer: None,
144 }
145 }
146
147 pub fn low_latency() -> Self {
149 Self {
150 batch_size: 1_000,
151 flush_timeout: Duration::from_secs(1),
152 compression: parquet::basic::Compression::SNAPPY,
153 file_namer: None,
154 }
155 }
156}
157
158#[derive(Debug, Clone, Default)]
160pub struct BatchWriteStats {
161 pub batches_written: u64,
163 pub events_written: u64,
165 pub bytes_written: u64,
167 pub avg_batch_size: f64,
169 pub events_per_sec: f64,
171 pub total_write_time_ns: u64,
173 pub timeout_flushes: u64,
175 pub size_flushes: u64,
177}
178
179#[derive(Debug, Clone)]
181pub struct BatchWriteResult {
182 pub events_written: usize,
184 pub batches_flushed: usize,
186 pub duration: Duration,
188 pub events_per_sec: f64,
190}
191
192pub struct ParquetStorage {
201 storage_dir: PathBuf,
203
204 current_batches: Mutex<HashMap<String, Vec<Event>>>,
213 pending: Tally,
215
216 config: ParquetStorageConfig,
218
219 schema: Arc<Schema>,
221
222 last_flush_time: Mutex<Instant>,
224
225 batches_written: AtomicU64,
227 events_written: AtomicU64,
228 bytes_written: AtomicU64,
229 total_write_time_ns: AtomicU64,
230 timeout_flushes: AtomicU64,
231 size_flushes: AtomicU64,
232}
233
234impl ParquetStorage {
235 pub fn new(storage_dir: impl AsRef<Path>) -> Result<Self> {
237 Self::with_config(storage_dir, ParquetStorageConfig::default())
238 }
239
240 pub fn with_config(
242 storage_dir: impl AsRef<Path>,
243 config: ParquetStorageConfig,
244 ) -> Result<Self> {
245 Self::open(storage_dir, config, true)
246 }
247
248 pub(crate) fn open_existing(storage_dir: impl AsRef<Path>) -> Result<Self> {
249 Self::open(storage_dir, ParquetStorageConfig::default(), false)
250 }
251
252 fn open(
253 storage_dir: impl AsRef<Path>,
254 config: ParquetStorageConfig,
255 recover: bool,
256 ) -> Result<Self> {
257 let storage_dir = storage_dir.as_ref().to_path_buf();
258
259 fs::create_dir_all(&storage_dir).map_err(|e| {
261 AllSourceError::StorageError(format!("Failed to create storage directory: {e}"))
262 })?;
263
264 let schema = event_schema();
265
266 let storage = Self {
267 storage_dir,
268 current_batches: Mutex::new(HashMap::new()),
269 pending: Tally::new(Owner::StoragePending),
270 config,
271 schema,
272 last_flush_time: Mutex::new(Instant::now()),
273 batches_written: AtomicU64::new(0),
274 events_written: AtomicU64::new(0),
275 bytes_written: AtomicU64::new(0),
276 total_write_time_ns: AtomicU64::new(0),
277 timeout_flushes: AtomicU64::new(0),
278 size_flushes: AtomicU64::new(0),
279 };
280
281 if recover {
286 match storage.cleanup_partial_writes() {
287 Ok(0) => {}
288 Ok(n) => tracing::warn!(
289 "cleanup_partial_writes acted on {n} crash-detritus file(s) on boot — \
290 see preceding logs for per-file detail"
291 ),
292 Err(e) => tracing::error!("cleanup_partial_writes failed on boot: {e}"),
293 }
294 }
295
296 Ok(storage)
297 }
298
299 #[deprecated(note = "Use new() or with_config() instead - default batch size is now 10,000")]
301 pub fn with_legacy_batch_size(storage_dir: impl AsRef<Path>) -> Result<Self> {
302 Self::with_config(
303 storage_dir,
304 ParquetStorageConfig {
305 batch_size: 1000,
306 ..Default::default()
307 },
308 )
309 }
310
311 #[cfg_attr(feature = "hotpath", hotpath::measure)]
321 pub fn append_event(&self, event: Event) -> Result<()> {
322 let tenant = event.tenant_id_str().to_string();
323 self.pending.add(event.resident_bytes());
324 let should_flush_tenant = {
325 let mut batches = self.current_batches.lock().unwrap();
326 let entry = batches.entry(tenant.clone()).or_default();
327 entry.push(event);
328 entry.len() >= self.config.batch_size
329 };
330
331 if should_flush_tenant {
332 self.size_flushes.fetch_add(1, Ordering::Relaxed);
333 self.flush_tenant(&tenant)?;
334 }
335
336 Ok(())
337 }
338
339 #[cfg_attr(feature = "hotpath", hotpath::measure)]
345 pub fn batch_write(&self, events: Vec<Event>) -> Result<BatchWriteResult> {
346 let start = Instant::now();
347 let event_count = events.len();
348
349 let mut grouped: HashMap<String, Vec<Event>> = HashMap::new();
352 for event in events {
353 self.pending.add(event.resident_bytes());
354 grouped
355 .entry(event.tenant_id_str().to_string())
356 .or_default()
357 .push(event);
358 }
359
360 let mut tenants_to_flush: Vec<String> = Vec::new();
361 {
362 let mut batches = self.current_batches.lock().unwrap();
363 for (tenant, mut new_events) in grouped {
364 let entry = batches.entry(tenant.clone()).or_default();
365 entry.append(&mut new_events);
366 if entry.len() >= self.config.batch_size {
367 tenants_to_flush.push(tenant);
368 }
369 }
370 }
371
372 let mut batches_flushed = 0;
373 for tenant in tenants_to_flush {
374 self.size_flushes.fetch_add(1, Ordering::Relaxed);
375 self.flush_tenant(&tenant)?;
376 batches_flushed += 1;
377 }
378
379 let duration = start.elapsed();
380
381 Ok(BatchWriteResult {
382 events_written: event_count,
383 batches_flushed,
384 duration,
385 events_per_sec: event_count as f64 / duration.as_secs_f64(),
386 })
387 }
388
389 #[cfg_attr(feature = "hotpath", hotpath::measure)]
397 pub fn check_timeout_flush(&self) -> Result<bool> {
398 let should_flush = {
399 let last_flush = self.last_flush_time.lock().unwrap();
400 let batches = self.current_batches.lock().unwrap();
401 let any_pending = batches.values().any(|v| !v.is_empty());
402 any_pending && last_flush.elapsed() >= self.config.flush_timeout
403 };
404
405 if should_flush {
406 self.timeout_flushes.fetch_add(1, Ordering::Relaxed);
407 self.flush()?;
408 Ok(true)
409 } else {
410 Ok(false)
411 }
412 }
413
414 #[cfg_attr(feature = "hotpath", hotpath::measure)]
421 pub fn flush(&self) -> Result<()> {
422 let tenants: Vec<String> = {
423 let batches = self.current_batches.lock().unwrap();
424 batches
425 .iter()
426 .filter(|(_, v)| !v.is_empty())
427 .map(|(k, _)| k.clone())
428 .collect()
429 };
430 if tenants.is_empty() {
431 return Ok(());
432 }
433 for tenant in tenants {
434 self.flush_tenant(&tenant)?;
435 }
436 Ok(())
437 }
438
439 pub(crate) fn has_pending_tenant_events(&self, tenant_id: &str) -> bool {
442 self.current_batches
443 .lock()
444 .unwrap()
445 .get(tenant_id)
446 .is_some_and(|events| !events.is_empty())
447 }
448
449 fn flush_tenant(&self, tenant_id: &str) -> Result<()> {
464 let events_to_write = {
465 let mut batches = self.current_batches.lock().unwrap();
466 match batches.get_mut(tenant_id) {
467 Some(v) if !v.is_empty() => std::mem::take(v),
468 _ => return Ok(()),
469 }
470 };
471
472 let batch_count = events_to_write.len();
473 let start = Instant::now();
474
475 let written = self.write_tenant_events(tenant_id, &events_to_write);
476 let parts = match written {
477 Ok(written) => written,
478 Err(e) => {
479 let mut batches = self.current_batches.lock().unwrap();
482 let pending = batches.entry(tenant_id.to_string()).or_default();
483 let arrived_during_write = std::mem::replace(pending, events_to_write);
484 pending.extend(arrived_during_write);
485 return Err(e);
486 }
487 };
488
489 let duration = start.elapsed();
490 self.pending
491 .sub(events_to_write.iter().map(Event::resident_bytes).sum());
492
493 let mut offset = 0;
498 for part in &parts {
499 let rows = usize::try_from(part.metadata.file_metadata().num_rows())
500 .map_err(|_| AllSourceError::StorageError("Invalid archive output rows".into()))?;
501 if let Err(error) = self.record_flushed_versions(
502 tenant_id,
503 &part.path,
504 &events_to_write[offset..offset + rows],
505 ) {
506 tracing::warn!(tenant_id, %error, "could not update tenant version manifest");
507 }
508 offset += rows;
509 }
510
511 self.batches_written.fetch_add(1, Ordering::Relaxed);
512 self.events_written
513 .fetch_add(batch_count as u64, Ordering::Relaxed);
514 let bytes = parts
515 .iter()
516 .flat_map(|part| part.metadata.row_groups())
517 .map(|group| group.total_byte_size() as u64)
518 .sum();
519 self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
520 self.total_write_time_ns
521 .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed);
522
523 {
524 let mut last_flush = self.last_flush_time.lock().unwrap();
525 *last_flush = Instant::now();
526 }
527
528 tracing::info!(
529 "Wrote {} events for tenant={} to {} files in {:?}",
530 batch_count,
531 tenant_id,
532 parts.len(),
533 duration
534 );
535
536 Ok(())
537 }
538
539 fn write_tenant_events(&self, tenant_id: &str, events: &[Event]) -> Result<Vec<PublishedPart>> {
540 let record_batch = self.events_to_record_batch(events)?;
541
542 let now = chrono::Utc::now();
543 let partition_dir = partition_path_for_tenant(&self.storage_dir, tenant_id, now)?;
544 fs::create_dir_all(&partition_dir).map_err(|e| {
545 AllSourceError::StorageError(format!(
546 "Failed to create tenant partition {}: {e}",
547 partition_dir.display()
548 ))
549 })?;
550 let file_stem = match &self.config.file_namer {
551 Some(FileNamer(name)) => name(tenant_id, now),
552 None => format!(
553 "events-{}-{}",
554 now.format("%Y%m%d-%H%M%S%3f"),
555 uuid::Uuid::new_v4().as_simple()
556 ),
557 };
558
559 tracing::info!(
560 "Flushing {} events for tenant={} to {}/{}.parquet",
561 events.len(),
562 tenant_id,
563 partition_dir.display(),
564 file_stem
565 );
566
567 let mut output = ArchiveOutput::new(
568 &partition_dir,
569 &file_stem,
570 self.config.compression,
571 ArchiveReadLimits::default().max_file_bytes,
572 true,
573 )?;
574 output.stage(&record_batch)?;
575 output.publish()
576 }
577
578 fn write_record_batch_atomic(
595 &self,
596 partition_dir: &Path,
597 file_stem: &str,
598 record_batch: &RecordBatch,
599 ) -> Result<(PathBuf, parquet::file::metadata::ParquetMetaData)> {
600 let mut output = ArchiveOutput::new(
601 partition_dir,
602 file_stem,
603 self.config.compression,
604 ArchiveReadLimits::default().max_file_bytes,
605 false,
606 )?;
607 output.stage(record_batch)?;
608 let part = output
609 .publish()?
610 .pop()
611 .ok_or_else(|| AllSourceError::StorageError("Archive output missing".into()))?;
612 Ok((part.path, part.metadata))
613 }
614
615 pub fn write_atomic_parquet(
639 &self,
640 tenant_id: &str,
641 file_stem: &str,
642 events: &[Event],
643 ) -> Result<PathBuf> {
644 if events.is_empty() {
645 return Err(AllSourceError::StorageError(
646 "write_atomic_parquet called with empty event slice".to_string(),
647 ));
648 }
649 let anchor_ts = events
654 .iter()
655 .map(|e| e.timestamp)
656 .min()
657 .unwrap_or_else(chrono::Utc::now);
658 let partition_dir = partition_path_for_tenant(&self.storage_dir, tenant_id, anchor_ts)?;
659 fs::create_dir_all(&partition_dir).map_err(|e| {
660 AllSourceError::StorageError(format!(
661 "Failed to create tenant partition {}: {e}",
662 partition_dir.display()
663 ))
664 })?;
665
666 let record_batch = self.events_to_record_batch(events)?;
667 let (final_path, _meta) =
668 self.write_record_batch_atomic(&partition_dir, file_stem, &record_batch)?;
669
670 tracing::info!(
671 tenant_id = tenant_id,
672 file = %final_path.display(),
673 event_count = events.len(),
674 "wrote atomic snapshot file"
675 );
676
677 Ok(final_path)
678 }
679
680 pub(crate) fn write_atomic_parquet_parts(
681 &self,
682 tenant_id: &str,
683 file_stem: &str,
684 events: &[Event],
685 ) -> Result<Vec<PathBuf>> {
686 if events.is_empty() {
687 return Err(AllSourceError::StorageError(
688 "Cannot archive empty events".into(),
689 ));
690 }
691 let anchor = events
692 .iter()
693 .map(|event| event.timestamp)
694 .min()
695 .ok_or_else(|| AllSourceError::StorageError("Cannot archive empty events".into()))?;
696 let directory = partition_path_for_tenant(&self.storage_dir, tenant_id, anchor)?;
697 fs::create_dir_all(&directory).map_err(|error| {
698 AllSourceError::StorageError(format!("Failed to create archive partition: {error}"))
699 })?;
700 let batch = self.events_to_record_batch(events)?;
701 let mut output = ArchiveOutput::new(
702 &directory,
703 file_stem,
704 self.config.compression,
705 ArchiveReadLimits::default().max_file_bytes,
706 true,
707 )?;
708 output.stage(&batch)?;
709 Ok(output
710 .publish()?
711 .into_iter()
712 .map(|part| part.path)
713 .collect())
714 }
715
716 pub fn cleanup_partial_writes(&self) -> Result<usize> {
739 let mut acted = 0usize;
740 let mut stack: Vec<PathBuf> = vec![self.storage_dir.clone()];
741 while let Some(dir) = stack.pop() {
742 acted += recover_pending_outputs(&dir)?;
743 let Ok(entries) = fs::read_dir(&dir) else {
744 continue;
745 };
746 for entry in entries.flatten() {
747 let path = entry.path();
748 let Ok(ft) = entry.file_type() else { continue };
749 if ft.is_dir() {
750 stack.push(path);
751 continue;
752 }
753 if !ft.is_file() {
754 continue;
755 }
756 let path_str = path.to_string_lossy();
757 if path_str.ends_with(".parquet.tmp") {
758 match fs::remove_file(&path) {
759 Ok(()) => {
760 tracing::warn!(
761 file = %path.display(),
762 "cleaned up orphan snapshot tmp file (crash recovery)"
763 );
764 acted += 1;
765 }
766 Err(e) => {
767 tracing::error!(
768 file = %path.display(),
769 "failed to remove orphan snapshot tmp file: {e}"
770 );
771 }
772 }
773 } else if path_str.ends_with(".parquet")
774 && fs::metadata(&path).is_ok_and(|m| m.len() == 0)
775 {
776 let ts = chrono::Utc::now().timestamp();
780 let quarantine_path = path.with_extension(format!("parquet.corrupt-{ts}"));
781 match fs::rename(&path, &quarantine_path) {
782 Ok(()) => {
783 tracing::error!(
784 from = %path.display(),
785 to = %quarantine_path.display(),
786 "quarantined 0-byte parquet file (issue #166 pre-fix crash). \
787 Operator: inspect and rm if not needed."
788 );
789 acted += 1;
790 }
791 Err(e) => {
792 tracing::error!(
793 file = %path.display(),
794 "failed to quarantine 0-byte parquet file: {e}"
795 );
796 }
797 }
798 }
799 }
800 }
801 Ok(acted)
802 }
803
804 #[cfg_attr(feature = "hotpath", hotpath::measure)]
810 pub fn flush_on_shutdown(&self) -> Result<usize> {
811 let total_pending: usize = {
812 let batches = self.current_batches.lock().unwrap();
813 batches.values().map(Vec::len).sum()
814 };
815
816 if total_pending > 0 {
817 tracing::info!(
818 "Shutdown: flushing {} pending events across all tenants",
819 total_pending
820 );
821 self.flush()?;
822 }
823
824 Ok(total_pending)
825 }
826
827 pub fn batch_stats(&self) -> BatchWriteStats {
829 let batches = self.batches_written.load(Ordering::Relaxed);
830 let events = self.events_written.load(Ordering::Relaxed);
831 let bytes = self.bytes_written.load(Ordering::Relaxed);
832 let time_ns = self.total_write_time_ns.load(Ordering::Relaxed);
833
834 let time_secs = time_ns as f64 / 1_000_000_000.0;
835
836 BatchWriteStats {
837 batches_written: batches,
838 events_written: events,
839 bytes_written: bytes,
840 avg_batch_size: if batches > 0 {
841 events as f64 / batches as f64
842 } else {
843 0.0
844 },
845 events_per_sec: if time_secs > 0.0 {
846 events as f64 / time_secs
847 } else {
848 0.0
849 },
850 total_write_time_ns: time_ns,
851 timeout_flushes: self.timeout_flushes.load(Ordering::Relaxed),
852 size_flushes: self.size_flushes.load(Ordering::Relaxed),
853 }
854 }
855
856 pub fn pending_count(&self) -> usize {
858 self.current_batches
859 .lock()
860 .unwrap()
861 .values()
862 .map(Vec::len)
863 .sum()
864 }
865
866 pub fn batch_size(&self) -> usize {
868 self.config.batch_size
869 }
870
871 pub fn flush_timeout(&self) -> Duration {
873 self.config.flush_timeout
874 }
875
876 fn events_to_record_batch(&self, events: &[Event]) -> Result<RecordBatch> {
877 event_codec::events_to_record_batch(&self.schema, events)
878 }
879
880 #[cfg_attr(feature = "hotpath", hotpath::measure)]
887 pub fn load_all_events(&self) -> Result<Vec<Event>> {
888 let parquet_files = find_parquet_files_recursive(&self.storage_dir)?;
889
890 let mut all_events = Vec::with_capacity(parquet_files.len() * self.config.batch_size);
891 let mut skipped = 0usize;
892 for file_path in parquet_files {
893 tracing::info!("Loading events from {}", file_path.display());
894 let tenant_id = tenant_id_from_path(&self.storage_dir, &file_path);
895 match self.load_events_from_file(&file_path, &tenant_id) {
900 Ok(file_events) => all_events.extend(file_events),
901 Err(e) => {
902 tracing::error!(
903 file = %file_path.display(),
904 error = %e,
905 "Skipping unreadable parquet file — other files will still load. \
906 Likely a 0-byte or truncated file from an unclean shutdown; \
907 inspect and remove manually after confirming."
908 );
909 skipped += 1;
910 }
911 }
912 }
913
914 if skipped > 0 {
915 tracing::warn!(
916 "Loaded {} events from storage; skipped {} unreadable file(s)",
917 all_events.len(),
918 skipped
919 );
920 } else {
921 tracing::info!("Loaded {} total events from storage", all_events.len());
922 }
923
924 Ok(all_events)
925 }
926
927 #[cfg_attr(feature = "hotpath", hotpath::measure)]
933 fn load_events_from_file(&self, file_path: &Path, tenant_id: &str) -> Result<Vec<Event>> {
934 self.load_events_from_file_with_budget(file_path, tenant_id, None)
935 }
936
937 fn load_events_from_file_with_budget(
938 &self,
939 file_path: &Path,
940 tenant_id: &str,
941 mut budget: Option<&mut ArchiveReadBudget>,
942 ) -> Result<Vec<Event>> {
943 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
944
945 if let Some(budget) = budget.as_deref() {
946 budget.check()?;
947 }
948 let file = File::open(file_path).map_err(|e| {
949 AllSourceError::StorageError(format!("Failed to open parquet file: {e}"))
950 })?;
951
952 if let Some(budget) = budget.as_deref_mut() {
953 let metadata = file.metadata().map_err(|error| {
954 AllSourceError::StorageError(format!("Failed to inspect archive file: {error}"))
955 })?;
956 budget.compressed(metadata.len())?;
957 }
958 let mut builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
959 if let Some(budget) = budget.as_deref_mut() {
960 for group in builder.metadata().row_groups() {
964 budget.rows(group.num_rows())?;
965 }
966 builder = builder.with_batch_size(256);
967 }
968 let reader = builder.build()?;
969
970 let mut events = Vec::new();
971
972 for batch in reader {
973 if let Some(budget) = budget.as_deref() {
974 budget.check()?;
975 }
976 let batch = batch?;
977 if let Some(budget) = budget.as_deref_mut() {
978 budget.decoded_payload(decoded_text_bytes(&batch))?;
979 }
980 let batch_events = self.record_batch_to_events(&batch, tenant_id)?;
981 events.extend(batch_events);
982 }
983
984 if let Some(budget) = budget {
985 budget.check()?;
986 }
987
988 Ok(events)
989 }
990
991 pub fn load_entity_events_for_tenant(
1008 &self,
1009 tenant_id: &str,
1010 entity_id: &str,
1011 ) -> Result<(Vec<Event>, usize)> {
1012 let files = self.list_parquet_files_for_tenant(tenant_id)?;
1013 let mut events = Vec::new();
1014 let mut skipped = 0usize;
1015 for file_path in &files {
1016 match self.load_entity_events_from_file(file_path, tenant_id, entity_id) {
1017 Ok(matches) => events.extend(matches),
1018 Err(error) => {
1019 tracing::error!(
1020 tenant_id = tenant_id,
1021 file = %file_path.display(),
1022 error = %error,
1023 "Unreadable parquet file in entity-scoped archive read"
1024 );
1025 skipped += 1;
1026 }
1027 }
1028 }
1029 tracing::info!(
1030 tenant_id = tenant_id,
1031 entity_id = entity_id,
1032 file_count = files.len(),
1033 matched = events.len(),
1034 skipped_files = skipped,
1035 "entity-scoped archive read complete"
1036 );
1037 Ok((events, skipped))
1038 }
1039
1040 fn load_entity_events_from_file(
1043 &self,
1044 file_path: &Path,
1045 tenant_id: &str,
1046 entity_id: &str,
1047 ) -> Result<Vec<Event>> {
1048 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
1049
1050 let file = File::open(file_path).map_err(|error| unreadable(file_path, error))?;
1051 let builder =
1052 ParquetRecordBatchReaderBuilder::try_new(file).map_err(|e| unreadable(file_path, e))?;
1053 let needle = entity_id.as_bytes();
1054 let groups: Vec<usize> = builder
1055 .metadata()
1056 .row_groups()
1057 .iter()
1058 .enumerate()
1059 .filter(|(_, group)| row_group_may_hold_entity(group, needle))
1060 .map(|(index, _)| index)
1061 .collect();
1062 if groups.is_empty() {
1063 return Ok(Vec::new());
1064 }
1065
1066 let reader = builder
1067 .with_row_groups(groups)
1068 .with_batch_size(256)
1069 .build()
1070 .map_err(|error| unreadable(file_path, error))?;
1071
1072 let mut events = Vec::new();
1073 for batch in reader {
1074 let batch = batch.map_err(|error| unreadable(file_path, error))?;
1075 for event in self.record_batch_to_events(&batch, tenant_id)? {
1078 if event.entity_id_str() == entity_id {
1079 events.push(event);
1080 }
1081 }
1082 }
1083 Ok(events)
1084 }
1085
1086 pub fn load_events_from_file_path(
1092 &self,
1093 file_path: &Path,
1094 tenant_id: &str,
1095 ) -> Result<Vec<Event>> {
1096 self.load_events_from_file(file_path, tenant_id)
1097 }
1098
1099 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1103 fn record_batch_to_events(&self, batch: &RecordBatch, tenant_id: &str) -> Result<Vec<Event>> {
1104 crate::infrastructure::memory::ledger::resident()
1105 .record_rows_decoded(batch.num_rows() as u64);
1106 let event_ids = batch
1107 .column(0)
1108 .as_any()
1109 .downcast_ref::<arrow::array::StringArray>()
1110 .ok_or_else(|| AllSourceError::StorageError("Invalid event_id column".to_string()))?;
1111
1112 let event_types = batch
1113 .column(1)
1114 .as_any()
1115 .downcast_ref::<arrow::array::StringArray>()
1116 .ok_or_else(|| AllSourceError::StorageError("Invalid event_type column".to_string()))?;
1117
1118 let entity_ids = batch
1119 .column(2)
1120 .as_any()
1121 .downcast_ref::<arrow::array::StringArray>()
1122 .ok_or_else(|| AllSourceError::StorageError("Invalid entity_id column".to_string()))?;
1123
1124 let payloads = batch
1125 .column(3)
1126 .as_any()
1127 .downcast_ref::<arrow::array::StringArray>()
1128 .ok_or_else(|| AllSourceError::StorageError("Invalid payload column".to_string()))?;
1129
1130 let timestamps = batch
1131 .column(4)
1132 .as_any()
1133 .downcast_ref::<TimestampMicrosecondArray>()
1134 .ok_or_else(|| AllSourceError::StorageError("Invalid timestamp column".to_string()))?;
1135
1136 let metadatas = batch
1137 .column(5)
1138 .as_any()
1139 .downcast_ref::<arrow::array::StringArray>()
1140 .ok_or_else(|| AllSourceError::StorageError("Invalid metadata column".to_string()))?;
1141
1142 let versions = batch
1143 .column(6)
1144 .as_any()
1145 .downcast_ref::<arrow::array::UInt64Array>()
1146 .ok_or_else(|| AllSourceError::StorageError("Invalid version column".to_string()))?;
1147
1148 let valid_froms = optional_timestamp_column(batch, VALID_FROM_COLUMN)?;
1149 let valid_tos = optional_timestamp_column(batch, VALID_TO_COLUMN)?;
1150
1151 let mut events = Vec::new();
1152
1153 for i in 0..batch.num_rows() {
1154 let id = uuid::Uuid::parse_str(event_ids.value(i))
1155 .map_err(|e| AllSourceError::StorageError(format!("Invalid UUID: {e}")))?;
1156
1157 let timestamp = chrono::DateTime::from_timestamp_micros(timestamps.value(i))
1158 .ok_or_else(|| AllSourceError::StorageError("Invalid timestamp".to_string()))?;
1159
1160 let metadata = if metadatas.is_null(i) {
1161 None
1162 } else {
1163 Some(serde_json::from_str(metadatas.value(i))?)
1164 };
1165
1166 let mut event = Event::reconstruct_from_strings(
1167 id,
1168 event_types.value(i).to_string(),
1169 entity_ids.value(i).to_string(),
1170 tenant_id.to_string(),
1171 serde_json::from_str(payloads.value(i))?,
1172 timestamp,
1173 metadata,
1174 versions.value(i) as i64,
1175 );
1176 event.valid_from = valid_time_at(valid_froms, i)?;
1177 event.valid_to = valid_time_at(valid_tos, i)?;
1178
1179 events.push(event);
1180 }
1181
1182 Ok(events)
1183 }
1184
1185 pub fn list_parquet_files(&self) -> Result<Vec<PathBuf>> {
1191 find_parquet_files_recursive(&self.storage_dir)
1192 }
1193
1194 pub fn tenant_id_for_file(&self, file_path: &Path) -> String {
1196 tenant_id_from_path(&self.storage_dir, file_path)
1197 }
1198
1199 pub fn list_parquet_files_for_tenant(&self, tenant_id: &str) -> Result<Vec<PathBuf>> {
1212 let safe = sanitize_tenant_id_for_path(tenant_id)?;
1213 let tenant_root = self.storage_dir.join(safe);
1214 if !tenant_root.is_dir() {
1215 return Ok(Vec::new());
1216 }
1217 find_parquet_files_recursive(&tenant_root)
1218 }
1219
1220 pub fn tenant_archive_bytes(&self, tenant_id: &str) -> Result<(u64, usize)> {
1229 let files = self.list_parquet_files_for_tenant(tenant_id)?;
1230 let count = files.len();
1231 let bytes = files
1232 .iter()
1233 .filter_map(|path| std::fs::metadata(path).ok())
1234 .map(|metadata| metadata.len())
1235 .sum();
1236 Ok((bytes, count))
1237 }
1238
1239 fn list_complete_tenant_archive(
1240 &self,
1241 tenant_id: &str,
1242 budget: &mut ArchiveReadBudget,
1243 ) -> Result<Vec<PathBuf>> {
1244 budget.check()?;
1245 let safe = sanitize_tenant_id_for_path(tenant_id)?;
1246 let root = self.storage_dir.join(safe);
1247 match fs::symlink_metadata(&root) {
1248 Ok(metadata) if metadata.is_dir() => {
1249 find_parquet_files_recursive_with_integrity(&root, Some(budget))
1250 }
1251 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
1252 _ => Err(AllSourceError::StorageError(
1253 "Cannot verify conditional version: tenant archive is not an accessible directory"
1254 .into(),
1255 )),
1256 }
1257 }
1258
1259 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1278 pub fn load_events_for_tenant(&self, tenant_id: &str) -> Result<Vec<Event>> {
1279 self.load_events_for_tenant_with_integrity(tenant_id, None)
1280 .map(|(events, _complete)| events)
1281 }
1282
1283 pub(crate) fn resolve_entity_version(
1299 &self,
1300 tenant_id: &str,
1301 entity_id: &str,
1302 budget: &mut ArchiveReadBudget,
1303 ) -> Result<ResolvedVersion> {
1304 let files = self.list_complete_tenant_archive(tenant_id, budget)?;
1305 let tenant_dir = self
1306 .storage_dir
1307 .join(sanitize_tenant_id_for_path(tenant_id)?);
1308 let mut manifest = VersionManifest::load(&tenant_dir).unwrap_or_default();
1309
1310 let outstanding: Vec<PathBuf> = files
1311 .into_iter()
1312 .filter(|path| {
1313 manifest_key(&tenant_dir, path).is_none_or(|key| !manifest.covered.contains(&key))
1314 })
1315 .collect();
1316
1317 if outstanding.is_empty() {
1318 return Ok(ResolvedVersion::Complete(manifest.version_of(entity_id)));
1319 }
1320
1321 let mut folded = 0usize;
1322 let mut exhausted = None;
1323 for path in &outstanding {
1324 if let Err(error) = self.fold_entity_versions(path, &mut manifest.entities, budget) {
1326 exhausted = Some(error);
1327 break;
1328 }
1329 if let Some(key) = manifest_key(&tenant_dir, path) {
1330 manifest.covered.insert(key);
1331 }
1332 folded += 1;
1333 }
1334
1335 if folded > 0 {
1337 manifest.store(&tenant_dir)?;
1338 }
1339
1340 if let Some(error) = exhausted {
1341 let remaining = outstanding.len() - folded;
1342 if is_budget_exhaustion(&error) {
1346 return Ok(ResolvedVersion::Incomplete {
1347 remaining,
1348 reason: error.to_string(),
1349 });
1350 }
1351 return Err(error);
1352 }
1353
1354 Ok(ResolvedVersion::Complete(manifest.version_of(entity_id)))
1355 }
1356
1357 pub(crate) fn record_flushed_versions(
1360 &self,
1361 tenant_id: &str,
1362 file: &Path,
1363 events: &[Event],
1364 ) -> Result<()> {
1365 let tenant_dir = self
1366 .storage_dir
1367 .join(sanitize_tenant_id_for_path(tenant_id)?);
1368 let Some(key) = manifest_key(&tenant_dir, file) else {
1369 return Ok(());
1370 };
1371 let mut manifest = VersionManifest::load(&tenant_dir).unwrap_or_default();
1372 manifest.observe_file(&key, events);
1373 manifest.store(&tenant_dir)
1374 }
1375
1376 fn fold_entity_versions(
1385 &self,
1386 file_path: &Path,
1387 versions: &mut HashMap<String, u64>,
1388 budget: &mut ArchiveReadBudget,
1389 ) -> Result<()> {
1390 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
1391
1392 budget.check()?;
1393 let file = File::open(file_path).map_err(|e| {
1394 AllSourceError::StorageError(format!("Failed to open parquet file: {e}"))
1395 })?;
1396 let file_len = file
1397 .metadata()
1398 .map_err(|error| {
1399 AllSourceError::StorageError(format!("Failed to inspect archive file: {error}"))
1400 })?
1401 .len();
1402 budget.compressed(file_len)?;
1403
1404 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
1405 .map_err(|error| unreadable(file_path, error))?;
1406
1407 for group in builder.metadata().row_groups() {
1410 let retained: i64 = [ENTITY_ID_COLUMN, VERSION_COLUMN]
1411 .iter()
1412 .map(|&column| group.column(column).uncompressed_size())
1413 .sum();
1414 budget.decoded_metadata(group.num_rows(), retained)?;
1415 }
1416
1417 let reader = builder
1418 .with_batch_size(1024)
1419 .build()
1420 .map_err(|error| unreadable(file_path, error))?;
1421
1422 for batch in reader {
1423 budget.check()?;
1424 let batch = batch.map_err(|error| unreadable(file_path, error))?;
1425 let entity_ids = batch
1426 .column(ENTITY_ID_COLUMN)
1427 .as_any()
1428 .downcast_ref::<arrow::array::StringArray>()
1429 .ok_or_else(|| {
1430 AllSourceError::StorageError("Invalid entity_id column".to_string())
1431 })?;
1432 let row_versions = batch
1433 .column(VERSION_COLUMN)
1434 .as_any()
1435 .downcast_ref::<arrow::array::UInt64Array>()
1436 .ok_or_else(|| {
1437 AllSourceError::StorageError("Invalid version column".to_string())
1438 })?;
1439
1440 for i in 0..batch.num_rows() {
1441 let version = row_versions.value(i);
1442 versions
1443 .entry(entity_ids.value(i).to_string())
1444 .and_modify(|current| *current = (*current).max(version))
1445 .or_insert(version);
1446 }
1447 }
1448
1449 Ok(())
1450 }
1451
1452 pub(crate) fn load_events_for_tenant_with_integrity(
1453 &self,
1454 tenant_id: &str,
1455 budget: Option<&mut ArchiveReadBudget>,
1456 ) -> Result<(Vec<Event>, bool)> {
1457 let mut events = Vec::new();
1458 let complete = self.for_each_tenant_file_events(tenant_id, budget, |batch| {
1459 events.extend(batch);
1460 Ok(())
1461 })?;
1462 Ok((events, complete))
1463 }
1464
1465 pub(crate) fn for_each_tenant_file_events(
1477 &self,
1478 tenant_id: &str,
1479 mut budget: Option<&mut ArchiveReadBudget>,
1480 mut visit: impl FnMut(Vec<Event>) -> Result<()>,
1481 ) -> Result<bool> {
1482 let require_complete = budget.is_some();
1483 let parquet_files = if let Some(budget) = budget.as_deref_mut() {
1484 self.list_complete_tenant_archive(tenant_id, budget)?
1485 } else {
1486 self.list_parquet_files_for_tenant(tenant_id)?
1487 };
1488 tracing::info!(
1489 tenant_id = tenant_id,
1490 file_count = parquet_files.len(),
1491 "load_events_for_tenant: walking tenant subtree only"
1492 );
1493
1494 let mut visited = 0usize;
1495 let mut skipped = 0usize;
1496 for file_path in parquet_files {
1497 tracing::debug!(
1498 tenant_id = tenant_id,
1499 file = %file_path.display(),
1500 "load_events_for_tenant: opening file"
1501 );
1502 match self.load_events_from_file_with_budget(
1507 &file_path,
1508 tenant_id,
1509 budget.as_deref_mut(),
1510 ) {
1511 Ok(file_events) => {
1512 visited += file_events.len();
1513 visit(file_events)?;
1514 }
1515 Err(e) => {
1516 tracing::error!(
1517 tenant_id = tenant_id,
1518 file = %file_path.display(),
1519 error = %e,
1520 require_complete,
1521 "Unreadable parquet file in tenant subtree"
1522 );
1523 skipped += 1;
1524 if require_complete {
1525 if let Some(budget) = budget.as_deref() {
1526 budget.check()?;
1527 }
1528 if is_budget_exhaustion(&e) {
1529 return Err(e);
1530 }
1531 return Err(AllSourceError::StorageError(format!(
1532 "Cannot verify conditional version from incomplete archive: {e}"
1533 )));
1534 }
1535 }
1536 }
1537 }
1538
1539 tracing::info!(
1540 tenant_id = tenant_id,
1541 event_count = visited,
1542 skipped_files = skipped,
1543 "load_events_for_tenant: complete"
1544 );
1545 Ok(require_complete && skipped == 0)
1548 }
1549
1550 pub fn storage_dir(&self) -> &Path {
1552 &self.storage_dir
1553 }
1554
1555 pub fn migrate_flat_layout(&self, dry_run: bool) -> Result<MigrationReport> {
1578 let flat_files = list_flat_layout_files(&self.storage_dir)?;
1579 let mut report = MigrationReport {
1580 dry_run,
1581 ..Default::default()
1582 };
1583
1584 for flat_file in flat_files {
1585 let events = self.load_events_from_file(&flat_file, "default")?;
1589 report.flat_files_seen += 1;
1590
1591 if events.is_empty() {
1592 if !dry_run {
1594 fs::remove_file(&flat_file).map_err(|e| {
1595 AllSourceError::StorageError(format!(
1596 "Failed to remove empty flat file {}: {e}",
1597 flat_file.display()
1598 ))
1599 })?;
1600 }
1601 report.flat_files_removed += 1;
1602 continue;
1603 }
1604
1605 let mut groups: HashMap<(String, String), Vec<Event>> = HashMap::new();
1611 for event in events {
1612 let key = (
1613 event.tenant_id_str().to_string(),
1614 event.timestamp().format("%Y-%m").to_string(),
1615 );
1616 groups.entry(key).or_default().push(event);
1617 }
1618
1619 for ((tenant, yyyy_mm), group_events) in groups {
1620 let count = group_events.len();
1621 if !dry_run {
1622 let safe_tenant = sanitize_tenant_id_for_path(&tenant)?;
1623 let target_dir = self.storage_dir.join(safe_tenant).join(&yyyy_mm);
1624 fs::create_dir_all(&target_dir).map_err(|e| {
1625 AllSourceError::StorageError(format!(
1626 "Failed to create partition {}: {e}",
1627 target_dir.display()
1628 ))
1629 })?;
1630 let filename = format!(
1631 "events-{}-{}.parquet",
1632 chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"),
1633 uuid::Uuid::new_v4().as_simple()
1634 );
1635 let record_batch = self.events_to_record_batch(&group_events)?;
1636 let mut output = ArchiveOutput::new(
1637 &target_dir,
1638 filename.trim_end_matches(".parquet"),
1639 self.config.compression,
1640 ArchiveReadLimits::default().max_file_bytes,
1641 true,
1642 )?;
1643 output.stage(&record_batch)?;
1644 report.partitions_written += output.publish()?.len();
1645 }
1646 report.events_migrated += count;
1647 }
1648
1649 if !dry_run {
1650 fs::remove_file(&flat_file).map_err(|e| {
1651 AllSourceError::StorageError(format!(
1652 "Failed to remove flat file {} after migration: {e}",
1653 flat_file.display()
1654 ))
1655 })?;
1656 report.flat_files_removed += 1;
1657 }
1658 }
1659
1660 Ok(report)
1661 }
1662
1663 pub fn stats(&self) -> Result<StorageStats> {
1665 let parquet_files = find_parquet_files_recursive(&self.storage_dir)?;
1666 let mut total_size_bytes = 0u64;
1667 for path in &parquet_files {
1668 if let Ok(metadata) = fs::metadata(path) {
1669 total_size_bytes += metadata.len();
1670 }
1671 }
1672
1673 let current_batch_size: usize = self
1674 .current_batches
1675 .lock()
1676 .unwrap()
1677 .values()
1678 .map(Vec::len)
1679 .sum();
1680
1681 Ok(StorageStats {
1682 total_files: parquet_files.len(),
1683 total_size_bytes,
1684 storage_dir: self.storage_dir.clone(),
1685 current_batch_size,
1686 })
1687 }
1688}
1689
1690fn sanitize_tenant_id_for_path(tenant_id: &str) -> Result<&str> {
1703 if tenant_id.is_empty() {
1704 return Err(AllSourceError::StorageError(
1705 "tenant_id is empty (cannot derive partition path)".to_string(),
1706 ));
1707 }
1708 if tenant_id.len() > 128 {
1709 return Err(AllSourceError::StorageError(format!(
1710 "tenant_id is too long for partition path: {} bytes (max 128)",
1711 tenant_id.len()
1712 )));
1713 }
1714 if tenant_id == "." || tenant_id == ".." {
1715 return Err(AllSourceError::StorageError(format!(
1716 "tenant_id {tenant_id:?} is reserved"
1717 )));
1718 }
1719 for c in tenant_id.chars() {
1720 let ok = c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.';
1721 if !ok {
1722 return Err(AllSourceError::StorageError(format!(
1723 "tenant_id {tenant_id:?} contains disallowed character {c:?} for partition path"
1724 )));
1725 }
1726 }
1727 Ok(tenant_id)
1728}
1729
1730fn unreadable(path: &Path, error: impl std::fmt::Display) -> AllSourceError {
1733 AllSourceError::StorageError(format!(
1734 "Cannot verify conditional version from {}: {error}",
1735 path.display()
1736 ))
1737}
1738
1739fn row_group_may_hold_entity(
1750 group: &parquet::file::metadata::RowGroupMetaData,
1751 needle: &[u8],
1752) -> bool {
1753 let Some(statistics) = group.column(ENTITY_ID_COLUMN).statistics() else {
1754 return true;
1755 };
1756 let (Some(min), Some(max)) = (statistics.min_bytes_opt(), statistics.max_bytes_opt()) else {
1757 return true;
1758 };
1759 min <= needle && needle <= max
1760}
1761
1762fn manifest_key(tenant_dir: &Path, file: &Path) -> Option<String> {
1768 Some(
1769 file.strip_prefix(tenant_dir)
1770 .ok()?
1771 .to_string_lossy()
1772 .into_owned(),
1773 )
1774}
1775
1776fn is_budget_exhaustion(error: &AllSourceError) -> bool {
1779 matches!(error, AllSourceError::ArchiveBudgetExceeded { .. })
1780}
1781
1782fn partition_path_for_tenant(
1787 root: &Path,
1788 tenant_id: &str,
1789 when: chrono::DateTime<chrono::Utc>,
1790) -> Result<PathBuf> {
1791 let safe = sanitize_tenant_id_for_path(tenant_id)?;
1792 Ok(root.join(safe).join(when.format("%Y-%m").to_string()))
1793}
1794
1795fn tenant_id_from_path(root: &Path, file_path: &Path) -> String {
1805 let Ok(rel) = file_path.strip_prefix(root) else {
1806 return "default".to_string();
1807 };
1808 let mut comps = rel.components();
1809 let first = comps.next();
1810 let next = comps.next();
1811 match (first, next) {
1812 (Some(std::path::Component::Normal(tenant)), Some(_)) => {
1814 tenant.to_string_lossy().into_owned()
1815 }
1816 _ => "default".to_string(),
1818 }
1819}
1820
1821fn list_flat_layout_files(root: &Path) -> Result<Vec<PathBuf>> {
1827 let entries = fs::read_dir(root).map_err(|e| {
1828 AllSourceError::StorageError(format!("Failed to read storage directory: {e}"))
1829 })?;
1830 let mut out: Vec<PathBuf> = entries
1831 .filter_map(std::result::Result::ok)
1832 .filter_map(|entry| {
1833 let ft = entry.file_type().ok()?;
1834 if !ft.is_file() {
1835 return None;
1836 }
1837 let path = entry.path();
1838 if path.extension().and_then(|s| s.to_str()) == Some("parquet") {
1839 Some(path)
1840 } else {
1841 None
1842 }
1843 })
1844 .collect();
1845 out.sort();
1846 Ok(out)
1847}
1848
1849fn find_parquet_files_recursive(root: &Path) -> Result<Vec<PathBuf>> {
1860 find_parquet_files_recursive_with_integrity(root, None)
1861}
1862
1863fn find_parquet_files_recursive_with_integrity(
1864 root: &Path,
1865 mut budget: Option<&mut ArchiveReadBudget>,
1866) -> Result<Vec<PathBuf>> {
1867 let require_complete = budget.is_some();
1868 let mut out = Vec::new();
1869 let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
1870
1871 while let Some(dir) = stack.pop() {
1872 if let Some(budget) = budget.as_deref() {
1873 budget.check()?;
1874 }
1875 let entries = match fs::read_dir(&dir) {
1876 Ok(e) => e,
1877 Err(e) if dir == root || require_complete => {
1881 return Err(AllSourceError::StorageError(format!(
1882 "Failed to read storage directory: {e}"
1883 )));
1884 }
1885 Err(_) => continue,
1886 };
1887
1888 for entry in entries {
1889 if let Some(budget) = budget.as_deref_mut() {
1890 budget.entry()?;
1891 }
1892 let entry = match entry {
1893 Ok(entry) => entry,
1894 Err(error) if require_complete => {
1895 return Err(AllSourceError::StorageError(format!(
1896 "Failed to enumerate complete archive: {error}"
1897 )));
1898 }
1899 Err(_) => continue,
1900 };
1901 let path = entry.path();
1902 if pending_marker(&path) && require_complete {
1903 return Err(AllSourceError::StorageError(
1904 "Archive output publication incomplete".into(),
1905 ));
1906 }
1907 let ft = match entry.file_type() {
1911 Ok(file_type) => file_type,
1912 Err(error) if require_complete => {
1913 return Err(AllSourceError::StorageError(format!(
1914 "Failed to inspect complete archive entry: {error}"
1915 )));
1916 }
1917 Err(_) => continue,
1918 };
1919 if ft.is_dir() {
1920 stack.push(path);
1921 } else if ft.is_file() && pending_part(&path) {
1922 if require_complete {
1923 return Err(AllSourceError::StorageError(
1924 "Archive output publication incomplete".into(),
1925 ));
1926 }
1927 } else if ft.is_file()
1928 && path
1929 .extension()
1930 .and_then(|ext| ext.to_str())
1931 .is_some_and(|ext| ext == "parquet")
1932 {
1933 if let Some(budget) = budget.as_deref_mut() {
1934 budget.file()?;
1935 }
1936 out.push(path);
1937 }
1938 }
1939 }
1940
1941 out.sort();
1942 if let Some(budget) = budget {
1943 budget.check()?;
1944 }
1945 Ok(out)
1946}
1947
1948impl Drop for ParquetStorage {
1949 fn drop(&mut self) {
1950 if let Err(e) = self.flush_on_shutdown() {
1952 tracing::error!("Failed to flush events on drop: {}", e);
1953 }
1954 }
1955}
1956
1957#[derive(Debug, Default, Clone, serde::Serialize)]
1959pub struct MigrationReport {
1960 pub dry_run: bool,
1962 pub flat_files_seen: usize,
1964 pub flat_files_removed: usize,
1966 pub partitions_written: usize,
1968 pub events_migrated: usize,
1970}
1971
1972#[derive(Debug, serde::Serialize)]
1973pub struct StorageStats {
1974 pub total_files: usize,
1975 pub total_size_bytes: u64,
1976 pub storage_dir: PathBuf,
1977 pub current_batch_size: usize,
1978}
1979
1980#[cfg(test)]
1981mod tests {
1982 use super::*;
1983 use arrow::datatypes::{DataType, Field, TimeUnit};
1984 use serde_json::json;
1985 use std::sync::Arc;
1986 use tempfile::TempDir;
1987
1988 fn create_test_event(entity_id: &str) -> Event {
1989 Event::reconstruct_from_strings(
1990 uuid::Uuid::new_v4(),
1991 "test.event".to_string(),
1992 entity_id.to_string(),
1993 "default".to_string(),
1994 json!({
1995 "test": "data",
1996 "value": 42
1997 }),
1998 chrono::Utc::now(),
1999 None,
2000 1,
2001 )
2002 }
2003
2004 #[test]
2005 fn valid_time_round_trips_through_parquet() {
2006 let temp_dir = TempDir::new().unwrap();
2007 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2008 let valid_from = chrono::DateTime::from_timestamp_micros(1_700_000_000_123_456).unwrap();
2009 let valid_to = chrono::DateTime::from_timestamp_micros(1_700_000_900_000_001).unwrap();
2010
2011 let mut event = create_test_event("entity-valid");
2012 event.valid_from = Some(valid_from);
2013 event.valid_to = Some(valid_to);
2014 let mut open_ended = create_test_event("entity-open");
2015 open_ended.valid_from = Some(valid_from);
2016 storage.append_event(event).unwrap();
2017 storage.append_event(open_ended).unwrap();
2018 storage.flush().unwrap();
2019
2020 let mut loaded = storage.load_all_events().unwrap();
2021 loaded.sort_by(|a, b| a.entity_id_str().cmp(b.entity_id_str()));
2022 assert_eq!(loaded.len(), 2);
2023 assert_eq!(loaded[0].entity_id_str(), "entity-open");
2024 assert_eq!(loaded[0].valid_from, Some(valid_from));
2025 assert_eq!(loaded[0].valid_to, None);
2026 assert_eq!(loaded[1].valid_from, Some(valid_from));
2027 assert_eq!(loaded[1].valid_to, Some(valid_to));
2028 }
2029
2030 #[test]
2033 fn a_parquet_file_without_valid_time_columns_reads_back_unset() {
2034 use arrow::array::{StringArray, TimestampMicrosecondArray, UInt64Array};
2035 use parquet::arrow::ArrowWriter;
2036
2037 let temp_dir = TempDir::new().unwrap();
2038 let path = temp_dir.path().join("pre-valid-time.parquet");
2039 let ids = [
2040 uuid::Uuid::new_v4().to_string(),
2041 uuid::Uuid::new_v4().to_string(),
2042 ];
2043 let timestamps = [1_700_000_000_000_000_i64, 1_700_000_100_000_000_i64];
2044 let schema = Arc::new(Schema::new(vec![
2045 Field::new("event_id", DataType::Utf8, false),
2046 Field::new("event_type", DataType::Utf8, false),
2047 Field::new("entity_id", DataType::Utf8, false),
2048 Field::new("payload", DataType::Utf8, false),
2049 Field::new(
2050 "timestamp",
2051 DataType::Timestamp(TimeUnit::Microsecond, None),
2052 false,
2053 ),
2054 Field::new("metadata", DataType::Utf8, true),
2055 Field::new("version", DataType::UInt64, false),
2056 ]));
2057 let batch = RecordBatch::try_new(
2058 schema.clone(),
2059 vec![
2060 Arc::new(StringArray::from(vec![ids[0].as_str(), ids[1].as_str()])),
2061 Arc::new(StringArray::from(vec!["test.event", "test.event"])),
2062 Arc::new(StringArray::from(vec!["entity-a", "entity-b"])),
2063 Arc::new(StringArray::from(vec!["{}", "{}"])),
2064 Arc::new(TimestampMicrosecondArray::from(timestamps.to_vec())),
2065 Arc::new(StringArray::from(vec![None::<&str>, None])),
2066 Arc::new(UInt64Array::from(vec![1_u64, 2])),
2067 ],
2068 )
2069 .unwrap();
2070 let mut writer = ArrowWriter::try_new(File::create(&path).unwrap(), schema, None).unwrap();
2071 writer.write(&batch).unwrap();
2072 writer.close().unwrap();
2073
2074 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2075 let loaded = storage
2076 .load_events_from_file_path(&path, "default")
2077 .unwrap();
2078
2079 assert_eq!(loaded.len(), 2);
2080 assert_eq!(loaded[0].id.to_string(), ids[0]);
2081 assert_eq!(loaded[0].timestamp.timestamp_micros(), timestamps[0]);
2082 assert_eq!(loaded[0].valid_from, None);
2083 assert_eq!(loaded[0].valid_to, None);
2084 assert_eq!(loaded[1].valid_from, None);
2085 assert_eq!(loaded[1].valid_to, None);
2086 }
2087
2088 #[test]
2089 fn test_parquet_storage_write_read() {
2090 let temp_dir = TempDir::new().unwrap();
2091 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2092
2093 for i in 0..10 {
2095 let event = create_test_event(&format!("entity-{i}"));
2096 storage.append_event(event).unwrap();
2097 }
2098
2099 storage.flush().unwrap();
2101
2102 let loaded_events = storage.load_all_events().unwrap();
2104 assert_eq!(loaded_events.len(), 10);
2105 }
2106
2107 #[test]
2108 fn test_storage_stats() {
2109 let temp_dir = TempDir::new().unwrap();
2110 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2111
2112 for i in 0..5 {
2114 storage
2115 .append_event(create_test_event(&format!("entity-{i}")))
2116 .unwrap();
2117 }
2118 storage.flush().unwrap();
2119
2120 let stats = storage.stats().unwrap();
2121 assert_eq!(stats.total_files, 1);
2122 assert!(stats.total_size_bytes > 0);
2123 }
2124
2125 #[test]
2126 fn test_default_batch_size() {
2127 let temp_dir = TempDir::new().unwrap();
2128 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2129
2130 assert_eq!(storage.batch_size(), DEFAULT_BATCH_SIZE);
2132 assert_eq!(storage.batch_size(), 10_000);
2133 }
2134
2135 #[test]
2136 fn test_custom_config() {
2137 let temp_dir = TempDir::new().unwrap();
2138 let config = ParquetStorageConfig {
2139 batch_size: 5_000,
2140 flush_timeout: Duration::from_secs(2),
2141 compression: parquet::basic::Compression::SNAPPY,
2142 file_namer: None,
2143 };
2144 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2145
2146 assert_eq!(storage.batch_size(), 5_000);
2147 assert_eq!(storage.flush_timeout(), Duration::from_secs(2));
2148 }
2149
2150 #[test]
2151 fn test_batch_write() {
2152 let temp_dir = TempDir::new().unwrap();
2153 let config = ParquetStorageConfig {
2154 batch_size: 100, ..Default::default()
2156 };
2157 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2158
2159 let events: Vec<Event> = (0..250)
2167 .map(|i| create_test_event(&format!("entity-{i}")))
2168 .collect();
2169
2170 let result = storage.batch_write(events).unwrap();
2171 assert_eq!(result.events_written, 250);
2172 assert_eq!(result.batches_flushed, 1);
2173 assert_eq!(storage.pending_count(), 0);
2174
2175 storage.flush().unwrap();
2177
2178 let loaded = storage.load_all_events().unwrap();
2180 assert_eq!(loaded.len(), 250);
2181 }
2182
2183 #[test]
2184 fn test_auto_flush_on_batch_size() {
2185 let temp_dir = TempDir::new().unwrap();
2186 let config = ParquetStorageConfig {
2187 batch_size: 10, ..Default::default()
2189 };
2190 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2191
2192 for i in 0..15 {
2194 storage
2195 .append_event(create_test_event(&format!("entity-{i}")))
2196 .unwrap();
2197 }
2198
2199 assert_eq!(storage.pending_count(), 5);
2201
2202 let stats = storage.batch_stats();
2203 assert_eq!(stats.events_written, 10);
2204 assert_eq!(stats.batches_written, 1);
2205 assert_eq!(stats.size_flushes, 1);
2206 }
2207
2208 #[test]
2209 fn test_flush_on_shutdown() {
2210 let temp_dir = TempDir::new().unwrap();
2211 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2212
2213 for i in 0..5 {
2215 storage
2216 .append_event(create_test_event(&format!("entity-{i}")))
2217 .unwrap();
2218 }
2219
2220 assert_eq!(storage.pending_count(), 5);
2221
2222 let flushed = storage.flush_on_shutdown().unwrap();
2224 assert_eq!(flushed, 5);
2225 assert_eq!(storage.pending_count(), 0);
2226
2227 let loaded = storage.load_all_events().unwrap();
2229 assert_eq!(loaded.len(), 5);
2230 }
2231
2232 #[test]
2233 fn test_thread_safe_writes() {
2234 let temp_dir = TempDir::new().unwrap();
2235 let config = ParquetStorageConfig {
2236 batch_size: 100,
2237 ..Default::default()
2238 };
2239 let storage = Arc::new(ParquetStorage::with_config(temp_dir.path(), config).unwrap());
2240
2241 let events_per_thread = 50;
2242 let thread_count = 4;
2243
2244 std::thread::scope(|s| {
2245 for t in 0..thread_count {
2246 let storage_ref = Arc::clone(&storage);
2247 s.spawn(move || {
2248 for i in 0..events_per_thread {
2249 let event = create_test_event(&format!("thread-{t}-entity-{i}"));
2250 storage_ref.append_event(event).unwrap();
2251 }
2252 });
2253 }
2254 });
2255
2256 storage.flush().unwrap();
2258
2259 let loaded = storage.load_all_events().unwrap();
2261 assert_eq!(loaded.len(), events_per_thread * thread_count);
2262 }
2263
2264 #[test]
2265 fn test_batch_stats() {
2266 let temp_dir = TempDir::new().unwrap();
2267 let config = ParquetStorageConfig {
2268 batch_size: 50,
2269 ..Default::default()
2270 };
2271 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2272
2273 let events: Vec<Event> = (0..100)
2278 .map(|i| create_test_event(&format!("entity-{i}")))
2279 .collect();
2280
2281 storage.batch_write(events).unwrap();
2282
2283 let stats = storage.batch_stats();
2284 assert_eq!(stats.batches_written, 1);
2285 assert_eq!(stats.events_written, 100);
2286 assert!(stats.avg_batch_size > 0.0);
2287 assert!(stats.events_per_sec > 0.0);
2288 assert_eq!(stats.size_flushes, 1);
2289 }
2290
2291 #[test]
2292 fn test_config_presets() {
2293 let high_throughput = ParquetStorageConfig::high_throughput();
2294 assert_eq!(high_throughput.batch_size, 50_000);
2295 assert_eq!(high_throughput.flush_timeout, Duration::from_secs(10));
2296
2297 let low_latency = ParquetStorageConfig::low_latency();
2298 assert_eq!(low_latency.batch_size, 1_000);
2299 assert_eq!(low_latency.flush_timeout, Duration::from_secs(1));
2300
2301 let default = ParquetStorageConfig::default();
2302 assert_eq!(default.batch_size, DEFAULT_BATCH_SIZE);
2303 assert_eq!(default.batch_size, 10_000);
2304 }
2305
2306 #[test]
2309 #[ignore]
2310 fn test_batch_write_throughput() {
2311 let temp_dir = TempDir::new().unwrap();
2312 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2313
2314 let event_count = 50_000;
2315
2316 let events: Vec<Event> = (0..event_count)
2318 .map(|i| create_test_event(&format!("entity-{i}")))
2319 .collect();
2320
2321 let start = std::time::Instant::now();
2322 let result = storage.batch_write(events).unwrap();
2323 storage.flush().unwrap(); let batch_duration = start.elapsed();
2325
2326 let batch_stats = storage.batch_stats();
2327
2328 println!("\n=== Parquet Batch Write Performance (BATCH_SIZE=10,000) ===");
2329 println!("Events: {event_count}");
2330 println!("Duration: {batch_duration:?}");
2331 println!("Events/sec: {:.0}", result.events_per_sec);
2332 println!("Batches written: {}", batch_stats.batches_written);
2333 println!("Avg batch size: {:.0}", batch_stats.avg_batch_size);
2334 println!("Bytes written: {} KB", batch_stats.bytes_written / 1024);
2335
2336 assert!(
2339 result.events_per_sec > 10_000.0,
2340 "Batch write throughput too low: {:.0} events/sec (expected >10K in debug, >100K in release)",
2341 result.events_per_sec
2342 );
2343 }
2344
2345 #[test]
2347 #[ignore]
2348 fn test_single_event_write_baseline() {
2349 let temp_dir = TempDir::new().unwrap();
2350 let config = ParquetStorageConfig {
2351 batch_size: 1, ..Default::default()
2353 };
2354 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2355
2356 let event_count = 1_000; let start = std::time::Instant::now();
2359 for i in 0..event_count {
2360 let event = create_test_event(&format!("entity-{i}"));
2361 storage.append_event(event).unwrap();
2362 }
2363 let duration = start.elapsed();
2364
2365 let events_per_sec = f64::from(event_count) / duration.as_secs_f64();
2366
2367 println!("\n=== Single-Event Write Baseline ===");
2368 println!("Events: {event_count}");
2369 println!("Duration: {duration:?}");
2370 println!("Events/sec: {events_per_sec:.0}");
2371
2372 }
2375
2376 fn touch_parquet(path: &Path) {
2386 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2387 std::fs::write(path, b"").unwrap();
2388 }
2389
2390 #[test]
2391 fn test_walker_finds_files_in_flat_layout() {
2392 let temp_dir = TempDir::new().unwrap();
2393 let root = temp_dir.path();
2394 touch_parquet(&root.join("events-20260101-120000000-aaaa.parquet"));
2395 touch_parquet(&root.join("events-20260101-130000000-bbbb.parquet"));
2396
2397 let mut found = find_parquet_files_recursive(root).unwrap();
2398 found.sort();
2399 assert_eq!(found.len(), 2);
2400 assert!(
2401 found[0]
2402 .file_name()
2403 .unwrap()
2404 .to_str()
2405 .unwrap()
2406 .starts_with("events-"),
2407 "expected events-* file, got {found:?}"
2408 );
2409 }
2410
2411 #[test]
2412 fn test_walker_finds_files_in_tenant_partitioned_tree() {
2413 let temp_dir = TempDir::new().unwrap();
2414 let root = temp_dir.path();
2415 touch_parquet(&root.join("tenant-a/2026-01/events-20260101-120000000-aaaa.parquet"));
2417 touch_parquet(&root.join("tenant-a/2026-02/events-20260201-120000000-bbbb.parquet"));
2418 touch_parquet(&root.join("tenant-b/2026-01/events-20260103-120000000-cccc.parquet"));
2419
2420 let found = find_parquet_files_recursive(root).unwrap();
2421 assert_eq!(found.len(), 3);
2422 assert!(found[0].to_str().unwrap().contains("tenant-a"));
2425 assert!(found[1].to_str().unwrap().contains("tenant-a"));
2426 assert!(found[2].to_str().unwrap().contains("tenant-b"));
2427 }
2428
2429 #[test]
2430 fn test_walker_handles_mixed_legacy_and_partitioned_layouts() {
2431 let temp_dir = TempDir::new().unwrap();
2436 let root = temp_dir.path();
2437 touch_parquet(&root.join("events-legacy-aaaa.parquet"));
2438 touch_parquet(&root.join("tenant-a/2026-01/events-new-bbbb.parquet"));
2439
2440 let found = find_parquet_files_recursive(root).unwrap();
2441 assert_eq!(found.len(), 2);
2442 }
2443
2444 #[test]
2445 fn test_walker_ignores_non_parquet_files() {
2446 let temp_dir = TempDir::new().unwrap();
2447 let root = temp_dir.path();
2448 std::fs::write(root.join("README.md"), b"hello").unwrap();
2449 std::fs::write(root.join("events.json"), b"[]").unwrap();
2450 touch_parquet(&root.join("events-20260101-120000000-aaaa.parquet"));
2451 std::fs::write(root.join("not-a-parquet-file.bin"), b"").unwrap();
2454
2455 let found = find_parquet_files_recursive(root).unwrap();
2456 assert_eq!(found.len(), 1);
2457 assert_eq!(
2458 found[0].extension().and_then(|s| s.to_str()),
2459 Some("parquet")
2460 );
2461 }
2462
2463 fn event_with_tenant(tenant: &str, entity_id: &str) -> Event {
2467 Event::reconstruct_from_strings(
2468 uuid::Uuid::new_v4(),
2469 "test.event".to_string(),
2470 entity_id.to_string(),
2471 tenant.to_string(),
2472 json!({"k": "v"}),
2473 chrono::Utc::now(),
2474 None,
2475 1,
2476 )
2477 }
2478
2479 #[test]
2480 fn test_flush_writes_into_per_tenant_partition() {
2481 let temp_dir = TempDir::new().unwrap();
2485 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2486
2487 for i in 0..3 {
2488 storage
2489 .append_event(event_with_tenant("default", &format!("entity-{i}")))
2490 .unwrap();
2491 }
2492 storage.flush().unwrap();
2493
2494 let parquet_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
2495 assert_eq!(parquet_files.len(), 1);
2496
2497 let rel = parquet_files[0]
2498 .strip_prefix(temp_dir.path())
2499 .unwrap()
2500 .to_string_lossy()
2501 .into_owned();
2502 let parts: Vec<&str> = rel.split(std::path::MAIN_SEPARATOR).collect();
2504 assert_eq!(parts.len(), 3, "expected tenant/yyyy-mm/file, got {rel}");
2505 assert_eq!(parts[0], "default");
2506 assert!(
2509 parts[1].len() == 7 && parts[1].as_bytes()[4] == b'-',
2510 "expected yyyy-mm, got {}",
2511 parts[1]
2512 );
2513 assert!(parts[2].starts_with("events-") && parts[2].ends_with(".parquet"));
2514
2515 let loaded = storage.load_all_events().unwrap();
2516 assert_eq!(loaded.len(), 3);
2517 }
2518
2519 #[test]
2520 fn test_multiple_tenants_get_isolated_subtrees() {
2521 let temp_dir = TempDir::new().unwrap();
2524 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2525
2526 for i in 0..2 {
2527 storage
2528 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2529 .unwrap();
2530 }
2531 for i in 0..3 {
2532 storage
2533 .append_event(event_with_tenant("bob", &format!("b-{i}")))
2534 .unwrap();
2535 }
2536 storage.flush().unwrap();
2537
2538 let alice_subtree = temp_dir.path().join("alice");
2539 let bob_subtree = temp_dir.path().join("bob");
2540 assert!(alice_subtree.is_dir(), "alice should have its own subtree");
2541 assert!(bob_subtree.is_dir(), "bob should have its own subtree");
2542
2543 let alice_files = find_parquet_files_recursive(&alice_subtree).unwrap();
2544 let bob_files = find_parquet_files_recursive(&bob_subtree).unwrap();
2545 assert_eq!(alice_files.len(), 1);
2546 assert_eq!(bob_files.len(), 1);
2547
2548 let loaded = storage.load_all_events().unwrap();
2551 let (alice_count, bob_count) =
2552 loaded
2553 .iter()
2554 .fold((0, 0), |(a, b), e| match e.tenant_id_str() {
2555 "alice" => (a + 1, b),
2556 "bob" => (a, b + 1),
2557 _ => (a, b),
2558 });
2559 assert_eq!(alice_count, 2);
2560 assert_eq!(bob_count, 3);
2561 }
2562
2563 #[test]
2564 fn test_size_flush_only_drains_full_tenant() {
2565 let temp_dir = TempDir::new().unwrap();
2569 let config = ParquetStorageConfig {
2570 batch_size: 5,
2571 ..Default::default()
2572 };
2573 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2574
2575 for i in 0..5 {
2578 storage
2579 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2580 .unwrap();
2581 }
2582 for i in 0..2 {
2584 storage
2585 .append_event(event_with_tenant("bob", &format!("b-{i}")))
2586 .unwrap();
2587 }
2588
2589 assert_eq!(
2590 storage.pending_count(),
2591 2,
2592 "only bob's 2 events should be pending"
2593 );
2594
2595 let parquet_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
2596 assert_eq!(parquet_files.len(), 1, "only alice should have flushed");
2597 assert!(
2598 parquet_files[0]
2599 .to_string_lossy()
2600 .contains(&format!("alice{}", std::path::MAIN_SEPARATOR)),
2601 "expected alice partition, got {}",
2602 parquet_files[0].display()
2603 );
2604 }
2605
2606 #[test]
2607 fn test_tenant_id_from_path_recovers_tenant_for_partitioned_files() {
2608 let root = Path::new("/data/storage");
2609 let f = Path::new("/data/storage/alice/2026-04/events-20260426-120000000-aaaa.parquet");
2610 assert_eq!(tenant_id_from_path(root, f), "alice");
2611 }
2612
2613 #[test]
2614 fn test_tenant_id_from_path_falls_back_to_default_for_legacy_flat_layout() {
2615 let root = Path::new("/data/storage");
2616 let f = Path::new("/data/storage/events-20260426-120000000-aaaa.parquet");
2617 assert_eq!(tenant_id_from_path(root, f), "default");
2620 }
2621
2622 #[test]
2623 fn test_sanitize_tenant_id_for_path_accepts_safe_inputs() {
2624 for ok in [
2625 "default",
2626 "system",
2627 "1e6b2d1c-2f64-4441-9cf9-42f2e451aa17",
2628 "onboard-diagnostic-160-at-example-com",
2629 "tenant_with_underscore",
2630 "v1.0",
2631 ] {
2632 assert!(
2633 sanitize_tenant_id_for_path(ok).is_ok(),
2634 "{ok:?} should be accepted"
2635 );
2636 }
2637 }
2638
2639 #[test]
2640 fn test_sanitize_tenant_id_for_path_rejects_unsafe_inputs() {
2641 for bad in [
2642 "", "..", ".", "foo/bar", "foo\\bar", "foo bar", "foo\nbar", "foo\0bar", "tenant?", "tenant*", ] {
2653 assert!(
2654 sanitize_tenant_id_for_path(bad).is_err(),
2655 "{bad:?} should be rejected"
2656 );
2657 }
2658
2659 let too_long = "a".repeat(129);
2661 assert!(sanitize_tenant_id_for_path(&too_long).is_err());
2662 }
2663
2664 #[test]
2665 fn test_partition_path_for_tenant_shape() {
2666 let root = Path::new("/data");
2667 let when = chrono::DateTime::parse_from_rfc3339("2026-04-26T12:00:00Z")
2668 .unwrap()
2669 .with_timezone(&chrono::Utc);
2670 let path = partition_path_for_tenant(root, "alice", when).unwrap();
2671 assert_eq!(path, Path::new("/data/alice/2026-04"));
2672 }
2673
2674 #[test]
2675 fn test_append_event_rejects_unsafe_tenant_at_flush() {
2676 let temp_dir = TempDir::new().unwrap();
2682 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2683
2684 storage
2688 .append_event(event_with_tenant("../escape", "e-0"))
2689 .unwrap();
2690 let result = storage.flush();
2691 assert!(result.is_err(), "flush should reject unsafe tenant_id");
2692 let msg = format!("{}", result.unwrap_err());
2693 assert!(
2694 msg.contains("disallowed character") || msg.contains("reserved"),
2695 "expected sanitization error message, got: {msg}"
2696 );
2697 }
2698
2699 #[test]
2704 fn test_load_events_for_tenant_only_walks_target_subtree() {
2705 let temp_dir = TempDir::new().unwrap();
2710 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2711
2712 for i in 0..2 {
2713 storage
2714 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2715 .unwrap();
2716 }
2717 for i in 0..3 {
2718 storage
2719 .append_event(event_with_tenant("bob", &format!("b-{i}")))
2720 .unwrap();
2721 }
2722 for i in 0..1 {
2723 storage
2724 .append_event(event_with_tenant("carol", &format!("c-{i}")))
2725 .unwrap();
2726 }
2727 storage.flush().unwrap();
2728
2729 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
2730 assert_eq!(alice_files.len(), 1);
2731 assert!(
2732 alice_files[0]
2733 .to_string_lossy()
2734 .contains(&format!("alice{}", std::path::MAIN_SEPARATOR)),
2735 "expected alice file, got {}",
2736 alice_files[0].display()
2737 );
2738 for f in &alice_files {
2742 let s = f.to_string_lossy();
2743 assert!(!s.contains("bob"), "alice listing leaked bob file: {s}");
2744 assert!(!s.contains("carol"), "alice listing leaked carol file: {s}");
2745 }
2746
2747 let alice_events = storage.load_events_for_tenant("alice").unwrap();
2748 assert_eq!(alice_events.len(), 2);
2749 for e in &alice_events {
2750 assert_eq!(e.tenant_id_str(), "alice");
2751 }
2752
2753 let bob_events = storage.load_events_for_tenant("bob").unwrap();
2754 assert_eq!(bob_events.len(), 3);
2755 for e in &bob_events {
2756 assert_eq!(e.tenant_id_str(), "bob");
2757 }
2758
2759 let carol_events = storage.load_events_for_tenant("carol").unwrap();
2760 assert_eq!(carol_events.len(), 1);
2761 assert_eq!(carol_events[0].tenant_id_str(), "carol");
2762 }
2763
2764 #[test]
2765 fn test_load_events_for_tenant_returns_empty_when_subtree_missing() {
2766 let temp_dir = TempDir::new().unwrap();
2770 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2771
2772 storage
2775 .append_event(event_with_tenant("alice", "a-0"))
2776 .unwrap();
2777 storage.flush().unwrap();
2778
2779 let files = storage
2780 .list_parquet_files_for_tenant("nobody-here")
2781 .unwrap();
2782 assert!(files.is_empty());
2783
2784 let events = storage.load_events_for_tenant("nobody-here").unwrap();
2785 assert!(events.is_empty());
2786 }
2787
2788 #[test]
2789 fn test_load_events_for_tenant_rejects_unsafe_tenant_id() {
2790 let temp_dir = TempDir::new().unwrap();
2793 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2794
2795 for unsafe_tid in ["..", "a/b", "a\\b", "", "a..b/.."] {
2796 let result = storage.load_events_for_tenant(unsafe_tid);
2797 assert!(
2798 result.is_err(),
2799 "tenant_id {unsafe_tid:?} should have been rejected"
2800 );
2801 }
2802 }
2803
2804 #[test]
2805 fn test_load_events_for_tenant_ignores_legacy_flat_layout_files() {
2806 let temp_dir = TempDir::new().unwrap();
2814 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2815
2816 let _flat = seed_flat_layout_file(&storage, 4);
2818
2819 let default_events = storage.load_events_for_tenant("default").unwrap();
2822 assert!(
2823 default_events.is_empty(),
2824 "tenant-scoped load must not pick up flat-layout files; got {} events",
2825 default_events.len()
2826 );
2827
2828 let all_events = storage.load_all_events().unwrap();
2830 assert_eq!(all_events.len(), 4);
2831 }
2832
2833 #[test]
2838 fn test_write_atomic_parquet_emits_file_under_tenant_partition() {
2839 let temp_dir = TempDir::new().unwrap();
2844 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2845
2846 let events: Vec<Event> = (0..3)
2847 .map(|i| event_with_tenant("alice", &format!("a-{i}")))
2848 .collect();
2849
2850 let final_path = storage
2851 .write_atomic_parquet("alice", "snapshot.alice.range", &events)
2852 .unwrap();
2853
2854 let rel = final_path
2856 .strip_prefix(temp_dir.path())
2857 .unwrap()
2858 .to_string_lossy()
2859 .into_owned();
2860 let parts: Vec<&str> = rel.split(std::path::MAIN_SEPARATOR).collect();
2861 assert_eq!(parts.len(), 3, "expected tenant/yyyy-mm/file, got {rel}");
2862 assert_eq!(parts[0], "alice");
2863 assert_eq!(parts[2], "snapshot.alice.range.parquet");
2864
2865 assert!(final_path.is_file());
2867 let tmp = final_path.with_extension("parquet.tmp");
2868 assert!(
2869 !tmp.exists(),
2870 "tmp should have been renamed away; still at {}",
2871 tmp.display()
2872 );
2873
2874 let loaded = storage.load_events_for_tenant("alice").unwrap();
2876 assert_eq!(loaded.len(), 3);
2877 }
2878
2879 #[test]
2880 fn test_write_atomic_parquet_rejects_empty_events() {
2881 let temp_dir = TempDir::new().unwrap();
2882 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2883 let result = storage.write_atomic_parquet("alice", "snap", &[]);
2884 assert!(result.is_err());
2885 }
2886
2887 #[test]
2888 fn test_write_atomic_parquet_rejects_unsafe_tenant() {
2889 let temp_dir = TempDir::new().unwrap();
2890 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2891 let events = [event_with_tenant("alice", "e-0")];
2892 for unsafe_tid in ["..", "a/b", ""] {
2893 let result = storage.write_atomic_parquet(unsafe_tid, "snap", &events);
2894 assert!(
2895 result.is_err(),
2896 "unsafe tenant_id {unsafe_tid:?} should have been rejected"
2897 );
2898 }
2899 }
2900
2901 #[test]
2902 fn test_cleanup_partial_writes_removes_orphan_tmps() {
2903 let temp_dir = TempDir::new().unwrap();
2907 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2908
2909 for i in 0..2 {
2912 storage
2913 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2914 .unwrap();
2915 }
2916 storage.flush().unwrap();
2917 let real_files_before = find_parquet_files_recursive(temp_dir.path()).unwrap();
2918 assert_eq!(real_files_before.len(), 1);
2919
2920 let alice_subtree = temp_dir.path().join("alice");
2922 let orphan_dir = real_files_before[0].parent().unwrap();
2923 let orphan_path = orphan_dir.join("snapshot.alice.crashed.parquet.tmp");
2924 std::fs::write(&orphan_path, b"fake partial parquet").unwrap();
2925 assert!(orphan_path.is_file());
2926
2927 let nested_dir = alice_subtree.join("2099-01");
2929 std::fs::create_dir_all(&nested_dir).unwrap();
2930 let nested_orphan = nested_dir.join("events-x.parquet.tmp");
2931 std::fs::write(&nested_orphan, b"junk").unwrap();
2932
2933 let removed = storage.cleanup_partial_writes().unwrap();
2934 assert_eq!(removed, 2, "two orphan tmps should have been cleaned");
2935 assert!(!orphan_path.exists());
2936 assert!(!nested_orphan.exists());
2937
2938 let real_files_after = find_parquet_files_recursive(temp_dir.path()).unwrap();
2940 assert_eq!(real_files_after, real_files_before);
2941 }
2942
2943 #[test]
2944 fn test_cleanup_partial_writes_quarantines_zero_byte_parquet() {
2945 let temp_dir = TempDir::new().unwrap();
2950 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2951
2952 for i in 0..2 {
2954 storage
2955 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2956 .unwrap();
2957 }
2958 storage.flush().unwrap();
2959 let healthy_files_before = find_parquet_files_recursive(temp_dir.path()).unwrap();
2960 assert_eq!(healthy_files_before.len(), 1);
2961 let healthy_file = &healthy_files_before[0];
2962 let healthy_dir = healthy_file.parent().unwrap();
2963
2964 let bricked = healthy_dir.join("events-bricked-deadbeef.parquet");
2966 std::fs::write(&bricked, b"").unwrap();
2967 assert_eq!(std::fs::metadata(&bricked).unwrap().len(), 0);
2968
2969 let acted = storage.cleanup_partial_writes().unwrap();
2970 assert_eq!(acted, 1, "only the 0-byte file should have been acted on");
2971
2972 assert!(!bricked.exists(), "0-byte file should have been renamed");
2975 let quarantined: Vec<_> = std::fs::read_dir(healthy_dir)
2976 .unwrap()
2977 .flatten()
2978 .map(|e| e.path())
2979 .filter(|p| {
2980 p.file_name()
2981 .and_then(|n| n.to_str())
2982 .is_some_and(|n| n.starts_with("events-bricked-deadbeef.parquet.corrupt-"))
2983 })
2984 .collect();
2985 assert_eq!(
2986 quarantined.len(),
2987 1,
2988 "expected one .parquet.corrupt-<ts> sibling"
2989 );
2990
2991 assert!(
2993 healthy_file.exists(),
2994 "healthy parquet must not be molested"
2995 );
2996 }
2997
2998 #[test]
2999 fn test_load_all_events_skips_zero_byte_parquet() {
3000 let temp_dir = TempDir::new().unwrap();
3004 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3005
3006 for i in 0..2 {
3008 storage
3009 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3010 .unwrap();
3011 }
3012 storage.flush().unwrap();
3013
3014 let healthy_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
3018 let bricked = healthy_files[0]
3019 .parent()
3020 .unwrap()
3021 .join("events-bricked-cafef00d.parquet");
3022 std::fs::write(&bricked, b"").unwrap();
3023
3024 let loaded = storage.load_all_events().unwrap();
3025 assert_eq!(
3026 loaded.len(),
3027 2,
3028 "all healthy events should still load despite the 0-byte file"
3029 );
3030 }
3031
3032 #[test]
3033 fn test_load_events_for_tenant_skips_zero_byte_parquet() {
3034 let temp_dir = TempDir::new().unwrap();
3037 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3038
3039 for i in 0..3 {
3040 storage
3041 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3042 .unwrap();
3043 }
3044 storage.flush().unwrap();
3045
3046 let healthy = find_parquet_files_recursive(temp_dir.path()).unwrap();
3047 let bricked = healthy[0]
3048 .parent()
3049 .unwrap()
3050 .join("events-bricked-feedface.parquet");
3051 std::fs::write(&bricked, b"").unwrap();
3052
3053 let events = storage.load_events_for_tenant("alice").unwrap();
3054 assert_eq!(events.len(), 3, "lazy load must skip the 0-byte file");
3055 }
3056
3057 #[test]
3058 fn test_flush_tenant_leaves_no_zero_byte_parquet_after_normal_flush() {
3059 let temp_dir = TempDir::new().unwrap();
3063 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3064
3065 for i in 0..5 {
3066 storage
3067 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3068 .unwrap();
3069 }
3070 storage.flush().unwrap();
3071
3072 let mut tmp_count = 0;
3073 let mut zero_byte_count = 0;
3074 let mut healthy_count = 0;
3075 let mut stack = vec![temp_dir.path().to_path_buf()];
3076 while let Some(d) = stack.pop() {
3077 for entry in std::fs::read_dir(&d).unwrap().flatten() {
3078 let p = entry.path();
3079 if p.is_dir() {
3080 stack.push(p);
3081 continue;
3082 }
3083 let name = p.file_name().unwrap().to_string_lossy().into_owned();
3084 if name.ends_with(".parquet.tmp") {
3085 tmp_count += 1;
3086 } else if name.ends_with(".parquet") {
3087 if std::fs::metadata(&p).unwrap().len() == 0 {
3088 zero_byte_count += 1;
3089 } else {
3090 healthy_count += 1;
3091 }
3092 }
3093 }
3094 }
3095 assert_eq!(tmp_count, 0, ".parquet.tmp survivors after flush");
3096 assert_eq!(zero_byte_count, 0, "0-byte .parquet survivors after flush");
3097 assert_eq!(healthy_count, 1, "expected exactly one healthy parquet");
3098 }
3099
3100 #[test]
3101 fn test_new_calls_cleanup_partial_writes_on_boot() {
3102 let temp_dir = TempDir::new().unwrap();
3106 let stale = temp_dir.path().join("orphan.parquet.tmp");
3107 std::fs::write(&stale, b"crash detritus").unwrap();
3108 assert!(stale.is_file());
3109
3110 let _storage = ParquetStorage::new(temp_dir.path()).unwrap();
3111 assert!(
3112 !stale.exists(),
3113 "stale tmp should have been cleaned by ParquetStorage::new"
3114 );
3115 }
3116
3117 fn seed_flat_layout_file(storage: &ParquetStorage, count: usize) -> PathBuf {
3127 for i in 0..count {
3128 storage
3129 .append_event(create_test_event(&format!("entity-{i}")))
3130 .unwrap();
3131 }
3132 storage.flush().unwrap();
3133
3134 let default_subtree = storage.storage_dir().join("default");
3139 let candidates = find_parquet_files_recursive(&default_subtree).unwrap();
3140 assert!(
3141 !candidates.is_empty(),
3142 "seed expected at least one file under default/"
3143 );
3144 let src = candidates.into_iter().max().unwrap();
3145
3146 let dst = storage.storage_dir().join(src.file_name().unwrap());
3147 std::fs::rename(&src, &dst).unwrap();
3148 if let Some(month_dir) = src.parent() {
3152 let _ = std::fs::remove_dir(month_dir);
3153 if let Some(tenant_dir) = month_dir.parent() {
3154 let _ = std::fs::remove_dir(tenant_dir);
3155 }
3156 }
3157 dst
3158 }
3159
3160 #[test]
3161 fn test_migrate_flat_layout_dry_run_touches_nothing() {
3162 let temp_dir = TempDir::new().unwrap();
3163 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3164 let flat = seed_flat_layout_file(&storage, 7);
3165 assert!(flat.is_file(), "test setup: flat file should exist");
3166
3167 let report = storage.migrate_flat_layout(true).unwrap();
3168 assert!(report.dry_run);
3169 assert_eq!(report.flat_files_seen, 1);
3170 assert_eq!(report.events_migrated, 7);
3171 assert_eq!(report.flat_files_removed, 0);
3172 assert_eq!(report.partitions_written, 0);
3173 assert!(
3174 flat.is_file(),
3175 "flat file must still be present after dry run"
3176 );
3177 }
3178
3179 #[test]
3180 fn test_migrate_flat_layout_moves_events_into_default_tree_and_removes_flat() {
3181 let temp_dir = TempDir::new().unwrap();
3182 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3183 let flat = seed_flat_layout_file(&storage, 5);
3184
3185 let report = storage.migrate_flat_layout(false).unwrap();
3186 assert!(!report.dry_run);
3187 assert_eq!(report.flat_files_seen, 1);
3188 assert_eq!(report.flat_files_removed, 1);
3189 assert_eq!(report.events_migrated, 5);
3190 assert!(report.partitions_written >= 1);
3191 assert!(
3192 !flat.exists(),
3193 "flat file should be deleted after migration"
3194 );
3195
3196 let post = find_parquet_files_recursive(temp_dir.path()).unwrap();
3197 assert!(
3198 post.iter().all(|p| {
3199 let rel = p
3200 .strip_prefix(temp_dir.path())
3201 .unwrap()
3202 .to_string_lossy()
3203 .into_owned();
3204 rel.starts_with(&format!("default{}", std::path::MAIN_SEPARATOR))
3205 }),
3206 "all migrated files should be under default/"
3207 );
3208
3209 let loaded = storage.load_all_events().unwrap();
3210 assert_eq!(loaded.len(), 5);
3211 }
3212
3213 #[test]
3214 fn test_migrate_flat_layout_is_idempotent_when_re_run_after_completion() {
3215 let temp_dir = TempDir::new().unwrap();
3216 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3217 let _flat = seed_flat_layout_file(&storage, 4);
3218
3219 let first = storage.migrate_flat_layout(false).unwrap();
3220 assert_eq!(first.events_migrated, 4);
3221
3222 let second = storage.migrate_flat_layout(false).unwrap();
3225 assert_eq!(second.flat_files_seen, 0);
3226 assert_eq!(second.events_migrated, 0);
3227 assert_eq!(second.flat_files_removed, 0);
3228
3229 let loaded = storage.load_all_events().unwrap();
3230 assert_eq!(loaded.len(), 4, "rerun must not duplicate or lose events");
3231 }
3232
3233 #[test]
3234 fn test_migrate_flat_layout_ignores_already_partitioned_data() {
3235 let temp_dir = TempDir::new().unwrap();
3238 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3239
3240 for i in 0..3 {
3241 storage
3242 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3243 .unwrap();
3244 }
3245 storage.flush().unwrap();
3246
3247 let _flat = seed_flat_layout_file(&storage, 2);
3248
3249 let report = storage.migrate_flat_layout(false).unwrap();
3250 assert_eq!(report.flat_files_seen, 1, "only the flat file is in scope");
3251 assert_eq!(report.events_migrated, 2);
3252
3253 let alice_files = find_parquet_files_recursive(&temp_dir.path().join("alice")).unwrap();
3254 assert_eq!(alice_files.len(), 1, "alice's tree must be untouched");
3255
3256 let loaded = storage.load_all_events().unwrap();
3257 assert_eq!(loaded.len(), 5);
3258 let alice_count = loaded
3259 .iter()
3260 .filter(|e| e.tenant_id_str() == "alice")
3261 .count();
3262 let default_count = loaded
3263 .iter()
3264 .filter(|e| e.tenant_id_str() == "default")
3265 .count();
3266 assert_eq!(alice_count, 3);
3267 assert_eq!(default_count, 2);
3268 }
3269
3270 #[test]
3271 fn test_migrate_flat_layout_with_no_flat_files_is_a_clean_noop() {
3272 let temp_dir = TempDir::new().unwrap();
3273 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3274 let report = storage.migrate_flat_layout(false).unwrap();
3275 assert_eq!(report.flat_files_seen, 0);
3276 assert_eq!(report.events_migrated, 0);
3277 }
3278}