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 if recover {
260 fs::create_dir_all(&storage_dir).map_err(|e| {
261 AllSourceError::StorageError(format!("Failed to create storage directory: {e}"))
262 })?;
263 } else if !storage_dir.is_dir() {
264 return Err(AllSourceError::StorageError(
265 "Existing storage directory is unavailable".into(),
266 ));
267 }
268
269 let schema = event_schema();
270
271 let storage = Self {
272 storage_dir,
273 current_batches: Mutex::new(HashMap::new()),
274 pending: Tally::new(Owner::StoragePending),
275 config,
276 schema,
277 last_flush_time: Mutex::new(Instant::now()),
278 batches_written: AtomicU64::new(0),
279 events_written: AtomicU64::new(0),
280 bytes_written: AtomicU64::new(0),
281 total_write_time_ns: AtomicU64::new(0),
282 timeout_flushes: AtomicU64::new(0),
283 size_flushes: AtomicU64::new(0),
284 };
285
286 if recover {
291 match storage.cleanup_partial_writes() {
292 Ok(0) => {}
293 Ok(n) => tracing::warn!(
294 "cleanup_partial_writes acted on {n} crash-detritus file(s) on boot — \
295 see preceding logs for per-file detail"
296 ),
297 Err(e) => tracing::error!("cleanup_partial_writes failed on boot: {e}"),
298 }
299 }
300
301 Ok(storage)
302 }
303
304 #[deprecated(note = "Use new() or with_config() instead - default batch size is now 10,000")]
306 pub fn with_legacy_batch_size(storage_dir: impl AsRef<Path>) -> Result<Self> {
307 Self::with_config(
308 storage_dir,
309 ParquetStorageConfig {
310 batch_size: 1000,
311 ..Default::default()
312 },
313 )
314 }
315
316 #[cfg_attr(feature = "hotpath", hotpath::measure)]
326 pub fn append_event(&self, event: Event) -> Result<()> {
327 let tenant = event.tenant_id_str().to_string();
328 self.pending.add(event.resident_bytes());
329 let should_flush_tenant = {
330 let mut batches = self.current_batches.lock().unwrap();
331 let entry = batches.entry(tenant.clone()).or_default();
332 entry.push(event);
333 entry.len() >= self.config.batch_size
334 };
335
336 if should_flush_tenant {
337 self.size_flushes.fetch_add(1, Ordering::Relaxed);
338 self.flush_tenant(&tenant)?;
339 }
340
341 Ok(())
342 }
343
344 #[cfg_attr(feature = "hotpath", hotpath::measure)]
350 pub fn batch_write(&self, events: Vec<Event>) -> Result<BatchWriteResult> {
351 let start = Instant::now();
352 let event_count = events.len();
353
354 let mut grouped: HashMap<String, Vec<Event>> = HashMap::new();
357 for event in events {
358 self.pending.add(event.resident_bytes());
359 grouped
360 .entry(event.tenant_id_str().to_string())
361 .or_default()
362 .push(event);
363 }
364
365 let mut tenants_to_flush: Vec<String> = Vec::new();
366 {
367 let mut batches = self.current_batches.lock().unwrap();
368 for (tenant, mut new_events) in grouped {
369 let entry = batches.entry(tenant.clone()).or_default();
370 entry.append(&mut new_events);
371 if entry.len() >= self.config.batch_size {
372 tenants_to_flush.push(tenant);
373 }
374 }
375 }
376
377 let mut batches_flushed = 0;
378 for tenant in tenants_to_flush {
379 self.size_flushes.fetch_add(1, Ordering::Relaxed);
380 self.flush_tenant(&tenant)?;
381 batches_flushed += 1;
382 }
383
384 let duration = start.elapsed();
385
386 Ok(BatchWriteResult {
387 events_written: event_count,
388 batches_flushed,
389 duration,
390 events_per_sec: event_count as f64 / duration.as_secs_f64(),
391 })
392 }
393
394 #[cfg_attr(feature = "hotpath", hotpath::measure)]
402 pub fn check_timeout_flush(&self) -> Result<bool> {
403 let should_flush = {
404 let last_flush = self.last_flush_time.lock().unwrap();
405 let batches = self.current_batches.lock().unwrap();
406 let any_pending = batches.values().any(|v| !v.is_empty());
407 any_pending && last_flush.elapsed() >= self.config.flush_timeout
408 };
409
410 if should_flush {
411 self.timeout_flushes.fetch_add(1, Ordering::Relaxed);
412 self.flush()?;
413 Ok(true)
414 } else {
415 Ok(false)
416 }
417 }
418
419 #[cfg_attr(feature = "hotpath", hotpath::measure)]
426 pub fn flush(&self) -> Result<()> {
427 let tenants: Vec<String> = {
428 let batches = self.current_batches.lock().unwrap();
429 batches
430 .iter()
431 .filter(|(_, v)| !v.is_empty())
432 .map(|(k, _)| k.clone())
433 .collect()
434 };
435 if tenants.is_empty() {
436 return Ok(());
437 }
438 for tenant in tenants {
439 self.flush_tenant(&tenant)?;
440 }
441 Ok(())
442 }
443
444 pub(crate) fn has_pending_tenant_events(&self, tenant_id: &str) -> bool {
447 self.current_batches
448 .lock()
449 .unwrap()
450 .get(tenant_id)
451 .is_some_and(|events| !events.is_empty())
452 }
453
454 fn flush_tenant(&self, tenant_id: &str) -> Result<()> {
469 let events_to_write = {
470 let mut batches = self.current_batches.lock().unwrap();
471 match batches.get_mut(tenant_id) {
472 Some(v) if !v.is_empty() => std::mem::take(v),
473 _ => return Ok(()),
474 }
475 };
476
477 let batch_count = events_to_write.len();
478 let start = Instant::now();
479
480 let written = self.write_tenant_events(tenant_id, &events_to_write);
481 let parts = match written {
482 Ok(written) => written,
483 Err(e) => {
484 let mut batches = self.current_batches.lock().unwrap();
487 let pending = batches.entry(tenant_id.to_string()).or_default();
488 let arrived_during_write = std::mem::replace(pending, events_to_write);
489 pending.extend(arrived_during_write);
490 return Err(e);
491 }
492 };
493
494 let duration = start.elapsed();
495 self.pending
496 .sub(events_to_write.iter().map(Event::resident_bytes).sum());
497
498 let mut offset = 0;
503 for part in &parts {
504 let rows = usize::try_from(part.metadata.file_metadata().num_rows())
505 .map_err(|_| AllSourceError::StorageError("Invalid archive output rows".into()))?;
506 if let Err(error) = self.record_flushed_versions(
507 tenant_id,
508 &part.path,
509 &events_to_write[offset..offset + rows],
510 ) {
511 tracing::warn!(tenant_id, %error, "could not update tenant version manifest");
512 }
513 offset += rows;
514 }
515
516 self.batches_written.fetch_add(1, Ordering::Relaxed);
517 self.events_written
518 .fetch_add(batch_count as u64, Ordering::Relaxed);
519 let bytes = parts
520 .iter()
521 .flat_map(|part| part.metadata.row_groups())
522 .map(|group| group.total_byte_size() as u64)
523 .sum();
524 self.bytes_written.fetch_add(bytes, Ordering::Relaxed);
525 self.total_write_time_ns
526 .fetch_add(duration.as_nanos() as u64, Ordering::Relaxed);
527
528 {
529 let mut last_flush = self.last_flush_time.lock().unwrap();
530 *last_flush = Instant::now();
531 }
532
533 tracing::info!(
534 "Wrote {} events for tenant={} to {} files in {:?}",
535 batch_count,
536 tenant_id,
537 parts.len(),
538 duration
539 );
540
541 Ok(())
542 }
543
544 fn write_tenant_events(&self, tenant_id: &str, events: &[Event]) -> Result<Vec<PublishedPart>> {
545 let record_batch = self.events_to_record_batch(events)?;
546
547 let now = chrono::Utc::now();
548 let partition_dir = partition_path_for_tenant(&self.storage_dir, tenant_id, now)?;
549 fs::create_dir_all(&partition_dir).map_err(|e| {
550 AllSourceError::StorageError(format!(
551 "Failed to create tenant partition {}: {e}",
552 partition_dir.display()
553 ))
554 })?;
555 let file_stem = match &self.config.file_namer {
556 Some(FileNamer(name)) => name(tenant_id, now),
557 None => format!(
558 "events-{}-{}",
559 now.format("%Y%m%d-%H%M%S%3f"),
560 uuid::Uuid::new_v4().as_simple()
561 ),
562 };
563
564 tracing::info!(
565 "Flushing {} events for tenant={} to {}/{}.parquet",
566 events.len(),
567 tenant_id,
568 partition_dir.display(),
569 file_stem
570 );
571
572 let mut output = ArchiveOutput::new(
573 &partition_dir,
574 &file_stem,
575 self.config.compression,
576 ArchiveReadLimits::default().max_file_bytes,
577 true,
578 )?;
579 output.stage(&record_batch)?;
580 output.publish()
581 }
582
583 fn write_record_batch_atomic(
600 &self,
601 partition_dir: &Path,
602 file_stem: &str,
603 record_batch: &RecordBatch,
604 ) -> Result<(PathBuf, parquet::file::metadata::ParquetMetaData)> {
605 let mut output = ArchiveOutput::new(
606 partition_dir,
607 file_stem,
608 self.config.compression,
609 ArchiveReadLimits::default().max_file_bytes,
610 false,
611 )?;
612 output.stage(record_batch)?;
613 let part = output
614 .publish()?
615 .pop()
616 .ok_or_else(|| AllSourceError::StorageError("Archive output missing".into()))?;
617 Ok((part.path, part.metadata))
618 }
619
620 pub fn write_atomic_parquet(
644 &self,
645 tenant_id: &str,
646 file_stem: &str,
647 events: &[Event],
648 ) -> Result<PathBuf> {
649 if events.is_empty() {
650 return Err(AllSourceError::StorageError(
651 "write_atomic_parquet called with empty event slice".to_string(),
652 ));
653 }
654 let anchor_ts = events
659 .iter()
660 .map(|e| e.timestamp)
661 .min()
662 .unwrap_or_else(chrono::Utc::now);
663 let partition_dir = partition_path_for_tenant(&self.storage_dir, tenant_id, anchor_ts)?;
664 fs::create_dir_all(&partition_dir).map_err(|e| {
665 AllSourceError::StorageError(format!(
666 "Failed to create tenant partition {}: {e}",
667 partition_dir.display()
668 ))
669 })?;
670
671 let record_batch = self.events_to_record_batch(events)?;
672 let (final_path, _meta) =
673 self.write_record_batch_atomic(&partition_dir, file_stem, &record_batch)?;
674
675 tracing::info!(
676 tenant_id = tenant_id,
677 file = %final_path.display(),
678 event_count = events.len(),
679 "wrote atomic snapshot file"
680 );
681
682 Ok(final_path)
683 }
684
685 pub(crate) fn write_atomic_parquet_parts(
686 &self,
687 tenant_id: &str,
688 file_stem: &str,
689 events: &[Event],
690 ) -> Result<Vec<PathBuf>> {
691 if events.is_empty() {
692 return Err(AllSourceError::StorageError(
693 "Cannot archive empty events".into(),
694 ));
695 }
696 let anchor = events
697 .iter()
698 .map(|event| event.timestamp)
699 .min()
700 .ok_or_else(|| AllSourceError::StorageError("Cannot archive empty events".into()))?;
701 let directory = partition_path_for_tenant(&self.storage_dir, tenant_id, anchor)?;
702 fs::create_dir_all(&directory).map_err(|error| {
703 AllSourceError::StorageError(format!("Failed to create archive partition: {error}"))
704 })?;
705 let batch = self.events_to_record_batch(events)?;
706 let mut output = ArchiveOutput::new(
707 &directory,
708 file_stem,
709 self.config.compression,
710 ArchiveReadLimits::default().max_file_bytes,
711 true,
712 )?;
713 output.stage(&batch)?;
714 Ok(output
715 .publish()?
716 .into_iter()
717 .map(|part| part.path)
718 .collect())
719 }
720
721 pub fn cleanup_partial_writes(&self) -> Result<usize> {
744 let mut acted = 0usize;
745 let mut stack: Vec<PathBuf> = vec![self.storage_dir.clone()];
746 while let Some(dir) = stack.pop() {
747 acted += recover_pending_outputs(&dir)?;
748 let Ok(entries) = fs::read_dir(&dir) else {
749 continue;
750 };
751 for entry in entries.flatten() {
752 let path = entry.path();
753 let Ok(ft) = entry.file_type() else { continue };
754 if ft.is_dir() {
755 stack.push(path);
756 continue;
757 }
758 if !ft.is_file() {
759 continue;
760 }
761 let path_str = path.to_string_lossy();
762 if path_str.ends_with(".parquet.tmp") {
763 match fs::remove_file(&path) {
764 Ok(()) => {
765 tracing::warn!(
766 file = %path.display(),
767 "cleaned up orphan snapshot tmp file (crash recovery)"
768 );
769 acted += 1;
770 }
771 Err(e) => {
772 tracing::error!(
773 file = %path.display(),
774 "failed to remove orphan snapshot tmp file: {e}"
775 );
776 }
777 }
778 } else if path_str.ends_with(".parquet")
779 && fs::metadata(&path).is_ok_and(|m| m.len() == 0)
780 {
781 let ts = chrono::Utc::now().timestamp();
785 let quarantine_path = path.with_extension(format!("parquet.corrupt-{ts}"));
786 match fs::rename(&path, &quarantine_path) {
787 Ok(()) => {
788 tracing::error!(
789 from = %path.display(),
790 to = %quarantine_path.display(),
791 "quarantined 0-byte parquet file (issue #166 pre-fix crash). \
792 Operator: inspect and rm if not needed."
793 );
794 acted += 1;
795 }
796 Err(e) => {
797 tracing::error!(
798 file = %path.display(),
799 "failed to quarantine 0-byte parquet file: {e}"
800 );
801 }
802 }
803 }
804 }
805 }
806 Ok(acted)
807 }
808
809 #[cfg_attr(feature = "hotpath", hotpath::measure)]
815 pub fn flush_on_shutdown(&self) -> Result<usize> {
816 let total_pending: usize = {
817 let batches = self.current_batches.lock().unwrap();
818 batches.values().map(Vec::len).sum()
819 };
820
821 if total_pending > 0 {
822 tracing::info!(
823 "Shutdown: flushing {} pending events across all tenants",
824 total_pending
825 );
826 self.flush()?;
827 }
828
829 Ok(total_pending)
830 }
831
832 pub fn batch_stats(&self) -> BatchWriteStats {
834 let batches = self.batches_written.load(Ordering::Relaxed);
835 let events = self.events_written.load(Ordering::Relaxed);
836 let bytes = self.bytes_written.load(Ordering::Relaxed);
837 let time_ns = self.total_write_time_ns.load(Ordering::Relaxed);
838
839 let time_secs = time_ns as f64 / 1_000_000_000.0;
840
841 BatchWriteStats {
842 batches_written: batches,
843 events_written: events,
844 bytes_written: bytes,
845 avg_batch_size: if batches > 0 {
846 events as f64 / batches as f64
847 } else {
848 0.0
849 },
850 events_per_sec: if time_secs > 0.0 {
851 events as f64 / time_secs
852 } else {
853 0.0
854 },
855 total_write_time_ns: time_ns,
856 timeout_flushes: self.timeout_flushes.load(Ordering::Relaxed),
857 size_flushes: self.size_flushes.load(Ordering::Relaxed),
858 }
859 }
860
861 pub fn pending_count(&self) -> usize {
863 self.current_batches
864 .lock()
865 .unwrap()
866 .values()
867 .map(Vec::len)
868 .sum()
869 }
870
871 pub fn batch_size(&self) -> usize {
873 self.config.batch_size
874 }
875
876 pub fn flush_timeout(&self) -> Duration {
878 self.config.flush_timeout
879 }
880
881 fn events_to_record_batch(&self, events: &[Event]) -> Result<RecordBatch> {
882 event_codec::events_to_record_batch(&self.schema, events)
883 }
884
885 #[cfg_attr(feature = "hotpath", hotpath::measure)]
892 pub fn load_all_events(&self) -> Result<Vec<Event>> {
893 let parquet_files = find_parquet_files_recursive(&self.storage_dir)?;
894
895 let mut all_events = Vec::with_capacity(parquet_files.len() * self.config.batch_size);
896 let mut skipped = 0usize;
897 for file_path in parquet_files {
898 tracing::info!("Loading events from {}", file_path.display());
899 let tenant_id = tenant_id_from_path(&self.storage_dir, &file_path);
900 match self.load_events_from_file(&file_path, &tenant_id) {
905 Ok(file_events) => all_events.extend(file_events),
906 Err(e) => {
907 tracing::error!(
908 file = %file_path.display(),
909 error = %e,
910 "Skipping unreadable parquet file — other files will still load. \
911 Likely a 0-byte or truncated file from an unclean shutdown; \
912 inspect and remove manually after confirming."
913 );
914 skipped += 1;
915 }
916 }
917 }
918
919 if skipped > 0 {
920 tracing::warn!(
921 "Loaded {} events from storage; skipped {} unreadable file(s)",
922 all_events.len(),
923 skipped
924 );
925 } else {
926 tracing::info!("Loaded {} total events from storage", all_events.len());
927 }
928
929 Ok(all_events)
930 }
931
932 #[cfg_attr(feature = "hotpath", hotpath::measure)]
938 fn load_events_from_file(&self, file_path: &Path, tenant_id: &str) -> Result<Vec<Event>> {
939 self.load_events_from_file_with_budget(file_path, tenant_id, None)
940 }
941
942 fn load_events_from_file_with_budget(
943 &self,
944 file_path: &Path,
945 tenant_id: &str,
946 mut budget: Option<&mut ArchiveReadBudget>,
947 ) -> Result<Vec<Event>> {
948 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
949
950 if let Some(budget) = budget.as_deref() {
951 budget.check()?;
952 }
953 let file = File::open(file_path).map_err(|e| {
954 AllSourceError::StorageError(format!("Failed to open parquet file: {e}"))
955 })?;
956
957 if let Some(budget) = budget.as_deref_mut() {
958 let metadata = file.metadata().map_err(|error| {
959 AllSourceError::StorageError(format!("Failed to inspect archive file: {error}"))
960 })?;
961 budget.compressed(metadata.len())?;
962 }
963 let mut builder = ParquetRecordBatchReaderBuilder::try_new(file)?;
964 if let Some(budget) = budget.as_deref_mut() {
965 for group in builder.metadata().row_groups() {
969 budget.rows(group.num_rows())?;
970 }
971 builder = builder.with_batch_size(256);
972 }
973 let reader = builder.build()?;
974
975 let mut events = Vec::new();
976
977 for batch in reader {
978 if let Some(budget) = budget.as_deref() {
979 budget.check()?;
980 }
981 let batch = batch?;
982 if let Some(budget) = budget.as_deref_mut() {
983 budget.decoded_payload(decoded_text_bytes(&batch))?;
984 }
985 let batch_events = self.record_batch_to_events(&batch, tenant_id)?;
986 events.extend(batch_events);
987 }
988
989 if let Some(budget) = budget {
990 budget.check()?;
991 }
992
993 Ok(events)
994 }
995
996 pub fn load_entity_events_for_tenant(
1013 &self,
1014 tenant_id: &str,
1015 entity_id: &str,
1016 ) -> Result<(Vec<Event>, usize)> {
1017 let files = self.list_parquet_files_for_tenant(tenant_id)?;
1018 let mut events = Vec::new();
1019 let mut skipped = 0usize;
1020 for file_path in &files {
1021 match self.load_entity_events_from_file(file_path, tenant_id, entity_id) {
1022 Ok(matches) => events.extend(matches),
1023 Err(error) => {
1024 tracing::error!(
1025 tenant_id = tenant_id,
1026 file = %file_path.display(),
1027 error = %error,
1028 "Unreadable parquet file in entity-scoped archive read"
1029 );
1030 skipped += 1;
1031 }
1032 }
1033 }
1034 tracing::info!(
1035 tenant_id = tenant_id,
1036 entity_id = entity_id,
1037 file_count = files.len(),
1038 matched = events.len(),
1039 skipped_files = skipped,
1040 "entity-scoped archive read complete"
1041 );
1042 Ok((events, skipped))
1043 }
1044
1045 fn load_entity_events_from_file(
1048 &self,
1049 file_path: &Path,
1050 tenant_id: &str,
1051 entity_id: &str,
1052 ) -> Result<Vec<Event>> {
1053 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
1054
1055 let file = File::open(file_path).map_err(|error| unreadable(file_path, error))?;
1056 let builder =
1057 ParquetRecordBatchReaderBuilder::try_new(file).map_err(|e| unreadable(file_path, e))?;
1058 let needle = entity_id.as_bytes();
1059 let groups: Vec<usize> = builder
1060 .metadata()
1061 .row_groups()
1062 .iter()
1063 .enumerate()
1064 .filter(|(_, group)| row_group_may_hold_entity(group, needle))
1065 .map(|(index, _)| index)
1066 .collect();
1067 if groups.is_empty() {
1068 return Ok(Vec::new());
1069 }
1070
1071 let reader = builder
1072 .with_row_groups(groups)
1073 .with_batch_size(256)
1074 .build()
1075 .map_err(|error| unreadable(file_path, error))?;
1076
1077 let mut events = Vec::new();
1078 for batch in reader {
1079 let batch = batch.map_err(|error| unreadable(file_path, error))?;
1080 for event in self.record_batch_to_events(&batch, tenant_id)? {
1083 if event.entity_id_str() == entity_id {
1084 events.push(event);
1085 }
1086 }
1087 }
1088 Ok(events)
1089 }
1090
1091 pub fn load_events_from_file_path(
1097 &self,
1098 file_path: &Path,
1099 tenant_id: &str,
1100 ) -> Result<Vec<Event>> {
1101 self.load_events_from_file(file_path, tenant_id)
1102 }
1103
1104 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1108 fn record_batch_to_events(&self, batch: &RecordBatch, tenant_id: &str) -> Result<Vec<Event>> {
1109 crate::infrastructure::memory::ledger::resident()
1110 .record_rows_decoded(batch.num_rows() as u64);
1111 let event_ids = batch
1112 .column(0)
1113 .as_any()
1114 .downcast_ref::<arrow::array::StringArray>()
1115 .ok_or_else(|| AllSourceError::StorageError("Invalid event_id column".to_string()))?;
1116
1117 let event_types = batch
1118 .column(1)
1119 .as_any()
1120 .downcast_ref::<arrow::array::StringArray>()
1121 .ok_or_else(|| AllSourceError::StorageError("Invalid event_type column".to_string()))?;
1122
1123 let entity_ids = batch
1124 .column(2)
1125 .as_any()
1126 .downcast_ref::<arrow::array::StringArray>()
1127 .ok_or_else(|| AllSourceError::StorageError("Invalid entity_id column".to_string()))?;
1128
1129 let payloads = batch
1130 .column(3)
1131 .as_any()
1132 .downcast_ref::<arrow::array::StringArray>()
1133 .ok_or_else(|| AllSourceError::StorageError("Invalid payload column".to_string()))?;
1134
1135 let timestamps = batch
1136 .column(4)
1137 .as_any()
1138 .downcast_ref::<TimestampMicrosecondArray>()
1139 .ok_or_else(|| AllSourceError::StorageError("Invalid timestamp column".to_string()))?;
1140
1141 let metadatas = batch
1142 .column(5)
1143 .as_any()
1144 .downcast_ref::<arrow::array::StringArray>()
1145 .ok_or_else(|| AllSourceError::StorageError("Invalid metadata column".to_string()))?;
1146
1147 let versions = batch
1148 .column(6)
1149 .as_any()
1150 .downcast_ref::<arrow::array::UInt64Array>()
1151 .ok_or_else(|| AllSourceError::StorageError("Invalid version column".to_string()))?;
1152
1153 let valid_froms = optional_timestamp_column(batch, VALID_FROM_COLUMN)?;
1154 let valid_tos = optional_timestamp_column(batch, VALID_TO_COLUMN)?;
1155
1156 let mut events = Vec::new();
1157
1158 for i in 0..batch.num_rows() {
1159 let id = uuid::Uuid::parse_str(event_ids.value(i))
1160 .map_err(|e| AllSourceError::StorageError(format!("Invalid UUID: {e}")))?;
1161
1162 let timestamp = chrono::DateTime::from_timestamp_micros(timestamps.value(i))
1163 .ok_or_else(|| AllSourceError::StorageError("Invalid timestamp".to_string()))?;
1164
1165 let metadata = if metadatas.is_null(i) {
1166 None
1167 } else {
1168 Some(serde_json::from_str(metadatas.value(i))?)
1169 };
1170
1171 let mut event = Event::reconstruct_from_strings(
1172 id,
1173 event_types.value(i).to_string(),
1174 entity_ids.value(i).to_string(),
1175 tenant_id.to_string(),
1176 serde_json::from_str(payloads.value(i))?,
1177 timestamp,
1178 metadata,
1179 versions.value(i) as i64,
1180 );
1181 event.valid_from = valid_time_at(valid_froms, i)?;
1182 event.valid_to = valid_time_at(valid_tos, i)?;
1183
1184 events.push(event);
1185 }
1186
1187 Ok(events)
1188 }
1189
1190 pub fn list_parquet_files(&self) -> Result<Vec<PathBuf>> {
1196 find_parquet_files_recursive(&self.storage_dir)
1197 }
1198
1199 pub fn tenant_id_for_file(&self, file_path: &Path) -> String {
1201 tenant_id_from_path(&self.storage_dir, file_path)
1202 }
1203
1204 pub fn list_parquet_files_for_tenant(&self, tenant_id: &str) -> Result<Vec<PathBuf>> {
1217 let safe = sanitize_tenant_id_for_path(tenant_id)?;
1218 let tenant_root = self.storage_dir.join(safe);
1219 if !tenant_root.is_dir() {
1220 return Ok(Vec::new());
1221 }
1222 find_parquet_files_recursive(&tenant_root)
1223 }
1224
1225 pub fn tenant_archive_bytes(&self, tenant_id: &str) -> Result<(u64, usize)> {
1234 let files = self.list_parquet_files_for_tenant(tenant_id)?;
1235 let count = files.len();
1236 let bytes = files
1237 .iter()
1238 .filter_map(|path| std::fs::metadata(path).ok())
1239 .map(|metadata| metadata.len())
1240 .sum();
1241 Ok((bytes, count))
1242 }
1243
1244 fn list_complete_tenant_archive(
1245 &self,
1246 tenant_id: &str,
1247 budget: &mut ArchiveReadBudget,
1248 ) -> Result<Vec<PathBuf>> {
1249 budget.check()?;
1250 let safe = sanitize_tenant_id_for_path(tenant_id)?;
1251 let root = self.storage_dir.join(safe);
1252 match fs::symlink_metadata(&root) {
1253 Ok(metadata) if metadata.is_dir() => {
1254 find_parquet_files_recursive_with_integrity(&root, Some(budget))
1255 }
1256 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
1257 _ => Err(AllSourceError::StorageError(
1258 "Cannot verify conditional version: tenant archive is not an accessible directory"
1259 .into(),
1260 )),
1261 }
1262 }
1263
1264 #[cfg_attr(feature = "hotpath", hotpath::measure)]
1283 pub fn load_events_for_tenant(&self, tenant_id: &str) -> Result<Vec<Event>> {
1284 self.load_events_for_tenant_with_integrity(tenant_id, None)
1285 .map(|(events, _complete)| events)
1286 }
1287
1288 pub(crate) fn resolve_entity_version(
1304 &self,
1305 tenant_id: &str,
1306 entity_id: &str,
1307 budget: &mut ArchiveReadBudget,
1308 ) -> Result<ResolvedVersion> {
1309 let files = self.list_complete_tenant_archive(tenant_id, budget)?;
1310 let tenant_dir = self
1311 .storage_dir
1312 .join(sanitize_tenant_id_for_path(tenant_id)?);
1313 let mut manifest = VersionManifest::load(&tenant_dir).unwrap_or_default();
1314
1315 let outstanding: Vec<PathBuf> = files
1316 .into_iter()
1317 .filter(|path| {
1318 manifest_key(&tenant_dir, path).is_none_or(|key| !manifest.covered.contains(&key))
1319 })
1320 .collect();
1321
1322 if outstanding.is_empty() {
1323 return Ok(ResolvedVersion::Complete(manifest.version_of(entity_id)));
1324 }
1325
1326 let mut folded = 0usize;
1327 let mut exhausted = None;
1328 for path in &outstanding {
1329 if let Err(error) = self.fold_entity_versions(path, &mut manifest.entities, budget) {
1331 exhausted = Some(error);
1332 break;
1333 }
1334 if let Some(key) = manifest_key(&tenant_dir, path) {
1335 manifest.covered.insert(key);
1336 }
1337 folded += 1;
1338 }
1339
1340 if folded > 0 {
1342 manifest.store(&tenant_dir)?;
1343 }
1344
1345 if let Some(error) = exhausted {
1346 let remaining = outstanding.len() - folded;
1347 if is_budget_exhaustion(&error) {
1351 return Ok(ResolvedVersion::Incomplete {
1352 remaining,
1353 reason: error.to_string(),
1354 });
1355 }
1356 return Err(error);
1357 }
1358
1359 Ok(ResolvedVersion::Complete(manifest.version_of(entity_id)))
1360 }
1361
1362 pub(crate) fn record_flushed_versions(
1365 &self,
1366 tenant_id: &str,
1367 file: &Path,
1368 events: &[Event],
1369 ) -> Result<()> {
1370 let tenant_dir = self
1371 .storage_dir
1372 .join(sanitize_tenant_id_for_path(tenant_id)?);
1373 let Some(key) = manifest_key(&tenant_dir, file) else {
1374 return Ok(());
1375 };
1376 let mut manifest = VersionManifest::load(&tenant_dir).unwrap_or_default();
1377 manifest.observe_file(&key, events);
1378 manifest.store(&tenant_dir)
1379 }
1380
1381 fn fold_entity_versions(
1390 &self,
1391 file_path: &Path,
1392 versions: &mut HashMap<String, u64>,
1393 budget: &mut ArchiveReadBudget,
1394 ) -> Result<()> {
1395 use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
1396
1397 budget.check()?;
1398 let file = File::open(file_path).map_err(|e| {
1399 AllSourceError::StorageError(format!("Failed to open parquet file: {e}"))
1400 })?;
1401 let file_len = file
1402 .metadata()
1403 .map_err(|error| {
1404 AllSourceError::StorageError(format!("Failed to inspect archive file: {error}"))
1405 })?
1406 .len();
1407 budget.compressed(file_len)?;
1408
1409 let builder = ParquetRecordBatchReaderBuilder::try_new(file)
1410 .map_err(|error| unreadable(file_path, error))?;
1411
1412 for group in builder.metadata().row_groups() {
1415 let retained: i64 = [ENTITY_ID_COLUMN, VERSION_COLUMN]
1416 .iter()
1417 .map(|&column| group.column(column).uncompressed_size())
1418 .sum();
1419 budget.decoded_metadata(group.num_rows(), retained)?;
1420 }
1421
1422 let reader = builder
1423 .with_batch_size(1024)
1424 .build()
1425 .map_err(|error| unreadable(file_path, error))?;
1426
1427 for batch in reader {
1428 budget.check()?;
1429 let batch = batch.map_err(|error| unreadable(file_path, error))?;
1430 let entity_ids = batch
1431 .column(ENTITY_ID_COLUMN)
1432 .as_any()
1433 .downcast_ref::<arrow::array::StringArray>()
1434 .ok_or_else(|| {
1435 AllSourceError::StorageError("Invalid entity_id column".to_string())
1436 })?;
1437 let row_versions = batch
1438 .column(VERSION_COLUMN)
1439 .as_any()
1440 .downcast_ref::<arrow::array::UInt64Array>()
1441 .ok_or_else(|| {
1442 AllSourceError::StorageError("Invalid version column".to_string())
1443 })?;
1444
1445 for i in 0..batch.num_rows() {
1446 let version = row_versions.value(i);
1447 versions
1448 .entry(entity_ids.value(i).to_string())
1449 .and_modify(|current| *current = (*current).max(version))
1450 .or_insert(version);
1451 }
1452 }
1453
1454 Ok(())
1455 }
1456
1457 pub(crate) fn load_events_for_tenant_with_integrity(
1458 &self,
1459 tenant_id: &str,
1460 budget: Option<&mut ArchiveReadBudget>,
1461 ) -> Result<(Vec<Event>, bool)> {
1462 let mut events = Vec::new();
1463 let complete = self.for_each_tenant_file_events(tenant_id, budget, |batch| {
1464 events.extend(batch);
1465 Ok(())
1466 })?;
1467 Ok((events, complete))
1468 }
1469
1470 pub(crate) fn for_each_tenant_file_events(
1482 &self,
1483 tenant_id: &str,
1484 mut budget: Option<&mut ArchiveReadBudget>,
1485 mut visit: impl FnMut(Vec<Event>) -> Result<()>,
1486 ) -> Result<bool> {
1487 let require_complete = budget.is_some();
1488 let parquet_files = if let Some(budget) = budget.as_deref_mut() {
1489 self.list_complete_tenant_archive(tenant_id, budget)?
1490 } else {
1491 self.list_parquet_files_for_tenant(tenant_id)?
1492 };
1493 tracing::info!(
1494 tenant_id = tenant_id,
1495 file_count = parquet_files.len(),
1496 "load_events_for_tenant: walking tenant subtree only"
1497 );
1498
1499 let mut visited = 0usize;
1500 let mut skipped = 0usize;
1501 for file_path in parquet_files {
1502 tracing::debug!(
1503 tenant_id = tenant_id,
1504 file = %file_path.display(),
1505 "load_events_for_tenant: opening file"
1506 );
1507 match self.load_events_from_file_with_budget(
1512 &file_path,
1513 tenant_id,
1514 budget.as_deref_mut(),
1515 ) {
1516 Ok(file_events) => {
1517 visited += file_events.len();
1518 visit(file_events)?;
1519 }
1520 Err(e) => {
1521 tracing::error!(
1522 tenant_id = tenant_id,
1523 file = %file_path.display(),
1524 error = %e,
1525 require_complete,
1526 "Unreadable parquet file in tenant subtree"
1527 );
1528 skipped += 1;
1529 if require_complete {
1530 if let Some(budget) = budget.as_deref() {
1531 budget.check()?;
1532 }
1533 if is_budget_exhaustion(&e) {
1534 return Err(e);
1535 }
1536 return Err(AllSourceError::StorageError(format!(
1537 "Cannot verify conditional version from incomplete archive: {e}"
1538 )));
1539 }
1540 }
1541 }
1542 }
1543
1544 tracing::info!(
1545 tenant_id = tenant_id,
1546 event_count = visited,
1547 skipped_files = skipped,
1548 "load_events_for_tenant: complete"
1549 );
1550 Ok(require_complete && skipped == 0)
1553 }
1554
1555 pub fn storage_dir(&self) -> &Path {
1557 &self.storage_dir
1558 }
1559
1560 pub fn migrate_flat_layout(&self, dry_run: bool) -> Result<MigrationReport> {
1583 let flat_files = list_flat_layout_files(&self.storage_dir)?;
1584 let mut report = MigrationReport {
1585 dry_run,
1586 ..Default::default()
1587 };
1588
1589 for flat_file in flat_files {
1590 let events = self.load_events_from_file(&flat_file, "default")?;
1594 report.flat_files_seen += 1;
1595
1596 if events.is_empty() {
1597 if !dry_run {
1599 fs::remove_file(&flat_file).map_err(|e| {
1600 AllSourceError::StorageError(format!(
1601 "Failed to remove empty flat file {}: {e}",
1602 flat_file.display()
1603 ))
1604 })?;
1605 }
1606 report.flat_files_removed += 1;
1607 continue;
1608 }
1609
1610 let mut groups: HashMap<(String, String), Vec<Event>> = HashMap::new();
1616 for event in events {
1617 let key = (
1618 event.tenant_id_str().to_string(),
1619 event.timestamp().format("%Y-%m").to_string(),
1620 );
1621 groups.entry(key).or_default().push(event);
1622 }
1623
1624 for ((tenant, yyyy_mm), group_events) in groups {
1625 let count = group_events.len();
1626 if !dry_run {
1627 let safe_tenant = sanitize_tenant_id_for_path(&tenant)?;
1628 let target_dir = self.storage_dir.join(safe_tenant).join(&yyyy_mm);
1629 fs::create_dir_all(&target_dir).map_err(|e| {
1630 AllSourceError::StorageError(format!(
1631 "Failed to create partition {}: {e}",
1632 target_dir.display()
1633 ))
1634 })?;
1635 let filename = format!(
1636 "events-{}-{}.parquet",
1637 chrono::Utc::now().format("%Y%m%d-%H%M%S%3f"),
1638 uuid::Uuid::new_v4().as_simple()
1639 );
1640 let record_batch = self.events_to_record_batch(&group_events)?;
1641 let mut output = ArchiveOutput::new(
1642 &target_dir,
1643 filename.trim_end_matches(".parquet"),
1644 self.config.compression,
1645 ArchiveReadLimits::default().max_file_bytes,
1646 true,
1647 )?;
1648 output.stage(&record_batch)?;
1649 report.partitions_written += output.publish()?.len();
1650 }
1651 report.events_migrated += count;
1652 }
1653
1654 if !dry_run {
1655 fs::remove_file(&flat_file).map_err(|e| {
1656 AllSourceError::StorageError(format!(
1657 "Failed to remove flat file {} after migration: {e}",
1658 flat_file.display()
1659 ))
1660 })?;
1661 report.flat_files_removed += 1;
1662 }
1663 }
1664
1665 Ok(report)
1666 }
1667
1668 pub fn stats(&self) -> Result<StorageStats> {
1670 let parquet_files = find_parquet_files_recursive(&self.storage_dir)?;
1671 let mut total_size_bytes = 0u64;
1672 for path in &parquet_files {
1673 if let Ok(metadata) = fs::metadata(path) {
1674 total_size_bytes += metadata.len();
1675 }
1676 }
1677
1678 let current_batch_size: usize = self
1679 .current_batches
1680 .lock()
1681 .unwrap()
1682 .values()
1683 .map(Vec::len)
1684 .sum();
1685
1686 Ok(StorageStats {
1687 total_files: parquet_files.len(),
1688 total_size_bytes,
1689 storage_dir: self.storage_dir.clone(),
1690 current_batch_size,
1691 })
1692 }
1693}
1694
1695fn sanitize_tenant_id_for_path(tenant_id: &str) -> Result<&str> {
1708 if tenant_id.is_empty() {
1709 return Err(AllSourceError::StorageError(
1710 "tenant_id is empty (cannot derive partition path)".to_string(),
1711 ));
1712 }
1713 if tenant_id.len() > 128 {
1714 return Err(AllSourceError::StorageError(format!(
1715 "tenant_id is too long for partition path: {} bytes (max 128)",
1716 tenant_id.len()
1717 )));
1718 }
1719 if tenant_id == "." || tenant_id == ".." {
1720 return Err(AllSourceError::StorageError(format!(
1721 "tenant_id {tenant_id:?} is reserved"
1722 )));
1723 }
1724 for c in tenant_id.chars() {
1725 let ok = c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.';
1726 if !ok {
1727 return Err(AllSourceError::StorageError(format!(
1728 "tenant_id {tenant_id:?} contains disallowed character {c:?} for partition path"
1729 )));
1730 }
1731 }
1732 Ok(tenant_id)
1733}
1734
1735fn unreadable(path: &Path, error: impl std::fmt::Display) -> AllSourceError {
1738 AllSourceError::StorageError(format!(
1739 "Cannot verify conditional version from {}: {error}",
1740 path.display()
1741 ))
1742}
1743
1744fn row_group_may_hold_entity(
1755 group: &parquet::file::metadata::RowGroupMetaData,
1756 needle: &[u8],
1757) -> bool {
1758 let Some(statistics) = group.column(ENTITY_ID_COLUMN).statistics() else {
1759 return true;
1760 };
1761 let (Some(min), Some(max)) = (statistics.min_bytes_opt(), statistics.max_bytes_opt()) else {
1762 return true;
1763 };
1764 min <= needle && needle <= max
1765}
1766
1767fn manifest_key(tenant_dir: &Path, file: &Path) -> Option<String> {
1773 Some(
1774 file.strip_prefix(tenant_dir)
1775 .ok()?
1776 .to_string_lossy()
1777 .into_owned(),
1778 )
1779}
1780
1781fn is_budget_exhaustion(error: &AllSourceError) -> bool {
1784 matches!(error, AllSourceError::ArchiveBudgetExceeded { .. })
1785}
1786
1787fn partition_path_for_tenant(
1792 root: &Path,
1793 tenant_id: &str,
1794 when: chrono::DateTime<chrono::Utc>,
1795) -> Result<PathBuf> {
1796 let safe = sanitize_tenant_id_for_path(tenant_id)?;
1797 Ok(root.join(safe).join(when.format("%Y-%m").to_string()))
1798}
1799
1800fn tenant_id_from_path(root: &Path, file_path: &Path) -> String {
1810 let Ok(rel) = file_path.strip_prefix(root) else {
1811 return "default".to_string();
1812 };
1813 let mut comps = rel.components();
1814 let first = comps.next();
1815 let next = comps.next();
1816 match (first, next) {
1817 (Some(std::path::Component::Normal(tenant)), Some(_)) => {
1819 tenant.to_string_lossy().into_owned()
1820 }
1821 _ => "default".to_string(),
1823 }
1824}
1825
1826fn list_flat_layout_files(root: &Path) -> Result<Vec<PathBuf>> {
1832 let entries = fs::read_dir(root).map_err(|e| {
1833 AllSourceError::StorageError(format!("Failed to read storage directory: {e}"))
1834 })?;
1835 let mut out: Vec<PathBuf> = entries
1836 .filter_map(std::result::Result::ok)
1837 .filter_map(|entry| {
1838 let ft = entry.file_type().ok()?;
1839 if !ft.is_file() {
1840 return None;
1841 }
1842 let path = entry.path();
1843 if path.extension().and_then(|s| s.to_str()) == Some("parquet") {
1844 Some(path)
1845 } else {
1846 None
1847 }
1848 })
1849 .collect();
1850 out.sort();
1851 Ok(out)
1852}
1853
1854fn find_parquet_files_recursive(root: &Path) -> Result<Vec<PathBuf>> {
1865 find_parquet_files_recursive_with_integrity(root, None)
1866}
1867
1868fn find_parquet_files_recursive_with_integrity(
1869 root: &Path,
1870 mut budget: Option<&mut ArchiveReadBudget>,
1871) -> Result<Vec<PathBuf>> {
1872 let require_complete = budget.is_some();
1873 let mut out = Vec::new();
1874 let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
1875
1876 while let Some(dir) = stack.pop() {
1877 if let Some(budget) = budget.as_deref() {
1878 budget.check()?;
1879 }
1880 let entries = match fs::read_dir(&dir) {
1881 Ok(e) => e,
1882 Err(e) if dir == root || require_complete => {
1886 return Err(AllSourceError::StorageError(format!(
1887 "Failed to read storage directory: {e}"
1888 )));
1889 }
1890 Err(_) => continue,
1891 };
1892
1893 for entry in entries {
1894 if let Some(budget) = budget.as_deref_mut() {
1895 budget.entry()?;
1896 }
1897 let entry = match entry {
1898 Ok(entry) => entry,
1899 Err(error) if require_complete => {
1900 return Err(AllSourceError::StorageError(format!(
1901 "Failed to enumerate complete archive: {error}"
1902 )));
1903 }
1904 Err(_) => continue,
1905 };
1906 let path = entry.path();
1907 if pending_marker(&path) && require_complete {
1908 return Err(AllSourceError::StorageError(
1909 "Archive output publication incomplete".into(),
1910 ));
1911 }
1912 let ft = match entry.file_type() {
1916 Ok(file_type) => file_type,
1917 Err(error) if require_complete => {
1918 return Err(AllSourceError::StorageError(format!(
1919 "Failed to inspect complete archive entry: {error}"
1920 )));
1921 }
1922 Err(_) => continue,
1923 };
1924 if ft.is_dir() {
1925 stack.push(path);
1926 } else if ft.is_file() && pending_part(&path) {
1927 if require_complete {
1928 return Err(AllSourceError::StorageError(
1929 "Archive output publication incomplete".into(),
1930 ));
1931 }
1932 } else if ft.is_file()
1933 && path
1934 .extension()
1935 .and_then(|ext| ext.to_str())
1936 .is_some_and(|ext| ext == "parquet")
1937 {
1938 if let Some(budget) = budget.as_deref_mut() {
1939 budget.file()?;
1940 }
1941 out.push(path);
1942 }
1943 }
1944 }
1945
1946 out.sort();
1947 if let Some(budget) = budget {
1948 budget.check()?;
1949 }
1950 Ok(out)
1951}
1952
1953impl Drop for ParquetStorage {
1954 fn drop(&mut self) {
1955 if let Err(e) = self.flush_on_shutdown() {
1957 tracing::error!("Failed to flush events on drop: {}", e);
1958 }
1959 }
1960}
1961
1962#[derive(Debug, Default, Clone, serde::Serialize)]
1964pub struct MigrationReport {
1965 pub dry_run: bool,
1967 pub flat_files_seen: usize,
1969 pub flat_files_removed: usize,
1971 pub partitions_written: usize,
1973 pub events_migrated: usize,
1975}
1976
1977#[derive(Debug, serde::Serialize)]
1978pub struct StorageStats {
1979 pub total_files: usize,
1980 pub total_size_bytes: u64,
1981 pub storage_dir: PathBuf,
1982 pub current_batch_size: usize,
1983}
1984
1985#[cfg(test)]
1986mod tests {
1987 use super::*;
1988 use arrow::datatypes::{DataType, Field, TimeUnit};
1989 use serde_json::json;
1990 use std::sync::Arc;
1991 use tempfile::TempDir;
1992
1993 fn create_test_event(entity_id: &str) -> Event {
1994 Event::reconstruct_from_strings(
1995 uuid::Uuid::new_v4(),
1996 "test.event".to_string(),
1997 entity_id.to_string(),
1998 "default".to_string(),
1999 json!({
2000 "test": "data",
2001 "value": 42
2002 }),
2003 chrono::Utc::now(),
2004 None,
2005 1,
2006 )
2007 }
2008
2009 #[test]
2010 fn valid_time_round_trips_through_parquet() {
2011 let temp_dir = TempDir::new().unwrap();
2012 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2013 let valid_from = chrono::DateTime::from_timestamp_micros(1_700_000_000_123_456).unwrap();
2014 let valid_to = chrono::DateTime::from_timestamp_micros(1_700_000_900_000_001).unwrap();
2015
2016 let mut event = create_test_event("entity-valid");
2017 event.valid_from = Some(valid_from);
2018 event.valid_to = Some(valid_to);
2019 let mut open_ended = create_test_event("entity-open");
2020 open_ended.valid_from = Some(valid_from);
2021 storage.append_event(event).unwrap();
2022 storage.append_event(open_ended).unwrap();
2023 storage.flush().unwrap();
2024
2025 let mut loaded = storage.load_all_events().unwrap();
2026 loaded.sort_by(|a, b| a.entity_id_str().cmp(b.entity_id_str()));
2027 assert_eq!(loaded.len(), 2);
2028 assert_eq!(loaded[0].entity_id_str(), "entity-open");
2029 assert_eq!(loaded[0].valid_from, Some(valid_from));
2030 assert_eq!(loaded[0].valid_to, None);
2031 assert_eq!(loaded[1].valid_from, Some(valid_from));
2032 assert_eq!(loaded[1].valid_to, Some(valid_to));
2033 }
2034
2035 #[test]
2038 fn a_parquet_file_without_valid_time_columns_reads_back_unset() {
2039 use arrow::array::{StringArray, TimestampMicrosecondArray, UInt64Array};
2040 use parquet::arrow::ArrowWriter;
2041
2042 let temp_dir = TempDir::new().unwrap();
2043 let path = temp_dir.path().join("pre-valid-time.parquet");
2044 let ids = [
2045 uuid::Uuid::new_v4().to_string(),
2046 uuid::Uuid::new_v4().to_string(),
2047 ];
2048 let timestamps = [1_700_000_000_000_000_i64, 1_700_000_100_000_000_i64];
2049 let schema = Arc::new(Schema::new(vec![
2050 Field::new("event_id", DataType::Utf8, false),
2051 Field::new("event_type", DataType::Utf8, false),
2052 Field::new("entity_id", DataType::Utf8, false),
2053 Field::new("payload", DataType::Utf8, false),
2054 Field::new(
2055 "timestamp",
2056 DataType::Timestamp(TimeUnit::Microsecond, None),
2057 false,
2058 ),
2059 Field::new("metadata", DataType::Utf8, true),
2060 Field::new("version", DataType::UInt64, false),
2061 ]));
2062 let batch = RecordBatch::try_new(
2063 schema.clone(),
2064 vec![
2065 Arc::new(StringArray::from(vec![ids[0].as_str(), ids[1].as_str()])),
2066 Arc::new(StringArray::from(vec!["test.event", "test.event"])),
2067 Arc::new(StringArray::from(vec!["entity-a", "entity-b"])),
2068 Arc::new(StringArray::from(vec!["{}", "{}"])),
2069 Arc::new(TimestampMicrosecondArray::from(timestamps.to_vec())),
2070 Arc::new(StringArray::from(vec![None::<&str>, None])),
2071 Arc::new(UInt64Array::from(vec![1_u64, 2])),
2072 ],
2073 )
2074 .unwrap();
2075 let mut writer = ArrowWriter::try_new(File::create(&path).unwrap(), schema, None).unwrap();
2076 writer.write(&batch).unwrap();
2077 writer.close().unwrap();
2078
2079 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2080 let loaded = storage
2081 .load_events_from_file_path(&path, "default")
2082 .unwrap();
2083
2084 assert_eq!(loaded.len(), 2);
2085 assert_eq!(loaded[0].id.to_string(), ids[0]);
2086 assert_eq!(loaded[0].timestamp.timestamp_micros(), timestamps[0]);
2087 assert_eq!(loaded[0].valid_from, None);
2088 assert_eq!(loaded[0].valid_to, None);
2089 assert_eq!(loaded[1].valid_from, None);
2090 assert_eq!(loaded[1].valid_to, None);
2091 }
2092
2093 #[test]
2094 fn test_parquet_storage_write_read() {
2095 let temp_dir = TempDir::new().unwrap();
2096 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2097
2098 for i in 0..10 {
2100 let event = create_test_event(&format!("entity-{i}"));
2101 storage.append_event(event).unwrap();
2102 }
2103
2104 storage.flush().unwrap();
2106
2107 let loaded_events = storage.load_all_events().unwrap();
2109 assert_eq!(loaded_events.len(), 10);
2110 }
2111
2112 #[test]
2113 fn test_storage_stats() {
2114 let temp_dir = TempDir::new().unwrap();
2115 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2116
2117 for i in 0..5 {
2119 storage
2120 .append_event(create_test_event(&format!("entity-{i}")))
2121 .unwrap();
2122 }
2123 storage.flush().unwrap();
2124
2125 let stats = storage.stats().unwrap();
2126 assert_eq!(stats.total_files, 1);
2127 assert!(stats.total_size_bytes > 0);
2128 }
2129
2130 #[test]
2131 fn test_default_batch_size() {
2132 let temp_dir = TempDir::new().unwrap();
2133 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2134
2135 assert_eq!(storage.batch_size(), DEFAULT_BATCH_SIZE);
2137 assert_eq!(storage.batch_size(), 10_000);
2138 }
2139
2140 #[test]
2141 fn test_custom_config() {
2142 let temp_dir = TempDir::new().unwrap();
2143 let config = ParquetStorageConfig {
2144 batch_size: 5_000,
2145 flush_timeout: Duration::from_secs(2),
2146 compression: parquet::basic::Compression::SNAPPY,
2147 file_namer: None,
2148 };
2149 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2150
2151 assert_eq!(storage.batch_size(), 5_000);
2152 assert_eq!(storage.flush_timeout(), Duration::from_secs(2));
2153 }
2154
2155 #[test]
2156 fn test_batch_write() {
2157 let temp_dir = TempDir::new().unwrap();
2158 let config = ParquetStorageConfig {
2159 batch_size: 100, ..Default::default()
2161 };
2162 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2163
2164 let events: Vec<Event> = (0..250)
2172 .map(|i| create_test_event(&format!("entity-{i}")))
2173 .collect();
2174
2175 let result = storage.batch_write(events).unwrap();
2176 assert_eq!(result.events_written, 250);
2177 assert_eq!(result.batches_flushed, 1);
2178 assert_eq!(storage.pending_count(), 0);
2179
2180 storage.flush().unwrap();
2182
2183 let loaded = storage.load_all_events().unwrap();
2185 assert_eq!(loaded.len(), 250);
2186 }
2187
2188 #[test]
2189 fn test_auto_flush_on_batch_size() {
2190 let temp_dir = TempDir::new().unwrap();
2191 let config = ParquetStorageConfig {
2192 batch_size: 10, ..Default::default()
2194 };
2195 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2196
2197 for i in 0..15 {
2199 storage
2200 .append_event(create_test_event(&format!("entity-{i}")))
2201 .unwrap();
2202 }
2203
2204 assert_eq!(storage.pending_count(), 5);
2206
2207 let stats = storage.batch_stats();
2208 assert_eq!(stats.events_written, 10);
2209 assert_eq!(stats.batches_written, 1);
2210 assert_eq!(stats.size_flushes, 1);
2211 }
2212
2213 #[test]
2214 fn test_flush_on_shutdown() {
2215 let temp_dir = TempDir::new().unwrap();
2216 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2217
2218 for i in 0..5 {
2220 storage
2221 .append_event(create_test_event(&format!("entity-{i}")))
2222 .unwrap();
2223 }
2224
2225 assert_eq!(storage.pending_count(), 5);
2226
2227 let flushed = storage.flush_on_shutdown().unwrap();
2229 assert_eq!(flushed, 5);
2230 assert_eq!(storage.pending_count(), 0);
2231
2232 let loaded = storage.load_all_events().unwrap();
2234 assert_eq!(loaded.len(), 5);
2235 }
2236
2237 #[test]
2238 fn test_thread_safe_writes() {
2239 let temp_dir = TempDir::new().unwrap();
2240 let config = ParquetStorageConfig {
2241 batch_size: 100,
2242 ..Default::default()
2243 };
2244 let storage = Arc::new(ParquetStorage::with_config(temp_dir.path(), config).unwrap());
2245
2246 let events_per_thread = 50;
2247 let thread_count = 4;
2248
2249 std::thread::scope(|s| {
2250 for t in 0..thread_count {
2251 let storage_ref = Arc::clone(&storage);
2252 s.spawn(move || {
2253 for i in 0..events_per_thread {
2254 let event = create_test_event(&format!("thread-{t}-entity-{i}"));
2255 storage_ref.append_event(event).unwrap();
2256 }
2257 });
2258 }
2259 });
2260
2261 storage.flush().unwrap();
2263
2264 let loaded = storage.load_all_events().unwrap();
2266 assert_eq!(loaded.len(), events_per_thread * thread_count);
2267 }
2268
2269 #[test]
2270 fn test_batch_stats() {
2271 let temp_dir = TempDir::new().unwrap();
2272 let config = ParquetStorageConfig {
2273 batch_size: 50,
2274 ..Default::default()
2275 };
2276 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2277
2278 let events: Vec<Event> = (0..100)
2283 .map(|i| create_test_event(&format!("entity-{i}")))
2284 .collect();
2285
2286 storage.batch_write(events).unwrap();
2287
2288 let stats = storage.batch_stats();
2289 assert_eq!(stats.batches_written, 1);
2290 assert_eq!(stats.events_written, 100);
2291 assert!(stats.avg_batch_size > 0.0);
2292 assert!(stats.events_per_sec > 0.0);
2293 assert_eq!(stats.size_flushes, 1);
2294 }
2295
2296 #[test]
2297 fn test_config_presets() {
2298 let high_throughput = ParquetStorageConfig::high_throughput();
2299 assert_eq!(high_throughput.batch_size, 50_000);
2300 assert_eq!(high_throughput.flush_timeout, Duration::from_secs(10));
2301
2302 let low_latency = ParquetStorageConfig::low_latency();
2303 assert_eq!(low_latency.batch_size, 1_000);
2304 assert_eq!(low_latency.flush_timeout, Duration::from_secs(1));
2305
2306 let default = ParquetStorageConfig::default();
2307 assert_eq!(default.batch_size, DEFAULT_BATCH_SIZE);
2308 assert_eq!(default.batch_size, 10_000);
2309 }
2310
2311 #[test]
2314 #[ignore]
2315 fn test_batch_write_throughput() {
2316 let temp_dir = TempDir::new().unwrap();
2317 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2318
2319 let event_count = 50_000;
2320
2321 let events: Vec<Event> = (0..event_count)
2323 .map(|i| create_test_event(&format!("entity-{i}")))
2324 .collect();
2325
2326 let start = std::time::Instant::now();
2327 let result = storage.batch_write(events).unwrap();
2328 storage.flush().unwrap(); let batch_duration = start.elapsed();
2330
2331 let batch_stats = storage.batch_stats();
2332
2333 println!("\n=== Parquet Batch Write Performance (BATCH_SIZE=10,000) ===");
2334 println!("Events: {event_count}");
2335 println!("Duration: {batch_duration:?}");
2336 println!("Events/sec: {:.0}", result.events_per_sec);
2337 println!("Batches written: {}", batch_stats.batches_written);
2338 println!("Avg batch size: {:.0}", batch_stats.avg_batch_size);
2339 println!("Bytes written: {} KB", batch_stats.bytes_written / 1024);
2340
2341 assert!(
2344 result.events_per_sec > 10_000.0,
2345 "Batch write throughput too low: {:.0} events/sec (expected >10K in debug, >100K in release)",
2346 result.events_per_sec
2347 );
2348 }
2349
2350 #[test]
2352 #[ignore]
2353 fn test_single_event_write_baseline() {
2354 let temp_dir = TempDir::new().unwrap();
2355 let config = ParquetStorageConfig {
2356 batch_size: 1, ..Default::default()
2358 };
2359 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2360
2361 let event_count = 1_000; let start = std::time::Instant::now();
2364 for i in 0..event_count {
2365 let event = create_test_event(&format!("entity-{i}"));
2366 storage.append_event(event).unwrap();
2367 }
2368 let duration = start.elapsed();
2369
2370 let events_per_sec = f64::from(event_count) / duration.as_secs_f64();
2371
2372 println!("\n=== Single-Event Write Baseline ===");
2373 println!("Events: {event_count}");
2374 println!("Duration: {duration:?}");
2375 println!("Events/sec: {events_per_sec:.0}");
2376
2377 }
2380
2381 fn touch_parquet(path: &Path) {
2391 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2392 std::fs::write(path, b"").unwrap();
2393 }
2394
2395 #[test]
2396 fn test_walker_finds_files_in_flat_layout() {
2397 let temp_dir = TempDir::new().unwrap();
2398 let root = temp_dir.path();
2399 touch_parquet(&root.join("events-20260101-120000000-aaaa.parquet"));
2400 touch_parquet(&root.join("events-20260101-130000000-bbbb.parquet"));
2401
2402 let mut found = find_parquet_files_recursive(root).unwrap();
2403 found.sort();
2404 assert_eq!(found.len(), 2);
2405 assert!(
2406 found[0]
2407 .file_name()
2408 .unwrap()
2409 .to_str()
2410 .unwrap()
2411 .starts_with("events-"),
2412 "expected events-* file, got {found:?}"
2413 );
2414 }
2415
2416 #[test]
2417 fn test_walker_finds_files_in_tenant_partitioned_tree() {
2418 let temp_dir = TempDir::new().unwrap();
2419 let root = temp_dir.path();
2420 touch_parquet(&root.join("tenant-a/2026-01/events-20260101-120000000-aaaa.parquet"));
2422 touch_parquet(&root.join("tenant-a/2026-02/events-20260201-120000000-bbbb.parquet"));
2423 touch_parquet(&root.join("tenant-b/2026-01/events-20260103-120000000-cccc.parquet"));
2424
2425 let found = find_parquet_files_recursive(root).unwrap();
2426 assert_eq!(found.len(), 3);
2427 assert!(found[0].to_str().unwrap().contains("tenant-a"));
2430 assert!(found[1].to_str().unwrap().contains("tenant-a"));
2431 assert!(found[2].to_str().unwrap().contains("tenant-b"));
2432 }
2433
2434 #[test]
2435 fn test_walker_handles_mixed_legacy_and_partitioned_layouts() {
2436 let temp_dir = TempDir::new().unwrap();
2441 let root = temp_dir.path();
2442 touch_parquet(&root.join("events-legacy-aaaa.parquet"));
2443 touch_parquet(&root.join("tenant-a/2026-01/events-new-bbbb.parquet"));
2444
2445 let found = find_parquet_files_recursive(root).unwrap();
2446 assert_eq!(found.len(), 2);
2447 }
2448
2449 #[test]
2450 fn test_walker_ignores_non_parquet_files() {
2451 let temp_dir = TempDir::new().unwrap();
2452 let root = temp_dir.path();
2453 std::fs::write(root.join("README.md"), b"hello").unwrap();
2454 std::fs::write(root.join("events.json"), b"[]").unwrap();
2455 touch_parquet(&root.join("events-20260101-120000000-aaaa.parquet"));
2456 std::fs::write(root.join("not-a-parquet-file.bin"), b"").unwrap();
2459
2460 let found = find_parquet_files_recursive(root).unwrap();
2461 assert_eq!(found.len(), 1);
2462 assert_eq!(
2463 found[0].extension().and_then(|s| s.to_str()),
2464 Some("parquet")
2465 );
2466 }
2467
2468 fn event_with_tenant(tenant: &str, entity_id: &str) -> Event {
2472 Event::reconstruct_from_strings(
2473 uuid::Uuid::new_v4(),
2474 "test.event".to_string(),
2475 entity_id.to_string(),
2476 tenant.to_string(),
2477 json!({"k": "v"}),
2478 chrono::Utc::now(),
2479 None,
2480 1,
2481 )
2482 }
2483
2484 #[test]
2485 fn test_flush_writes_into_per_tenant_partition() {
2486 let temp_dir = TempDir::new().unwrap();
2490 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2491
2492 for i in 0..3 {
2493 storage
2494 .append_event(event_with_tenant("default", &format!("entity-{i}")))
2495 .unwrap();
2496 }
2497 storage.flush().unwrap();
2498
2499 let parquet_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
2500 assert_eq!(parquet_files.len(), 1);
2501
2502 let rel = parquet_files[0]
2503 .strip_prefix(temp_dir.path())
2504 .unwrap()
2505 .to_string_lossy()
2506 .into_owned();
2507 let parts: Vec<&str> = rel.split(std::path::MAIN_SEPARATOR).collect();
2509 assert_eq!(parts.len(), 3, "expected tenant/yyyy-mm/file, got {rel}");
2510 assert_eq!(parts[0], "default");
2511 assert!(
2514 parts[1].len() == 7 && parts[1].as_bytes()[4] == b'-',
2515 "expected yyyy-mm, got {}",
2516 parts[1]
2517 );
2518 assert!(parts[2].starts_with("events-") && parts[2].ends_with(".parquet"));
2519
2520 let loaded = storage.load_all_events().unwrap();
2521 assert_eq!(loaded.len(), 3);
2522 }
2523
2524 #[test]
2525 fn test_multiple_tenants_get_isolated_subtrees() {
2526 let temp_dir = TempDir::new().unwrap();
2529 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2530
2531 for i in 0..2 {
2532 storage
2533 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2534 .unwrap();
2535 }
2536 for i in 0..3 {
2537 storage
2538 .append_event(event_with_tenant("bob", &format!("b-{i}")))
2539 .unwrap();
2540 }
2541 storage.flush().unwrap();
2542
2543 let alice_subtree = temp_dir.path().join("alice");
2544 let bob_subtree = temp_dir.path().join("bob");
2545 assert!(alice_subtree.is_dir(), "alice should have its own subtree");
2546 assert!(bob_subtree.is_dir(), "bob should have its own subtree");
2547
2548 let alice_files = find_parquet_files_recursive(&alice_subtree).unwrap();
2549 let bob_files = find_parquet_files_recursive(&bob_subtree).unwrap();
2550 assert_eq!(alice_files.len(), 1);
2551 assert_eq!(bob_files.len(), 1);
2552
2553 let loaded = storage.load_all_events().unwrap();
2556 let (alice_count, bob_count) =
2557 loaded
2558 .iter()
2559 .fold((0, 0), |(a, b), e| match e.tenant_id_str() {
2560 "alice" => (a + 1, b),
2561 "bob" => (a, b + 1),
2562 _ => (a, b),
2563 });
2564 assert_eq!(alice_count, 2);
2565 assert_eq!(bob_count, 3);
2566 }
2567
2568 #[test]
2569 fn test_size_flush_only_drains_full_tenant() {
2570 let temp_dir = TempDir::new().unwrap();
2574 let config = ParquetStorageConfig {
2575 batch_size: 5,
2576 ..Default::default()
2577 };
2578 let storage = ParquetStorage::with_config(temp_dir.path(), config).unwrap();
2579
2580 for i in 0..5 {
2583 storage
2584 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2585 .unwrap();
2586 }
2587 for i in 0..2 {
2589 storage
2590 .append_event(event_with_tenant("bob", &format!("b-{i}")))
2591 .unwrap();
2592 }
2593
2594 assert_eq!(
2595 storage.pending_count(),
2596 2,
2597 "only bob's 2 events should be pending"
2598 );
2599
2600 let parquet_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
2601 assert_eq!(parquet_files.len(), 1, "only alice should have flushed");
2602 assert!(
2603 parquet_files[0]
2604 .to_string_lossy()
2605 .contains(&format!("alice{}", std::path::MAIN_SEPARATOR)),
2606 "expected alice partition, got {}",
2607 parquet_files[0].display()
2608 );
2609 }
2610
2611 #[test]
2612 fn test_tenant_id_from_path_recovers_tenant_for_partitioned_files() {
2613 let root = Path::new("/data/storage");
2614 let f = Path::new("/data/storage/alice/2026-04/events-20260426-120000000-aaaa.parquet");
2615 assert_eq!(tenant_id_from_path(root, f), "alice");
2616 }
2617
2618 #[test]
2619 fn test_tenant_id_from_path_falls_back_to_default_for_legacy_flat_layout() {
2620 let root = Path::new("/data/storage");
2621 let f = Path::new("/data/storage/events-20260426-120000000-aaaa.parquet");
2622 assert_eq!(tenant_id_from_path(root, f), "default");
2625 }
2626
2627 #[test]
2628 fn test_sanitize_tenant_id_for_path_accepts_safe_inputs() {
2629 for ok in [
2630 "default",
2631 "system",
2632 "1e6b2d1c-2f64-4441-9cf9-42f2e451aa17",
2633 "onboard-diagnostic-160-at-example-com",
2634 "tenant_with_underscore",
2635 "v1.0",
2636 ] {
2637 assert!(
2638 sanitize_tenant_id_for_path(ok).is_ok(),
2639 "{ok:?} should be accepted"
2640 );
2641 }
2642 }
2643
2644 #[test]
2645 fn test_sanitize_tenant_id_for_path_rejects_unsafe_inputs() {
2646 for bad in [
2647 "", "..", ".", "foo/bar", "foo\\bar", "foo bar", "foo\nbar", "foo\0bar", "tenant?", "tenant*", ] {
2658 assert!(
2659 sanitize_tenant_id_for_path(bad).is_err(),
2660 "{bad:?} should be rejected"
2661 );
2662 }
2663
2664 let too_long = "a".repeat(129);
2666 assert!(sanitize_tenant_id_for_path(&too_long).is_err());
2667 }
2668
2669 #[test]
2670 fn test_partition_path_for_tenant_shape() {
2671 let root = Path::new("/data");
2672 let when = chrono::DateTime::parse_from_rfc3339("2026-04-26T12:00:00Z")
2673 .unwrap()
2674 .with_timezone(&chrono::Utc);
2675 let path = partition_path_for_tenant(root, "alice", when).unwrap();
2676 assert_eq!(path, Path::new("/data/alice/2026-04"));
2677 }
2678
2679 #[test]
2680 fn test_append_event_rejects_unsafe_tenant_at_flush() {
2681 let temp_dir = TempDir::new().unwrap();
2687 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2688
2689 storage
2693 .append_event(event_with_tenant("../escape", "e-0"))
2694 .unwrap();
2695 let result = storage.flush();
2696 assert!(result.is_err(), "flush should reject unsafe tenant_id");
2697 let msg = format!("{}", result.unwrap_err());
2698 assert!(
2699 msg.contains("disallowed character") || msg.contains("reserved"),
2700 "expected sanitization error message, got: {msg}"
2701 );
2702 }
2703
2704 #[test]
2709 fn test_load_events_for_tenant_only_walks_target_subtree() {
2710 let temp_dir = TempDir::new().unwrap();
2715 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2716
2717 for i in 0..2 {
2718 storage
2719 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2720 .unwrap();
2721 }
2722 for i in 0..3 {
2723 storage
2724 .append_event(event_with_tenant("bob", &format!("b-{i}")))
2725 .unwrap();
2726 }
2727 for i in 0..1 {
2728 storage
2729 .append_event(event_with_tenant("carol", &format!("c-{i}")))
2730 .unwrap();
2731 }
2732 storage.flush().unwrap();
2733
2734 let alice_files = storage.list_parquet_files_for_tenant("alice").unwrap();
2735 assert_eq!(alice_files.len(), 1);
2736 assert!(
2737 alice_files[0]
2738 .to_string_lossy()
2739 .contains(&format!("alice{}", std::path::MAIN_SEPARATOR)),
2740 "expected alice file, got {}",
2741 alice_files[0].display()
2742 );
2743 for f in &alice_files {
2747 let s = f.to_string_lossy();
2748 assert!(!s.contains("bob"), "alice listing leaked bob file: {s}");
2749 assert!(!s.contains("carol"), "alice listing leaked carol file: {s}");
2750 }
2751
2752 let alice_events = storage.load_events_for_tenant("alice").unwrap();
2753 assert_eq!(alice_events.len(), 2);
2754 for e in &alice_events {
2755 assert_eq!(e.tenant_id_str(), "alice");
2756 }
2757
2758 let bob_events = storage.load_events_for_tenant("bob").unwrap();
2759 assert_eq!(bob_events.len(), 3);
2760 for e in &bob_events {
2761 assert_eq!(e.tenant_id_str(), "bob");
2762 }
2763
2764 let carol_events = storage.load_events_for_tenant("carol").unwrap();
2765 assert_eq!(carol_events.len(), 1);
2766 assert_eq!(carol_events[0].tenant_id_str(), "carol");
2767 }
2768
2769 #[test]
2770 fn test_load_events_for_tenant_returns_empty_when_subtree_missing() {
2771 let temp_dir = TempDir::new().unwrap();
2775 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2776
2777 storage
2780 .append_event(event_with_tenant("alice", "a-0"))
2781 .unwrap();
2782 storage.flush().unwrap();
2783
2784 let files = storage
2785 .list_parquet_files_for_tenant("nobody-here")
2786 .unwrap();
2787 assert!(files.is_empty());
2788
2789 let events = storage.load_events_for_tenant("nobody-here").unwrap();
2790 assert!(events.is_empty());
2791 }
2792
2793 #[test]
2794 fn test_load_events_for_tenant_rejects_unsafe_tenant_id() {
2795 let temp_dir = TempDir::new().unwrap();
2798 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2799
2800 for unsafe_tid in ["..", "a/b", "a\\b", "", "a..b/.."] {
2801 let result = storage.load_events_for_tenant(unsafe_tid);
2802 assert!(
2803 result.is_err(),
2804 "tenant_id {unsafe_tid:?} should have been rejected"
2805 );
2806 }
2807 }
2808
2809 #[test]
2810 fn test_load_events_for_tenant_ignores_legacy_flat_layout_files() {
2811 let temp_dir = TempDir::new().unwrap();
2819 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2820
2821 let _flat = seed_flat_layout_file(&storage, 4);
2823
2824 let default_events = storage.load_events_for_tenant("default").unwrap();
2827 assert!(
2828 default_events.is_empty(),
2829 "tenant-scoped load must not pick up flat-layout files; got {} events",
2830 default_events.len()
2831 );
2832
2833 let all_events = storage.load_all_events().unwrap();
2835 assert_eq!(all_events.len(), 4);
2836 }
2837
2838 #[test]
2843 fn test_write_atomic_parquet_emits_file_under_tenant_partition() {
2844 let temp_dir = TempDir::new().unwrap();
2849 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2850
2851 let events: Vec<Event> = (0..3)
2852 .map(|i| event_with_tenant("alice", &format!("a-{i}")))
2853 .collect();
2854
2855 let final_path = storage
2856 .write_atomic_parquet("alice", "snapshot.alice.range", &events)
2857 .unwrap();
2858
2859 let rel = final_path
2861 .strip_prefix(temp_dir.path())
2862 .unwrap()
2863 .to_string_lossy()
2864 .into_owned();
2865 let parts: Vec<&str> = rel.split(std::path::MAIN_SEPARATOR).collect();
2866 assert_eq!(parts.len(), 3, "expected tenant/yyyy-mm/file, got {rel}");
2867 assert_eq!(parts[0], "alice");
2868 assert_eq!(parts[2], "snapshot.alice.range.parquet");
2869
2870 assert!(final_path.is_file());
2872 let tmp = final_path.with_extension("parquet.tmp");
2873 assert!(
2874 !tmp.exists(),
2875 "tmp should have been renamed away; still at {}",
2876 tmp.display()
2877 );
2878
2879 let loaded = storage.load_events_for_tenant("alice").unwrap();
2881 assert_eq!(loaded.len(), 3);
2882 }
2883
2884 #[test]
2885 fn test_write_atomic_parquet_rejects_empty_events() {
2886 let temp_dir = TempDir::new().unwrap();
2887 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2888 let result = storage.write_atomic_parquet("alice", "snap", &[]);
2889 assert!(result.is_err());
2890 }
2891
2892 #[test]
2893 fn test_write_atomic_parquet_rejects_unsafe_tenant() {
2894 let temp_dir = TempDir::new().unwrap();
2895 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2896 let events = [event_with_tenant("alice", "e-0")];
2897 for unsafe_tid in ["..", "a/b", ""] {
2898 let result = storage.write_atomic_parquet(unsafe_tid, "snap", &events);
2899 assert!(
2900 result.is_err(),
2901 "unsafe tenant_id {unsafe_tid:?} should have been rejected"
2902 );
2903 }
2904 }
2905
2906 #[test]
2907 fn test_cleanup_partial_writes_removes_orphan_tmps() {
2908 let temp_dir = TempDir::new().unwrap();
2912 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2913
2914 for i in 0..2 {
2917 storage
2918 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2919 .unwrap();
2920 }
2921 storage.flush().unwrap();
2922 let real_files_before = find_parquet_files_recursive(temp_dir.path()).unwrap();
2923 assert_eq!(real_files_before.len(), 1);
2924
2925 let alice_subtree = temp_dir.path().join("alice");
2927 let orphan_dir = real_files_before[0].parent().unwrap();
2928 let orphan_path = orphan_dir.join("snapshot.alice.crashed.parquet.tmp");
2929 std::fs::write(&orphan_path, b"fake partial parquet").unwrap();
2930 assert!(orphan_path.is_file());
2931
2932 let nested_dir = alice_subtree.join("2099-01");
2934 std::fs::create_dir_all(&nested_dir).unwrap();
2935 let nested_orphan = nested_dir.join("events-x.parquet.tmp");
2936 std::fs::write(&nested_orphan, b"junk").unwrap();
2937
2938 let removed = storage.cleanup_partial_writes().unwrap();
2939 assert_eq!(removed, 2, "two orphan tmps should have been cleaned");
2940 assert!(!orphan_path.exists());
2941 assert!(!nested_orphan.exists());
2942
2943 let real_files_after = find_parquet_files_recursive(temp_dir.path()).unwrap();
2945 assert_eq!(real_files_after, real_files_before);
2946 }
2947
2948 #[test]
2949 fn test_cleanup_partial_writes_quarantines_zero_byte_parquet() {
2950 let temp_dir = TempDir::new().unwrap();
2955 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
2956
2957 for i in 0..2 {
2959 storage
2960 .append_event(event_with_tenant("alice", &format!("a-{i}")))
2961 .unwrap();
2962 }
2963 storage.flush().unwrap();
2964 let healthy_files_before = find_parquet_files_recursive(temp_dir.path()).unwrap();
2965 assert_eq!(healthy_files_before.len(), 1);
2966 let healthy_file = &healthy_files_before[0];
2967 let healthy_dir = healthy_file.parent().unwrap();
2968
2969 let bricked = healthy_dir.join("events-bricked-deadbeef.parquet");
2971 std::fs::write(&bricked, b"").unwrap();
2972 assert_eq!(std::fs::metadata(&bricked).unwrap().len(), 0);
2973
2974 let acted = storage.cleanup_partial_writes().unwrap();
2975 assert_eq!(acted, 1, "only the 0-byte file should have been acted on");
2976
2977 assert!(!bricked.exists(), "0-byte file should have been renamed");
2980 let quarantined: Vec<_> = std::fs::read_dir(healthy_dir)
2981 .unwrap()
2982 .flatten()
2983 .map(|e| e.path())
2984 .filter(|p| {
2985 p.file_name()
2986 .and_then(|n| n.to_str())
2987 .is_some_and(|n| n.starts_with("events-bricked-deadbeef.parquet.corrupt-"))
2988 })
2989 .collect();
2990 assert_eq!(
2991 quarantined.len(),
2992 1,
2993 "expected one .parquet.corrupt-<ts> sibling"
2994 );
2995
2996 assert!(
2998 healthy_file.exists(),
2999 "healthy parquet must not be molested"
3000 );
3001 }
3002
3003 #[test]
3004 fn test_load_all_events_skips_zero_byte_parquet() {
3005 let temp_dir = TempDir::new().unwrap();
3009 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3010
3011 for i in 0..2 {
3013 storage
3014 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3015 .unwrap();
3016 }
3017 storage.flush().unwrap();
3018
3019 let healthy_files = find_parquet_files_recursive(temp_dir.path()).unwrap();
3023 let bricked = healthy_files[0]
3024 .parent()
3025 .unwrap()
3026 .join("events-bricked-cafef00d.parquet");
3027 std::fs::write(&bricked, b"").unwrap();
3028
3029 let loaded = storage.load_all_events().unwrap();
3030 assert_eq!(
3031 loaded.len(),
3032 2,
3033 "all healthy events should still load despite the 0-byte file"
3034 );
3035 }
3036
3037 #[test]
3038 fn test_load_events_for_tenant_skips_zero_byte_parquet() {
3039 let temp_dir = TempDir::new().unwrap();
3042 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3043
3044 for i in 0..3 {
3045 storage
3046 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3047 .unwrap();
3048 }
3049 storage.flush().unwrap();
3050
3051 let healthy = find_parquet_files_recursive(temp_dir.path()).unwrap();
3052 let bricked = healthy[0]
3053 .parent()
3054 .unwrap()
3055 .join("events-bricked-feedface.parquet");
3056 std::fs::write(&bricked, b"").unwrap();
3057
3058 let events = storage.load_events_for_tenant("alice").unwrap();
3059 assert_eq!(events.len(), 3, "lazy load must skip the 0-byte file");
3060 }
3061
3062 #[test]
3063 fn test_flush_tenant_leaves_no_zero_byte_parquet_after_normal_flush() {
3064 let temp_dir = TempDir::new().unwrap();
3068 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3069
3070 for i in 0..5 {
3071 storage
3072 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3073 .unwrap();
3074 }
3075 storage.flush().unwrap();
3076
3077 let mut tmp_count = 0;
3078 let mut zero_byte_count = 0;
3079 let mut healthy_count = 0;
3080 let mut stack = vec![temp_dir.path().to_path_buf()];
3081 while let Some(d) = stack.pop() {
3082 for entry in std::fs::read_dir(&d).unwrap().flatten() {
3083 let p = entry.path();
3084 if p.is_dir() {
3085 stack.push(p);
3086 continue;
3087 }
3088 let name = p.file_name().unwrap().to_string_lossy().into_owned();
3089 if name.ends_with(".parquet.tmp") {
3090 tmp_count += 1;
3091 } else if name.ends_with(".parquet") {
3092 if std::fs::metadata(&p).unwrap().len() == 0 {
3093 zero_byte_count += 1;
3094 } else {
3095 healthy_count += 1;
3096 }
3097 }
3098 }
3099 }
3100 assert_eq!(tmp_count, 0, ".parquet.tmp survivors after flush");
3101 assert_eq!(zero_byte_count, 0, "0-byte .parquet survivors after flush");
3102 assert_eq!(healthy_count, 1, "expected exactly one healthy parquet");
3103 }
3104
3105 #[test]
3106 fn test_new_calls_cleanup_partial_writes_on_boot() {
3107 let temp_dir = TempDir::new().unwrap();
3111 let stale = temp_dir.path().join("orphan.parquet.tmp");
3112 std::fs::write(&stale, b"crash detritus").unwrap();
3113 assert!(stale.is_file());
3114
3115 let _storage = ParquetStorage::new(temp_dir.path()).unwrap();
3116 assert!(
3117 !stale.exists(),
3118 "stale tmp should have been cleaned by ParquetStorage::new"
3119 );
3120 }
3121
3122 fn seed_flat_layout_file(storage: &ParquetStorage, count: usize) -> PathBuf {
3132 for i in 0..count {
3133 storage
3134 .append_event(create_test_event(&format!("entity-{i}")))
3135 .unwrap();
3136 }
3137 storage.flush().unwrap();
3138
3139 let default_subtree = storage.storage_dir().join("default");
3144 let candidates = find_parquet_files_recursive(&default_subtree).unwrap();
3145 assert!(
3146 !candidates.is_empty(),
3147 "seed expected at least one file under default/"
3148 );
3149 let src = candidates.into_iter().max().unwrap();
3150
3151 let dst = storage.storage_dir().join(src.file_name().unwrap());
3152 std::fs::rename(&src, &dst).unwrap();
3153 if let Some(month_dir) = src.parent() {
3157 let _ = std::fs::remove_dir(month_dir);
3158 if let Some(tenant_dir) = month_dir.parent() {
3159 let _ = std::fs::remove_dir(tenant_dir);
3160 }
3161 }
3162 dst
3163 }
3164
3165 #[test]
3166 fn test_migrate_flat_layout_dry_run_touches_nothing() {
3167 let temp_dir = TempDir::new().unwrap();
3168 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3169 let flat = seed_flat_layout_file(&storage, 7);
3170 assert!(flat.is_file(), "test setup: flat file should exist");
3171
3172 let report = storage.migrate_flat_layout(true).unwrap();
3173 assert!(report.dry_run);
3174 assert_eq!(report.flat_files_seen, 1);
3175 assert_eq!(report.events_migrated, 7);
3176 assert_eq!(report.flat_files_removed, 0);
3177 assert_eq!(report.partitions_written, 0);
3178 assert!(
3179 flat.is_file(),
3180 "flat file must still be present after dry run"
3181 );
3182 }
3183
3184 #[test]
3185 fn test_migrate_flat_layout_moves_events_into_default_tree_and_removes_flat() {
3186 let temp_dir = TempDir::new().unwrap();
3187 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3188 let flat = seed_flat_layout_file(&storage, 5);
3189
3190 let report = storage.migrate_flat_layout(false).unwrap();
3191 assert!(!report.dry_run);
3192 assert_eq!(report.flat_files_seen, 1);
3193 assert_eq!(report.flat_files_removed, 1);
3194 assert_eq!(report.events_migrated, 5);
3195 assert!(report.partitions_written >= 1);
3196 assert!(
3197 !flat.exists(),
3198 "flat file should be deleted after migration"
3199 );
3200
3201 let post = find_parquet_files_recursive(temp_dir.path()).unwrap();
3202 assert!(
3203 post.iter().all(|p| {
3204 let rel = p
3205 .strip_prefix(temp_dir.path())
3206 .unwrap()
3207 .to_string_lossy()
3208 .into_owned();
3209 rel.starts_with(&format!("default{}", std::path::MAIN_SEPARATOR))
3210 }),
3211 "all migrated files should be under default/"
3212 );
3213
3214 let loaded = storage.load_all_events().unwrap();
3215 assert_eq!(loaded.len(), 5);
3216 }
3217
3218 #[test]
3219 fn test_migrate_flat_layout_is_idempotent_when_re_run_after_completion() {
3220 let temp_dir = TempDir::new().unwrap();
3221 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3222 let _flat = seed_flat_layout_file(&storage, 4);
3223
3224 let first = storage.migrate_flat_layout(false).unwrap();
3225 assert_eq!(first.events_migrated, 4);
3226
3227 let second = storage.migrate_flat_layout(false).unwrap();
3230 assert_eq!(second.flat_files_seen, 0);
3231 assert_eq!(second.events_migrated, 0);
3232 assert_eq!(second.flat_files_removed, 0);
3233
3234 let loaded = storage.load_all_events().unwrap();
3235 assert_eq!(loaded.len(), 4, "rerun must not duplicate or lose events");
3236 }
3237
3238 #[test]
3239 fn test_migrate_flat_layout_ignores_already_partitioned_data() {
3240 let temp_dir = TempDir::new().unwrap();
3243 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3244
3245 for i in 0..3 {
3246 storage
3247 .append_event(event_with_tenant("alice", &format!("a-{i}")))
3248 .unwrap();
3249 }
3250 storage.flush().unwrap();
3251
3252 let _flat = seed_flat_layout_file(&storage, 2);
3253
3254 let report = storage.migrate_flat_layout(false).unwrap();
3255 assert_eq!(report.flat_files_seen, 1, "only the flat file is in scope");
3256 assert_eq!(report.events_migrated, 2);
3257
3258 let alice_files = find_parquet_files_recursive(&temp_dir.path().join("alice")).unwrap();
3259 assert_eq!(alice_files.len(), 1, "alice's tree must be untouched");
3260
3261 let loaded = storage.load_all_events().unwrap();
3262 assert_eq!(loaded.len(), 5);
3263 let alice_count = loaded
3264 .iter()
3265 .filter(|e| e.tenant_id_str() == "alice")
3266 .count();
3267 let default_count = loaded
3268 .iter()
3269 .filter(|e| e.tenant_id_str() == "default")
3270 .count();
3271 assert_eq!(alice_count, 3);
3272 assert_eq!(default_count, 2);
3273 }
3274
3275 #[test]
3276 fn test_migrate_flat_layout_with_no_flat_files_is_a_clean_noop() {
3277 let temp_dir = TempDir::new().unwrap();
3278 let storage = ParquetStorage::new(temp_dir.path()).unwrap();
3279 let report = storage.migrate_flat_layout(false).unwrap();
3280 assert_eq!(report.flat_files_seen, 0);
3281 assert_eq!(report.events_migrated, 0);
3282 }
3283}