Skip to main content

allsource_core/
store.rs

1#[cfg(feature = "server")]
2use crate::application::services::webhook::WebhookRegistry;
3#[cfg(feature = "server")]
4use crate::infrastructure::memory::ledger::Lease;
5#[cfg(feature = "server")]
6use crate::infrastructure::observability::metrics::MetricsRegistry;
7#[cfg(feature = "server")]
8use crate::infrastructure::web::websocket::WebSocketManager;
9use crate::{
10    application::{
11        dto::QueryEventsRequest,
12        services::{
13            consumer::ConsumerRegistry,
14            exactly_once::{ExactlyOnceConfig, ExactlyOnceRegistry},
15            pipeline::PipelineManager,
16            projection::{EntitySnapshotProjection, EventCounterProjection, ProjectionManager},
17            replay::ReplayManager,
18            schema::{SchemaRegistry, SchemaRegistryConfig},
19            schema_evolution::SchemaEvolutionManager,
20        },
21    },
22    domain::entities::{Event, event::value_heap_bytes},
23    error::{AllSourceError, Result},
24    infrastructure::{
25        hash_state::{FastDashMap, FastSet, fast_dashmap},
26        memory::ledger::{BroadcastRing, MapCharge, Owner, Tally, string_heap},
27        persistence::{
28            archive_budget::{ArchiveReadBudget, ArchiveReadLimits, check_cancelled},
29            compaction::{CompactionConfig, CompactionManager},
30            index::{EventIndex, IndexEntry, ValidWindow},
31            storage::{FileNamer, ParquetStorage, ParquetStorageConfig},
32            tenant_loader::TenantLoader,
33            version_manifest::ResolvedVersion,
34            wal::{WALConfig, WriteAheadLog},
35        },
36        query::geospatial::GeoIndex,
37    },
38};
39use chrono::{DateTime, Utc};
40use parking_lot::RwLock;
41use std::{mem::size_of, path::PathBuf, sync::Arc};
42
43/// Slots the in-process event ring keeps for its receivers.
44const STORE_RING_CAPACITY: usize = 1024;
45
46/// Heap a fresh store allocates outside every owner, measured with a counting
47/// allocator at 16, 32 and 64 shards: a fixed part plus the shard arrays of its
48/// `DashMap::new` and `fast_dashmap` maps. `ledger_owns_heap` checks it within
49/// 10% on an empty store. `server` adds the webhook and websocket registries.
50#[cfg(feature = "server")]
51const STORE_FIXED_BYTES: u64 = 80_600;
52#[cfg(not(feature = "server"))]
53const STORE_FIXED_BYTES: u64 = 47_750;
54#[cfg(feature = "server")]
55const STORE_DEFAULT_DASHMAPS: u64 = 15;
56#[cfg(not(feature = "server"))]
57const STORE_DEFAULT_DASHMAPS: u64 = 11;
58const STORE_FAST_DASHMAPS: u64 = 16;
59
60fn store_structure_bytes() -> u64 {
61    let default_map = dashmap::DashMap::<(), ()>::new();
62    let fast_map = fast_dashmap::<(), ()>();
63    let shard_bytes = std::mem::size_of_val(&default_map.shards()[0]) as u64;
64    STORE_FIXED_BYTES
65        + (STORE_DEFAULT_DASHMAPS * default_map.shards().len() as u64
66            + STORE_FAST_DASHMAPS * fast_map.shards().len() as u64)
67            * shard_bytes
68}
69#[path = "store_feed.rs"]
70pub mod feed;
71#[path = "store_read_model.rs"]
72pub mod read_model;
73#[path = "store_view.rs"]
74pub mod view;
75#[cfg(feature = "server")]
76use tokio::sync::mpsc;
77
78/// High-performance event store with columnar storage
79/// What a read credential is allowed to see, enforced inside the store.
80///
81/// A read key is otherwise all-or-nothing: "let this tool read the store" and
82/// "let this tool read every credential ever issued" are the same grant. That is
83/// not theoretical — auth events carry session tokens whose value IS the
84/// `entity_id`, so a routine query rendered live bearer tokens into an agent's
85/// context (#265). Redacting on write cannot fix it: the token is the lookup
86/// key.
87///
88/// Deliberately **not** `Deserialize`. This must never be settable from a
89/// request body, or a caller widens its own scope by omitting the field.
90///
91/// Allow-list, not deny-list, on purpose: a stream family added later is
92/// excluded until someone names it, so the failure mode of forgetting is a
93/// missing read rather than a leak.
94#[derive(Debug, Clone, Default)]
95pub struct ReadScope {
96    allow_entity_prefixes: Option<Vec<String>>,
97}
98
99impl ReadScope {
100    /// Everything in the tenant — the behaviour of every read before scopes.
101    pub fn unrestricted() -> Self {
102        Self {
103            allow_entity_prefixes: None,
104        }
105    }
106
107    /// Only entities whose id starts with one of `prefixes`.
108    ///
109    /// An empty list denies everything, which is the safe reading of "scoped to
110    /// nothing" and stops an accidentally-empty config granting full access.
111    pub fn allow_entity_prefixes<I, S>(prefixes: I) -> Self
112    where
113        I: IntoIterator<Item = S>,
114        S: Into<String>,
115    {
116        Self {
117            allow_entity_prefixes: Some(prefixes.into_iter().map(Into::into).collect()),
118        }
119    }
120
121    /// Whether this scope can see `entity_id`.
122    pub fn permits(&self, entity_id: &str) -> bool {
123        match &self.allow_entity_prefixes {
124            None => true,
125            Some(allowed) => allowed.iter().any(|p| entity_id.starts_with(p.as_str())),
126        }
127    }
128
129    /// True when this scope restricts nothing.
130    pub fn is_unrestricted(&self) -> bool {
131        self.allow_entity_prefixes.is_none()
132    }
133}
134
135pub struct EventStore {
136    /// In-memory event storage
137    events: Arc<RwLock<Vec<Event>>>,
138
139    /// High-performance concurrent index
140    index: Arc<EventIndex>,
141
142    /// Projection manager for real-time aggregations
143    pub(crate) projections: Arc<RwLock<ProjectionManager>>,
144
145    /// Optional persistent storage (v0.2 feature)
146    storage: Option<Arc<RwLock<ParquetStorage>>>,
147
148    /// WebSocket manager for real-time event streaming (v0.2 feature)
149    #[cfg(feature = "server")]
150    websocket_manager: Arc<WebSocketManager>,
151
152    /// Write-Ahead Log for durability (v0.2 feature)
153    wal: Option<Arc<WriteAheadLog>>,
154
155    /// Compaction manager for Parquet optimization (v0.2 feature)
156    compaction_manager: Option<Arc<CompactionManager>>,
157
158    /// Schema registry for event validation (v0.5 feature)
159    schema_registry: Arc<SchemaRegistry>,
160
161    /// Replay manager for event replay and projection rebuilding (v0.5 feature)
162    replay_manager: Arc<ReplayManager>,
163
164    /// Pipeline manager for stream processing (v0.5 feature)
165    pipeline_manager: Arc<PipelineManager>,
166
167    /// Prometheus metrics registry (v0.6 feature)
168    #[cfg(feature = "server")]
169    metrics: Arc<MetricsRegistry>,
170
171    /// Total events ingested (for metrics)
172    total_ingested: Arc<RwLock<u64>>,
173
174    feed_indexes: FastDashMap<String, feed::FeedIndex>,
175    feed_indexes_charge: MapCharge,
176    /// `ALLSOURCE_FEED_DURABLE_LOG`; `None` when off.
177    feed_log: Option<Arc<crate::infrastructure::persistence::feed_log::FeedLog>>,
178    read_models: parking_lot::Mutex<std::collections::HashMap<String, read_model::ReadModel>>,
179    read_models_charge: Tally,
180
181    /// Projection status overrides (v0.13 feature)
182    /// Tracks pause/start state per projection name: "running" or "paused"
183    projection_status: Arc<FastDashMap<String, String>>,
184    projection_status_charge: MapCharge,
185
186    /// Webhook registry for outbound event delivery (v0.11 feature)
187    #[cfg(feature = "server")]
188    webhook_registry: Arc<WebhookRegistry>,
189
190    /// Channel sender for async webhook delivery tasks
191    #[cfg(feature = "server")]
192    webhook_tx: Arc<RwLock<Option<mpsc::UnboundedSender<WebhookDeliveryTask>>>>,
193
194    /// Geospatial index for coordinate-based queries (v2.0 feature)
195    geo_index: Arc<GeoIndex>,
196
197    /// Exactly-once processing registry (v2.0 feature)
198    exactly_once: Arc<ExactlyOnceRegistry>,
199
200    /// Autonomous schema evolution manager (v2.0 feature)
201    schema_evolution: Arc<SchemaEvolutionManager>,
202
203    /// Per-entity version marks for optimistic concurrency control (v0.14 feature)
204    /// Key: entity_id string, Value: highest version persisted for that entity.
205    /// Monotonic, and never lowered by a cache eviction.
206    entity_versions: Arc<FastDashMap<String, u64>>,
207    entity_versions_charge: MapCharge,
208
209    /// Tenants whose archived versions have been folded into `entity_versions`.
210    /// A conditional write needs the archive's high-water marks exactly once;
211    /// in-memory appends keep them current from then on.
212    ///
213    /// Tenants are certified only by a complete strict hydration. A
214    /// conditional write certifies the one entity it targets, so a tenant too
215    /// large to hydrate strictly can still take conditional writes.
216    version_index_tenants: Arc<FastDashMap<String, ()>>,
217    version_tenants_charge: MapCharge,
218
219    /// Entities whose archived version has been resolved. See
220    /// [`version_index_tenants`](Self::version_index_tenants).
221    version_index_entities: Arc<FastDashMap<String, ()>>,
222    version_entities_charge: MapCharge,
223
224    /// Durable consumer registry for subscription cursor tracking (v0.14 feature)
225    consumer_registry: Arc<ConsumerRegistry>,
226
227    /// In-process broadcast of every successfully-ingested event. Always enabled
228    /// so embedded consumers (TUI, web) can tail changes without the `server`
229    /// feature / HTTP stack. Lagging receivers see `RecvError::Lagged`.
230    event_broadcast_tx: tokio::sync::broadcast::Sender<Arc<Event>>,
231    event_ring: BroadcastRing,
232
233    /// Heap of the resident events (`events.resident`).
234    events_resident: Tally,
235    structure: Tally,
236
237    /// Per-tenant lazy-load bookkeeping. Tracks which tenants have
238    /// been hydrated from Parquet into the in-memory pile and
239    /// serializes concurrent first-loads of the same tenant. See
240    /// `ensure_tenant_loaded` and Step 2 of the sustainable data
241    /// strategy.
242    tenant_loader: Arc<TenantLoader>,
243    strict_archive_limits: ArchiveReadLimits,
244    /// Eviction must not reset indexes/versions underneath a writer or a
245    /// certified cache load. Acquire before durability, events and storage locks.
246    cache_residency_gate: RwLock<()>,
247    cache_generations: FastDashMap<String, u64>,
248    cache_generations_charge: MapCharge,
249    /// Bumped under the events write lock whenever events leave the Vec.
250    events_removed: std::sync::atomic::AtomicU64,
251
252    /// Cadence of the runtime checkpoint loop (Step 6). `None` means
253    /// the loop is disabled — WAL grows until boot. Production reads
254    /// this from `ALLSOURCE_CHECKPOINT_INTERVAL_SECONDS`. Stored on
255    /// the store so background tasks can read it without re-parsing
256    /// the env.
257    checkpoint_interval_secs: Option<u64>,
258
259    /// Read-only (replica) mode. Set when a second process attaches to a
260    /// data-dir already owned by a live writer (see Prime's data-dir lock).
261    /// A read-only store replays the WAL + Parquet into memory at boot so it
262    /// can serve reads, but it MUST NOT truncate the WAL (that would unlink
263    /// the inode the owner is still appending to — issue #201) and rejects
264    /// all writes with `AllSourceError::ReadOnly`.
265    read_only: bool,
266
267    /// Held shared from an event's WAL append until it is in the Parquet
268    /// batch, and exclusively while `checkpoint` seals the WAL. Without it an
269    /// event can sit in a sealed segment yet miss the flush that retires it.
270    durability_gate: RwLock<()>,
271
272    refresh_state: parking_lot::Mutex<refresh::RefreshState>,
273}
274
275/// A task queued for async webhook delivery
276#[cfg(feature = "server")]
277#[derive(Debug)]
278pub struct WebhookDeliveryTask {
279    pub webhook: crate::application::services::webhook::WebhookSubscription,
280    pub event: Event,
281    /// Released when the task is dropped, which is when its delivery ends.
282    _queued: Lease,
283}
284
285/// Time axis a query window is ordered by.
286#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
287pub enum WindowOrder {
288    /// `(timestamp, version)`: the order every existing caller gets.
289    #[default]
290    RecordTime,
291    /// `(valid_from, timestamp, version)`.
292    ValidTime,
293}
294
295/// Window ordering shared by the resident and archive paths.
296fn compare_query_order(a: &Event, b: &Event, order: WindowOrder) -> std::cmp::Ordering {
297    let valid = match order {
298        WindowOrder::RecordTime => std::cmp::Ordering::Equal,
299        WindowOrder::ValidTime => a.effective_valid_from().cmp(&b.effective_valid_from()),
300    };
301    valid
302        .then_with(|| a.timestamp.cmp(&b.timestamp))
303        .then_with(|| a.version.cmp(&b.version))
304}
305
306/// Reduce `items` to the `offset .. offset + limit` window under `order`,
307/// leaving that window sorted and everything past it dropped.
308///
309/// `limit == None` means "no window": the whole slice is sorted. Otherwise the
310/// window is partitioned off with `select_nth_unstable_by` — O(N) — and only
311/// the `offset + limit` retained items are sorted, O(k log k), instead of
312/// sorting all N (issue #251). `order` MUST be a total order (no two distinct
313/// items compare `Equal`); with one, this is observationally identical to
314/// sorting everything and then windowing, ties included.
315///
316/// The first `offset` items are kept, not skipped — the caller drops them,
317/// which is what makes `has_more`/`total` independent of the window.
318fn select_window<T>(
319    items: &mut Vec<T>,
320    offset: usize,
321    limit: Option<usize>,
322    order: impl Fn(&T, &T) -> std::cmp::Ordering + Copy,
323) {
324    match limit.map(|limit| offset.saturating_add(limit)) {
325        Some(0) => {
326            items.clear();
327            return;
328        }
329        Some(window_end) if window_end < items.len() => {
330            items.select_nth_unstable_by(window_end - 1, order);
331            items.truncate(window_end);
332        }
333        // No limit, or a window that already covers everything: nothing to
334        // partition off, the sort below orders the whole set.
335        _ => {}
336    }
337    items.sort_unstable_by(order);
338}
339
340impl EventStore {
341    /// Create a new in-memory event store
342    pub fn new() -> Self {
343        Self::with_config(EventStoreConfig::default())
344    }
345
346    /// Create event store with custom configuration
347    pub fn with_config(config: EventStoreConfig) -> Self {
348        Self::try_with_config(config)
349            .expect("Core cannot open while erasure maintenance is unfinished")
350    }
351
352    pub fn try_with_config(config: EventStoreConfig) -> Result<Self> {
353        crate::infrastructure::persistence::erasure_maintenance::require_no_pending(
354            config.storage_dir.as_deref(),
355            config.wal_dir.as_deref(),
356        )?;
357        let read_only_wal = if config.read_only {
358            config
359                .wal_dir
360                .as_ref()
361                .map(|dir| WriteAheadLog::open_read_only(dir, config.wal_config.clone()))
362                .transpose()?
363        } else {
364            None
365        };
366        let read_only_storage = if config.read_only {
367            if let Some(dir) = &config.storage_dir {
368                match std::fs::symlink_metadata(dir) {
369                    Ok(_) => Some(ParquetStorage::open_existing(dir)?),
370                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
371                    Err(error) => {
372                        return Err(AllSourceError::StorageError(format!(
373                            "Failed to inspect storage directory: {error}"
374                        )));
375                    }
376                }
377            } else {
378                None
379            }
380        } else {
381            None
382        };
383        Self::open_config(config, read_only_wal, read_only_storage)
384    }
385
386    fn open_config(
387        config: EventStoreConfig,
388        read_only_wal: Option<WriteAheadLog>,
389        read_only_storage: Option<ParquetStorage>,
390    ) -> Result<Self> {
391        let mut projections = ProjectionManager::new();
392
393        // Register built-in projections
394        if config.register_entity_snapshots {
395            projections.register(Arc::new(EntitySnapshotProjection::new("entity_snapshots")));
396        }
397        projections.register(Arc::new(EventCounterProjection::new("event_counters")));
398
399        // Initialize persistent storage if configured
400        let storage = if config.read_only {
401            read_only_storage.map(|storage| Arc::new(RwLock::new(storage)))
402        } else {
403            config.storage_dir.as_ref().and_then(|dir| {
404                match if let Some(namer) = &config.parquet_file_namer {
405                    ParquetStorage::with_config(
406                        dir,
407                        ParquetStorageConfig {
408                            file_namer: Some(namer.clone()),
409                            ..ParquetStorageConfig::default()
410                        },
411                    )
412                } else {
413                    ParquetStorage::new(dir)
414                } {
415                    Ok(storage) => {
416                        tracing::info!("✅ Parquet persistence enabled at: {}", dir.display());
417                        Some(Arc::new(RwLock::new(storage)))
418                    }
419                    Err(e) => {
420                        tracing::error!("❌ Failed to initialize Parquet storage: {}", e);
421                        None
422                    }
423                }
424            })
425        };
426
427        // Initialize WAL if configured (v0.2 feature)
428        let wal = if config.read_only {
429            read_only_wal.map(Arc::new)
430        } else {
431            config.wal_dir.as_ref().and_then(|dir| {
432                match WriteAheadLog::new(dir, config.wal_config.clone()) {
433                    Ok(wal) => {
434                        tracing::info!("✅ WAL enabled at: {}", dir.display());
435                        Some(Arc::new(wal))
436                    }
437                    Err(e) => {
438                        tracing::error!("❌ Failed to initialize WAL: {}", e);
439                        None
440                    }
441                }
442            })
443        };
444
445        // Initialize compaction manager if Parquet storage is enabled (v0.2 feature)
446        let compaction_manager = config.storage_dir.as_ref().map(|dir| {
447            let manager = CompactionManager::new(dir, config.compaction_config.clone());
448            Arc::new(manager)
449        });
450
451        // Initialize schema registry (v0.5 feature)
452        let schema_registry = Arc::new(SchemaRegistry::new(config.schema_registry_config.clone()));
453        tracing::info!("✅ Schema registry enabled");
454
455        // Initialize replay manager (v0.5 feature)
456        let replay_manager = Arc::new(ReplayManager::new());
457        tracing::info!("✅ Replay manager enabled");
458
459        // Initialize pipeline manager (v0.5 feature)
460        let pipeline_manager = Arc::new(PipelineManager::new());
461        tracing::info!("✅ Pipeline manager enabled");
462
463        // Initialize metrics registry (v0.6 feature)
464        #[cfg(feature = "server")]
465        let metrics = {
466            let m = MetricsRegistry::new();
467            tracing::info!("✅ Prometheus metrics registry initialized");
468            m
469        };
470
471        // Initialize webhook registry (v0.11 feature)
472        #[cfg(feature = "server")]
473        let webhook_registry = {
474            let w = Arc::new(WebhookRegistry::new());
475            tracing::info!("✅ Webhook registry initialized");
476            w
477        };
478
479        // Unconditional in-process event broadcaster so embedded consumers
480        // (TUI, web) can live-reload without the `server` feature.
481        let (event_broadcast_tx, _) = tokio::sync::broadcast::channel(STORE_RING_CAPACITY);
482
483        let store = Self {
484            strict_archive_limits: config.strict_archive_limits,
485            cache_residency_gate: RwLock::new(()),
486            cache_generations: fast_dashmap(),
487            events_removed: std::sync::atomic::AtomicU64::new(0),
488            cache_generations_charge: MapCharge::new(
489                Owner::CacheGenerations,
490                size_of::<(String, u64)>(),
491            ),
492            events_resident: Tally::new(Owner::EventsResident),
493            structure: {
494                let structure = Tally::new(Owner::Misc);
495                structure.add(store_structure_bytes());
496                structure
497            },
498            event_ring: BroadcastRing::new(STORE_RING_CAPACITY),
499            events: Arc::new(RwLock::new(Vec::new())),
500            index: Arc::new(EventIndex::new()),
501            projections: Arc::new(RwLock::new(projections)),
502            storage,
503            #[cfg(feature = "server")]
504            websocket_manager: Arc::new(WebSocketManager::new()),
505            wal,
506            compaction_manager,
507            schema_registry,
508            replay_manager,
509            pipeline_manager,
510            #[cfg(feature = "server")]
511            metrics,
512            total_ingested: Arc::new(RwLock::new(0)),
513            feed_indexes: fast_dashmap(),
514            feed_indexes_charge: MapCharge::new(
515                Owner::FeedIndex,
516                size_of::<(String, feed::FeedIndex)>(),
517            ),
518            feed_log: feed::open_feed_log(config.wal_dir.as_deref(), config.read_only),
519            read_models: parking_lot::Mutex::new(std::collections::HashMap::new()),
520            read_models_charge: Tally::new(Owner::ReadModels),
521            projection_status: Arc::new(fast_dashmap()),
522            projection_status_charge: MapCharge::new(Owner::Misc, size_of::<(String, String)>()),
523            #[cfg(feature = "server")]
524            webhook_registry,
525            #[cfg(feature = "server")]
526            webhook_tx: Arc::new(RwLock::new(None)),
527            geo_index: Arc::new(GeoIndex::new()),
528            exactly_once: Arc::new(ExactlyOnceRegistry::new(ExactlyOnceConfig::default())),
529            schema_evolution: Arc::new(SchemaEvolutionManager::new()),
530            entity_versions: Arc::new(fast_dashmap()),
531            entity_versions_charge: MapCharge::new(
532                Owner::EntityVersions,
533                size_of::<(String, u64)>(),
534            ),
535            version_index_tenants: Arc::new(fast_dashmap()),
536            version_tenants_charge: MapCharge::new(
537                Owner::VersionIndexTenants,
538                size_of::<(String, ())>(),
539            ),
540            version_index_entities: Arc::new(fast_dashmap()),
541            version_entities_charge: MapCharge::new(
542                Owner::VersionIndexEntities,
543                size_of::<(String, ())>(),
544            ),
545            consumer_registry: Arc::new(ConsumerRegistry::new()),
546            event_broadcast_tx,
547            tenant_loader: {
548                let loader = TenantLoader::new();
549                if let Some(budget) = config.cache_byte_budget {
550                    loader.set_byte_budget(budget);
551                    tracing::info!(
552                        "✅ Cache byte budget set to {} bytes ({:.2} GiB) — LRU eviction enabled",
553                        budget,
554                        budget as f64 / (1024.0 * 1024.0 * 1024.0)
555                    );
556                } else {
557                    tracing::info!(
558                        "✅ Cache budget unset — every loaded tenant stays resident \
559                         (set ALLSOURCE_CACHE_BYTES to enable eviction)"
560                    );
561                }
562                Arc::new(loader)
563            },
564            checkpoint_interval_secs: config.checkpoint_interval_secs,
565            read_only: config.read_only,
566            durability_gate: RwLock::new(()),
567            refresh_state: parking_lot::Mutex::new(refresh::RefreshState::default()),
568        };
569
570        if config.read_only {
571            tracing::info!(
572                "📖 EventStore opened READ-ONLY (replica): WAL will be replayed for reads but \
573                 not truncated; writes are rejected"
574            );
575        }
576
577        // Boot is now O(1) regardless of dataset size (Step 2 of the
578        // sustainable data strategy). Pre-Step-2 we scanned every
579        // Parquet file at startup; on the production volume that
580        // grew past available memory and Core OOM'd during recovery
581        // (issue #160). Now:
582        //
583        //   - Parquet data stays on disk. Tenants are hydrated on
584        //     demand by `ensure_tenant_loaded`, called from the
585        //     query path on first access.
586        //   - WAL is still recovered eagerly. WAL is bounded
587        //     (rotates / truncates after each Parquet flush), so
588        //     replaying it is O(recent un-flushed writes) — small
589        //     by construction and required for correctness, since
590        //     those events aren't durably in Parquet yet.
591        //
592        // After WAL recovery we still checkpoint recovered events
593        // to Parquet and truncate the WAL. The lazy-load path's
594        // dedupe in `append_loaded_event` (index.get_by_id check)
595        // makes it safe for the same event to be reachable through
596        // both WAL recovery and a subsequent ensure_tenant_loaded
597        // pass on the same tenant.
598        if let Some(ref wal) = store.wal {
599            if config.read_only
600                && let Ok(stamps) = wal.segment_stamps()
601            {
602                store.refresh_state.lock().set_wal_stamps(stamps);
603            }
604            match wal.recover() {
605                Ok(recovered_events) if !recovered_events.is_empty() => {
606                    let mut wal_new = 0usize;
607                    for event in recovered_events {
608                        let offset = store.events.read().len();
609                        if let Err(e) = store.index.index_event(
610                            event.id,
611                            event.entity_id_str(),
612                            event.event_type_str(),
613                            event.timestamp,
614                            ValidWindow::of(&event),
615                            offset,
616                        ) {
617                            tracing::error!("Failed to re-index WAL event {}: {}", event.id, e);
618                        }
619
620                        if let Err(e) = store.projections.read().process_event(&event) {
621                            tracing::error!("Failed to re-process WAL event {}: {}", event.id, e);
622                        }
623
624                        store.charge_entity_version(event.entity_id_str());
625                        *store
626                            .entity_versions
627                            .entry(event.entity_id_str().to_string())
628                            .or_insert(0) += 1;
629
630                        let mut events = store.events.write();
631                        store.observe_feed_head(&event, events.len() + 1);
632                        store.events_resident.add(event.resident_bytes());
633                        events.push(event);
634                        wal_new += 1;
635                    }
636
637                    // Step 6: expose replay size as a gauge so ops
638                    // can graph "how big was the last replay?" and
639                    // catch regressions where the checkpoint loop
640                    // stops draining the WAL.
641                    #[cfg(feature = "server")]
642                    store.metrics.wal_replay_events_total.set(wal_new as i64);
643
644                    if wal_new > 0 {
645                        let total = store.events.read().len();
646                        // total_ingested now reflects "events the
647                        // process knows about" rather than "events
648                        // ever written" — Parquet data isn't loaded
649                        // on boot, so the count grows as tenants
650                        // get hydrated. Consumers that need the
651                        // historical total should look at Parquet
652                        // file stats, not this counter.
653                        *store.total_ingested.write() = total as u64;
654                        tracing::info!(
655                            "✅ Recovered {} events from WAL (Parquet data stays cold until \
656                             first per-tenant query)",
657                            wal_new
658                        );
659
660                        // Checkpoint WAL events to Parquet — buffer
661                        // them into the per-tenant Parquet batches
662                        // first, then flush. Without this,
663                        // flush_storage() finds an empty current
664                        // batch and silently no-ops, the WAL gets
665                        // truncated, and the events exist only in
666                        // memory (lost on next restart).
667                        //
668                        // Skip entirely in read-only (replica) mode: a replica
669                        // does not own the WAL. `wal.truncate()` unlinks the WAL
670                        // file, which would delete the inode the owning writer is
671                        // still appending to and silently lose its in-flight
672                        // writes (issue #201). The replica keeps the recovered
673                        // events in memory for reads and leaves the file alone.
674                        if let Some(ref storage) = store.storage
675                            && !config.read_only
676                        {
677                            tracing::info!(
678                                "📸 Checkpointing {} WAL events to Parquet storage...",
679                                wal_new
680                            );
681                            let parquet = storage.read();
682                            let events = store.events.read();
683                            let mut buffered = 0usize;
684                            for event in events.iter().skip(events.len() - wal_new) {
685                                if let Err(e) = parquet.append_event(event.clone()) {
686                                    tracing::error!(
687                                        "Failed to buffer WAL event for Parquet: {}",
688                                        e
689                                    );
690                                } else {
691                                    buffered += 1;
692                                }
693                            }
694                            drop(events);
695                            drop(parquet);
696
697                            if buffered < wal_new {
698                                tracing::error!(
699                                    "Buffered {} of {} recovered WAL events; leaving the WAL \
700                                     in place so none are lost",
701                                    buffered,
702                                    wal_new
703                                );
704                            } else if buffered > 0 {
705                                if let Err(e) = store.flush_storage() {
706                                    tracing::error!("Failed to checkpoint to Parquet: {}", e);
707                                } else if let Err(e) = store.sync_feed_log() {
708                                    tracing::error!(
709                                        "Failed to sync the feed log; leaving the WAL in place: {}",
710                                        e
711                                    );
712                                } else if let Err(e) = wal.truncate() {
713                                    tracing::error!(
714                                        "Failed to truncate WAL after checkpoint: {}",
715                                        e
716                                    );
717                                } else {
718                                    tracing::info!(
719                                        "✅ WAL checkpointed and truncated ({} events)",
720                                        buffered
721                                    );
722                                }
723                            }
724                        }
725                    }
726                }
727                Ok(_) => {
728                    tracing::debug!("No events to recover from WAL");
729                    #[cfg(feature = "server")]
730                    store.metrics.wal_replay_events_total.set(0);
731                }
732                Err(e) => {
733                    if config.read_only {
734                        return Err(e);
735                    }
736                    tracing::error!("❌ WAL recovery failed: {}", e);
737                }
738            }
739        } else if store.storage.is_some() {
740            tracing::info!(
741                "📂 Boot complete (lazy-load mode): Parquet data stays on disk until first \
742                 per-tenant query"
743            );
744        }
745
746        Ok(store)
747    }
748
749    /// Whether this store was opened read-only (replica mode).
750    pub fn is_read_only(&self) -> bool {
751        self.read_only
752    }
753
754    /// Return `Err(AllSourceError::ReadOnly)` if the store is a read-only
755    /// replica. Called at the top of every write path so a replica never
756    /// appends to a WAL it does not own.
757    fn ensure_writable(&self) -> Result<()> {
758        if self.read_only {
759            return Err(crate::error::AllSourceError::ReadOnly(
760                "this AllSource instance is a read-only replica — the data directory is owned by \
761                 another running process. Stop the other process, or run a single shared writer \
762                 (e.g. Prime in --mode http) and point clients at it."
763                    .to_string(),
764            ));
765        }
766        Ok(())
767    }
768
769    /// Ingest a new event with optional optimistic concurrency check.
770    ///
771    /// If `expected_version` is `Some(v)`, the write is rejected with
772    /// `VersionConflict` unless the entity's current version equals `v`.
773    /// The version check and WAL append are atomic (locked together).
774    ///
775    /// Returns the new entity version after the append.
776    #[cfg_attr(feature = "hotpath", hotpath::measure)]
777    pub fn ingest_with_expected_version(
778        &self,
779        event: &Event,
780        expected_version: Option<u64>,
781    ) -> Result<u64> {
782        self.ingest_with_expected_version_cancellable(event, expected_version, None)
783    }
784
785    pub(crate) fn ingest_with_expected_version_cancellable(
786        &self,
787        event: &Event,
788        expected_version: Option<u64>,
789        cancellation: Option<&Arc<std::sync::atomic::AtomicBool>>,
790    ) -> Result<u64> {
791        check_cancelled(cancellation.map(Arc::as_ref))?;
792        // Reject writes in read-only (replica) mode before touching the WAL.
793        self.ensure_writable()?;
794
795        // Validate event first (before any locking)
796        self.validate_event(event)?;
797        // OCC needs the archive's versions, not its events. Reading only the
798        // versions keeps an ordinary append's lazy loading intact and keeps a
799        // large tenant from having to fit in memory to be written to.
800        if expected_version.is_some() {
801            self.ensure_version_for_entity(
802                event.tenant_id_str(),
803                event.entity_id_str(),
804                cancellation,
805            )?;
806        }
807
808        let _resident = self.cache_residency_gate.read();
809        let entity_id = event.entity_id_str().to_string();
810        let _durable = self.durability_gate.read();
811        check_cancelled(cancellation.map(Arc::as_ref))?;
812        let mut stored_event = event.clone();
813
814        // Atomic version check + append: hold the DashMap entry lock
815        // to prevent TOCTOU races between check and write.
816        let new_version = {
817            self.charge_entity_version(&entity_id);
818            let mut version_entry = self.entity_versions.entry(entity_id.clone()).or_insert(0);
819            check_cancelled(cancellation.map(Arc::as_ref))?;
820            let current = *version_entry;
821
822            if let Some(expected) = expected_version
823                && current != expected
824            {
825                return Err(crate::error::AllSourceError::VersionConflict { expected, current });
826            }
827
828            let next = current.checked_add(1).ok_or_else(|| {
829                crate::error::AllSourceError::InvalidInput("Entity version exhausted".into())
830            })?;
831            stored_event.version = i64::try_from(next).map_err(|_| {
832                crate::error::AllSourceError::InvalidInput("Entity version exhausted".into())
833            })?;
834
835            // Persist the same version that the acknowledgement returns.
836            if let Some(ref wal) = self.wal {
837                wal.append(stored_event.clone())?;
838            }
839
840            *version_entry = next;
841            next
842        };
843
844        // From here on, the event is durable (WAL) and version is bumped.
845        // Continue with indexing, projections, storage, and broadcast.
846        self.ingest_post_wal(&stored_event)?;
847
848        Ok(new_version)
849    }
850
851    /// Post-WAL ingestion: index, projections, storage, broadcast.
852    /// Called after WAL append and version bump are complete.
853    #[cfg_attr(feature = "hotpath", hotpath::measure)]
854    fn ingest_post_wal(&self, event: &Event) -> Result<()> {
855        #[cfg(feature = "server")]
856        let timer = self.metrics.ingestion_duration_seconds.start_timer();
857
858        let resident_bytes = event.resident_bytes();
859        let mut events = self.events.write();
860        let offset = events.len();
861
862        // Index the event
863        self.index.index_event(
864            event.id,
865            event.entity_id_str(),
866            event.event_type_str(),
867            event.timestamp,
868            ValidWindow::of(event),
869            offset,
870        )?;
871
872        // Process through projections
873        let projections = self.projections.read();
874        projections.process_event(event)?;
875        drop(projections);
876
877        // Process through pipelines
878        let pipeline_results = self.pipeline_manager.process_event(event);
879        if !pipeline_results.is_empty() {
880            tracing::debug!(
881                "Event {} processed by {} pipeline(s)",
882                event.id,
883                pipeline_results.len()
884            );
885            for (pipeline_id, result) in pipeline_results {
886                tracing::trace!("Pipeline {} result: {:?}", pipeline_id, result);
887            }
888        }
889
890        // Persist to Parquet storage if enabled
891        if let Some(ref storage) = self.storage {
892            let storage = storage.read();
893            storage.append_event(event.clone())?;
894        }
895
896        // Store the event in memory
897        self.observe_feed_head(event, events.len() + 1);
898        events.push(event.clone());
899        self.events_resident.add(resident_bytes);
900        let total_events = events.len();
901        drop(events);
902
903        // Broadcast to in-process subscribers (always on) + optional WS.
904        self.broadcast_ingested(Arc::new(event.clone()), resident_bytes);
905
906        // Dispatch to matching webhook subscriptions
907        #[cfg(feature = "server")]
908        self.dispatch_webhooks(event);
909
910        // Update geospatial index
911        self.geo_index.index_event(event);
912
913        // Autonomous schema evolution
914        self.schema_evolution
915            .analyze_event(event.event_type_str(), &event.payload);
916
917        // Update metrics
918        #[cfg(feature = "server")]
919        {
920            self.metrics.events_ingested_total.inc();
921            self.metrics
922                .events_ingested_by_type
923                .with_label_values(&[event.event_type_str()])
924                .inc();
925            self.metrics.storage_events_total.set(total_events as i64);
926        }
927
928        // Update legacy total counter
929        let mut total = self.total_ingested.write();
930        *total += 1;
931
932        #[cfg(feature = "server")]
933        timer.observe_duration();
934
935        tracing::debug!("Event ingested: {} (offset: {})", event.id, offset);
936
937        Ok(())
938    }
939
940    /// Ingest a new event into the store
941    #[cfg_attr(feature = "hotpath", hotpath::measure)]
942    pub fn ingest(&self, event: &Event) -> Result<()> {
943        // Start metrics timer (v0.6 feature)
944        #[cfg(feature = "server")]
945        let timer = self.metrics.ingestion_duration_seconds.start_timer();
946
947        // Reject writes in read-only (replica) mode before touching the WAL.
948        #[cfg(feature = "server")]
949        if let Err(e) = self.ensure_writable() {
950            self.metrics.ingestion_errors_total.inc();
951            timer.observe_duration();
952            return Err(e);
953        }
954        #[cfg(not(feature = "server"))]
955        self.ensure_writable()?;
956
957        // Validate event
958        #[cfg(feature = "server")]
959        if let Err(e) = self.validate_event(event) {
960            self.metrics.ingestion_errors_total.inc();
961            timer.observe_duration();
962            return Err(e);
963        }
964        #[cfg(not(feature = "server"))]
965        self.validate_event(event)?;
966
967        let _resident = self.cache_residency_gate.read();
968        let _durable = self.durability_gate.read();
969
970        // The version is stamped onto the event before anything durable sees
971        // it, so the number get_entity_version reports is the number on disk.
972        // The WAL append stays inside the entry lock: a version handed out but
973        // not persisted is one the next reader hands out again.
974        let stored_event = {
975            self.charge_entity_version(event.entity_id_str());
976            let mut version_entry = self
977                .entity_versions
978                .entry(event.entity_id_str().to_string())
979                .or_insert(0);
980            let next = version_entry.checked_add(1).ok_or_else(|| {
981                crate::error::AllSourceError::InvalidInput("Entity version exhausted".into())
982            })?;
983            let mut stored = event.clone();
984            stored.version = i64::try_from(next).map_err(|_| {
985                crate::error::AllSourceError::InvalidInput("Entity version exhausted".into())
986            })?;
987
988            if let Some(ref wal) = self.wal
989                && let Err(e) = wal.append(stored.clone())
990            {
991                #[cfg(feature = "server")]
992                {
993                    self.metrics.ingestion_errors_total.inc();
994                    timer.observe_duration();
995                }
996                return Err(e);
997            }
998
999            *version_entry = next;
1000            stored
1001        };
1002        let event = &stored_event;
1003
1004        let resident_bytes = event.resident_bytes();
1005        let mut events = self.events.write();
1006        let offset = events.len();
1007
1008        // Index the event
1009        self.index.index_event(
1010            event.id,
1011            event.entity_id_str(),
1012            event.event_type_str(),
1013            event.timestamp,
1014            ValidWindow::of(event),
1015            offset,
1016        )?;
1017
1018        // Process through projections
1019        let projections = self.projections.read();
1020        projections.process_event(event)?;
1021        drop(projections); // Release lock
1022
1023        // Process through pipelines (v0.5 feature)
1024        // Pipelines can transform, filter, and aggregate events in real-time
1025        let pipeline_results = self.pipeline_manager.process_event(event);
1026        if !pipeline_results.is_empty() {
1027            tracing::debug!(
1028                "Event {} processed by {} pipeline(s)",
1029                event.id,
1030                pipeline_results.len()
1031            );
1032            // Pipeline results could be stored, emitted, or forwarded elsewhere
1033            // For now, we just log them for observability
1034            for (pipeline_id, result) in pipeline_results {
1035                tracing::trace!("Pipeline {} result: {:?}", pipeline_id, result);
1036            }
1037        }
1038
1039        // Persist to Parquet storage if enabled (v0.2)
1040        if let Some(ref storage) = self.storage {
1041            let storage = storage.read();
1042            storage.append_event(event.clone())?;
1043        }
1044
1045        // Store the event in memory
1046        self.observe_feed_head(event, events.len() + 1);
1047        events.push(event.clone());
1048        self.events_resident.add(resident_bytes);
1049        let total_events = events.len();
1050        drop(events); // Release lock early
1051
1052        // Broadcast to in-process subscribers + optional WS.
1053        self.broadcast_ingested(Arc::new(event.clone()), resident_bytes);
1054
1055        // Dispatch to matching webhook subscriptions (v0.11 feature)
1056        #[cfg(feature = "server")]
1057        self.dispatch_webhooks(event);
1058
1059        // Update geospatial index (v2.0 feature)
1060        self.geo_index.index_event(event);
1061
1062        // Autonomous schema evolution (v2.0 feature)
1063        self.schema_evolution
1064            .analyze_event(event.event_type_str(), &event.payload);
1065
1066        // Update metrics (v0.6 feature)
1067        #[cfg(feature = "server")]
1068        {
1069            self.metrics.events_ingested_total.inc();
1070            self.metrics
1071                .events_ingested_by_type
1072                .with_label_values(&[event.event_type_str()])
1073                .inc();
1074            self.metrics.storage_events_total.set(total_events as i64);
1075        }
1076
1077        // Update legacy total counter
1078        let mut total = self.total_ingested.write();
1079        *total += 1;
1080
1081        #[cfg(feature = "server")]
1082        timer.observe_duration();
1083
1084        tracing::debug!("Event ingested: {} (offset: {})", event.id, offset);
1085
1086        Ok(())
1087    }
1088
1089    /// Ingest a batch of events with a single write lock acquisition.
1090    ///
1091    /// All events are validated first. If any event fails validation, no
1092    /// events are stored (all-or-nothing validation). Events are then written
1093    /// to WAL, indexed, processed through projections, and pushed to the
1094    /// events vector under a single write lock.
1095    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1096    pub fn ingest_batch(&self, mut batch: Vec<Event>) -> Result<()> {
1097        if batch.is_empty() {
1098            return Ok(());
1099        }
1100
1101        // Reject writes in read-only (replica) mode before touching the WAL.
1102        self.ensure_writable()?;
1103
1104        // Phase 1: Validate all events before acquiring any locks
1105        for event in &batch {
1106            self.validate_event(event)?;
1107        }
1108
1109        let _resident = self.cache_residency_gate.read();
1110        let _durable = self.durability_gate.read();
1111        let batch_count = batch.len();
1112
1113        // Phase 2: stamp each event with its version, then write to WAL.
1114        // Several events for one entity take consecutive versions. A WAL
1115        // failure after a bump leaves the mark above what is persisted, which
1116        // only ever skips a version — the reverse would reissue one.
1117        for event in &mut batch {
1118            self.charge_entity_version(event.entity_id_str());
1119            let mut version_entry = self
1120                .entity_versions
1121                .entry(event.entity_id_str().to_string())
1122                .or_insert(0);
1123            let next = version_entry.checked_add(1).ok_or_else(|| {
1124                crate::error::AllSourceError::InvalidInput("Entity version exhausted".into())
1125            })?;
1126            event.version = i64::try_from(next).map_err(|_| {
1127                crate::error::AllSourceError::InvalidInput("Entity version exhausted".into())
1128            })?;
1129            *version_entry = next;
1130        }
1131
1132        if let Some(ref wal) = self.wal {
1133            for event in &batch {
1134                wal.append(event.clone())?;
1135            }
1136        }
1137
1138        let resident_sizes: Vec<u64> = batch.iter().map(Event::resident_bytes).collect();
1139
1140        // Phase 3: Single write lock for index + projections + push
1141        let mut events = self.events.write();
1142        let projections = self.projections.read();
1143
1144        for (event, resident_bytes) in batch.into_iter().zip(resident_sizes) {
1145            let offset = events.len();
1146
1147            self.index.index_event(
1148                event.id,
1149                event.entity_id_str(),
1150                event.event_type_str(),
1151                event.timestamp,
1152                ValidWindow::of(&event),
1153                offset,
1154            )?;
1155
1156            projections.process_event(&event)?;
1157            self.pipeline_manager.process_event(&event);
1158
1159            if let Some(ref storage) = self.storage {
1160                let storage = storage.read();
1161                storage.append_event(event.clone())?;
1162            }
1163
1164            self.geo_index.index_event(&event);
1165            self.schema_evolution
1166                .analyze_event(event.event_type_str(), &event.payload);
1167
1168            // Broadcast to in-process subscribers
1169            self.broadcast_store_ring(Arc::new(event.clone()), resident_bytes);
1170
1171            self.observe_feed_head(&event, events.len() + 1);
1172            self.events_resident.add(resident_bytes);
1173            events.push(event);
1174        }
1175
1176        drop(projections);
1177        drop(events);
1178
1179        let mut total = self.total_ingested.write();
1180        *total += batch_count as u64;
1181
1182        Ok(())
1183    }
1184
1185    /// Ingest a replicated event from the leader (follower mode).
1186    ///
1187    /// Unlike `ingest()`, this method:
1188    /// - Skips WAL writing (the follower's WalReceiver manages its own local WAL)
1189    /// - Skips schema validation (the leader already validated)
1190    /// - Still indexes, processes projections/pipelines, and broadcasts to WebSocket clients
1191    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1192    pub fn ingest_replicated(&self, event: &Event) -> Result<()> {
1193        #[cfg(feature = "server")]
1194        let timer = self.metrics.ingestion_duration_seconds.start_timer();
1195
1196        let _resident = self.cache_residency_gate.read();
1197        let resident_bytes = event.resident_bytes();
1198        let mut events = self.events.write();
1199        let offset = events.len();
1200
1201        // Index the event
1202        self.index.index_event(
1203            event.id,
1204            event.entity_id_str(),
1205            event.event_type_str(),
1206            event.timestamp,
1207            ValidWindow::of(event),
1208            offset,
1209        )?;
1210
1211        // Process through projections
1212        let projections = self.projections.read();
1213        projections.process_event(event)?;
1214        drop(projections);
1215
1216        // Process through pipelines
1217        let pipeline_results = self.pipeline_manager.process_event(event);
1218        if !pipeline_results.is_empty() {
1219            tracing::debug!(
1220                "Replicated event {} processed by {} pipeline(s)",
1221                event.id,
1222                pipeline_results.len()
1223            );
1224        }
1225
1226        // A follower adopts the leader's version rather than assigning its
1227        // own. Counting here would renumber the leader's history and the two
1228        // would disagree about what version an entity is at.
1229        self.observe_entity_version(event);
1230
1231        if !self.read_only
1232            && let Some(storage) = &self.storage
1233        {
1234            storage.read().append_event(event.clone())?;
1235        }
1236
1237        // Store the event in memory
1238        self.observe_feed_head(event, events.len() + 1);
1239        events.push(event.clone());
1240        self.events_resident.add(resident_bytes);
1241        let total_events = events.len();
1242        drop(events);
1243
1244        // Broadcast to in-process subscribers + optional WS.
1245        self.broadcast_ingested(Arc::new(event.clone()), resident_bytes);
1246
1247        // Update metrics
1248        #[cfg(feature = "server")]
1249        {
1250            self.metrics.events_ingested_total.inc();
1251            self.metrics
1252                .events_ingested_by_type
1253                .with_label_values(&[event.event_type_str()])
1254                .inc();
1255            self.metrics.storage_events_total.set(total_events as i64);
1256        }
1257
1258        let mut total = self.total_ingested.write();
1259        *total += 1;
1260
1261        #[cfg(feature = "server")]
1262        timer.observe_duration();
1263
1264        tracing::debug!(
1265            "Replicated event ingested: {} (offset: {})",
1266            event.id,
1267            offset
1268        );
1269
1270        Ok(())
1271    }
1272
1273    /// Get the current version for an entity, as persisted on its latest event.
1274    /// Returns 0 if the entity has no events.
1275    #[cfg_attr(feature = "hotpath", hotpath::measure)]
1276    pub fn get_entity_version(&self, entity_id: &str) -> u64 {
1277        self.entity_versions.get(entity_id).map_or(0, |v| *v)
1278    }
1279
1280    fn broadcast_store_ring(&self, event: Arc<Event>, resident_bytes: u64) {
1281        let delivered = self.event_broadcast_tx.send(event).is_ok();
1282        self.event_ring.observe(delivered, resident_bytes);
1283    }
1284
1285    fn broadcast_ingested(&self, event: Arc<Event>, resident_bytes: u64) {
1286        #[cfg(feature = "server")]
1287        let for_websocket = Arc::clone(&event);
1288        self.broadcast_store_ring(event, resident_bytes);
1289        #[cfg(feature = "server")]
1290        self.websocket_manager.broadcast_event(for_websocket);
1291    }
1292
1293    fn charge_entity_version(&self, entity_id: &str) {
1294        self.entity_versions_charge.ensure(
1295            &self.entity_versions,
1296            entity_id,
1297            || entity_id.to_string(),
1298            || 0,
1299            entity_id.len() as u64,
1300        );
1301    }
1302
1303    /// Raise an entity's version high-water mark to the version `event` carries.
1304    ///
1305    /// The version is READ from the event, never derived from how many events
1306    /// are resident. Lazy loading and cache eviction both leave partial history
1307    /// in memory, so a count over what is resident yields a number lower than
1308    /// the one already on disk, and the next conditional write reuses it.
1309    ///
1310    /// Monotonic by construction: replaying a WAL tail over an already-loaded
1311    /// archive, or loading the same event twice, cannot lower the mark.
1312    fn observe_entity_version(&self, event: &Event) {
1313        let version = u64::try_from(event.version).unwrap_or(0);
1314        self.charge_entity_version(event.entity_id_str());
1315        self.entity_versions
1316            .entry(event.entity_id_str().to_string())
1317            .and_modify(|current| *current = (*current).max(version))
1318            .or_insert(version);
1319    }
1320
1321    /// Get the consumer registry for durable subscriptions.
1322    pub fn consumer_registry(&self) -> &ConsumerRegistry {
1323        &self.consumer_registry
1324    }
1325
1326    /// Subscribe to every successfully-ingested event in this store.
1327    ///
1328    /// Returns a `tokio::sync::broadcast::Receiver` that yields an `Arc<Event>`
1329    /// for each ingest. Always available — does not require the `server`
1330    /// feature. Lagging receivers surface `RecvError::Lagged`.
1331    pub fn subscribe_events(&self) -> tokio::sync::broadcast::Receiver<Arc<Event>> {
1332        self.event_broadcast_tx.subscribe()
1333    }
1334
1335    /// Replace the default in-memory consumer registry with a durable one.
1336    ///
1337    /// Called during startup when system repositories are available, so that
1338    /// consumer cursors survive Core restarts via WAL persistence.
1339    pub fn set_consumer_registry(&mut self, registry: Arc<ConsumerRegistry>) {
1340        self.consumer_registry = registry;
1341    }
1342
1343    /// Get the total number of events in the store (used as max offset for consumer ack).
1344    pub fn total_events(&self) -> usize {
1345        self.events.read().len()
1346    }
1347
1348    /// Get events after a given offset, optionally filtered by event type prefixes.
1349    /// Used by consumer polling to fetch unprocessed events.
1350    pub fn events_after_offset(
1351        &self,
1352        offset: u64,
1353        filters: &[String],
1354        limit: usize,
1355    ) -> Vec<(u64, Event)> {
1356        let events = self.events.read();
1357        let start = offset as usize;
1358        if start >= events.len() {
1359            return vec![];
1360        }
1361
1362        events[start..]
1363            .iter()
1364            .enumerate()
1365            .filter(|(_, event)| ConsumerRegistry::matches_filters(event.event_type_str(), filters))
1366            .take(limit)
1367            .map(|(i, event)| ((start + i + 1) as u64, event.clone()))
1368            .collect()
1369    }
1370
1371    /// Get the WebSocket manager for this store
1372    #[cfg(feature = "server")]
1373    pub fn websocket_manager(&self) -> Arc<WebSocketManager> {
1374        Arc::clone(&self.websocket_manager)
1375    }
1376
1377    /// Get the compaction manager for this store
1378    pub fn compaction_manager(&self) -> Option<Arc<CompactionManager>> {
1379        self.compaction_manager.as_ref().map(Arc::clone)
1380    }
1381
1382    /// Get the schema registry for this store (v0.5 feature)
1383    pub fn schema_registry(&self) -> Arc<SchemaRegistry> {
1384        Arc::clone(&self.schema_registry)
1385    }
1386
1387    /// Get the replay manager for this store (v0.5 feature)
1388    pub fn replay_manager(&self) -> Arc<ReplayManager> {
1389        Arc::clone(&self.replay_manager)
1390    }
1391
1392    /// Get the pipeline manager for this store (v0.5 feature)
1393    pub fn pipeline_manager(&self) -> Arc<PipelineManager> {
1394        Arc::clone(&self.pipeline_manager)
1395    }
1396
1397    /// Get the metrics registry for this store (v0.6 feature)
1398    #[cfg(feature = "server")]
1399    pub fn metrics(&self) -> Arc<MetricsRegistry> {
1400        Arc::clone(&self.metrics)
1401    }
1402
1403    /// Get the projection manager for this store (v0.7 feature)
1404    pub fn projection_manager(&self) -> parking_lot::RwLockReadGuard<'_, ProjectionManager> {
1405        self.projections.read()
1406    }
1407
1408    /// Register a custom projection at runtime.
1409    ///
1410    /// The projection will receive all future events via `process()`.
1411    /// Historical events are **not** replayed — only events ingested after
1412    /// registration will be processed by this projection.
1413    ///
1414    /// See [`register_projection_with_backfill`](Self::register_projection_with_backfill)
1415    /// to also process historical events.
1416    pub fn register_projection(
1417        &self,
1418        projection: Arc<dyn crate::application::services::projection::Projection>,
1419    ) {
1420        let mut pm = self.projections.write();
1421        pm.register(projection);
1422    }
1423
1424    /// Register a custom projection and replay all existing events through it.
1425    ///
1426    /// After registration, the projection will also receive all future events.
1427    /// Historical events are replayed under a read lock — the projection's
1428    /// internal state (typically DashMap) handles concurrent access.
1429    ///
1430    /// Replay is ordered by `(timestamp, version)`. The in-memory pile can be
1431    /// physically out of order when Parquet is hydrated after WAL recovery —
1432    /// the WAL tail holds the newest events while Parquet holds the older
1433    /// history — so the backfill must sort before replaying. Projections with
1434    /// last-write-wins merge semantics produce wrong state otherwise.
1435    pub fn register_projection_with_backfill(
1436        &self,
1437        projection: &Arc<dyn crate::application::services::projection::Projection>,
1438    ) -> Result<()> {
1439        // First register so future events are processed
1440        {
1441            let mut pm = self.projections.write();
1442            pm.register(Arc::clone(projection));
1443        }
1444
1445        // Then replay existing events in chronological order under read lock
1446        let events = self.events.read();
1447        let mut ordered: Vec<&Event> = events.iter().collect();
1448        ordered.sort_by(|a, b| {
1449            a.timestamp
1450                .cmp(&b.timestamp)
1451                .then_with(|| a.version.cmp(&b.version))
1452        });
1453        for event in ordered {
1454            projection.process(event)?;
1455        }
1456
1457        Ok(())
1458    }
1459
1460    /// Eagerly reconstruct the in-memory event pile from the full Parquet
1461    /// archive.
1462    ///
1463    /// The default boot path (Step 2, issue #160) keeps Parquet cold and
1464    /// hydrates tenants lazily on first query — the multi-tenant server
1465    /// cannot fit every tenant in memory. Embedded single-store consumers
1466    /// like Prime are the opposite case: their projections *are* the
1467    /// queryable surface and never trigger the lazy query path, so the
1468    /// projections must be backfilled from the complete history.
1469    ///
1470    /// Call this *before* registering projections. The dedupe in
1471    /// `append_loaded_event` makes it safe to run after WAL recovery —
1472    /// events already replayed from the WAL are not double-counted.
1473    /// No-op (and `Ok(0)`) when no Parquet storage is configured, e.g.
1474    /// in-memory test mode.
1475    ///
1476    /// Marks every tenant present in the archive as loaded, so a later
1477    /// `ensure_tenant_loaded` for it takes the warm path.
1478    ///
1479    /// Returns the number of events newly loaded from Parquet.
1480    pub fn hydrate_all_from_storage(&self) -> Result<usize> {
1481        let Some(storage) = self.storage.as_ref().map(Arc::clone) else {
1482            return Ok(0);
1483        };
1484
1485        let _resident = self.cache_residency_gate.read();
1486        // Listed before the load, so a file that lands in between is read again
1487        // by the first refresh and deduped, never skipped.
1488        let files_before_load = storage.read().list_parquet_files()?;
1489        let events = storage.read().load_all_events()?;
1490        self.refresh_state
1491            .lock()
1492            .mark_parquet_seen(files_before_load);
1493        let read_count = events.len();
1494        let tenants: Vec<String> = events
1495            .iter()
1496            .map(Event::tenant_id_str)
1497            .collect::<FastSet<_>>()
1498            .into_iter()
1499            .map(str::to_owned)
1500            .collect();
1501        let mut applied = 0;
1502        for event in events {
1503            applied += usize::from(self.append_loaded_event(event));
1504        }
1505        // Every tenant in the archive is now fully in memory. Unmarked, the
1506        // first `ensure_tenant_loaded` for each re-reads its whole subtree and
1507        // applies nothing.
1508        for tenant in &tenants {
1509            self.tenant_loader.mark_loaded(tenant);
1510        }
1511
1512        tracing::info!(
1513            read = read_count,
1514            applied = applied,
1515            "🔄 hydrate_all_from_storage: in-memory pile reconstructed from Parquet"
1516        );
1517        Ok(applied)
1518    }
1519
1520    /// Get the projection status map (v0.13 feature)
1521    pub fn set_projection_status(&self, name: String, status: String) {
1522        self.projection_status_charge
1523            .insert(&self.projection_status, name, status, |k, v| {
1524                string_heap(k) + string_heap(v)
1525            });
1526    }
1527
1528    pub fn projection_status(&self) -> Arc<FastDashMap<String, String>> {
1529        Arc::clone(&self.projection_status)
1530    }
1531
1532    /// Get the webhook registry for this store (v0.11 feature)
1533    /// Geospatial index for coordinate-based queries (v2.0 feature)
1534    pub fn geo_index(&self) -> Arc<GeoIndex> {
1535        self.geo_index.clone()
1536    }
1537
1538    /// Exactly-once processing registry (v2.0 feature)
1539    pub fn exactly_once(&self) -> Arc<ExactlyOnceRegistry> {
1540        self.exactly_once.clone()
1541    }
1542
1543    /// Schema evolution manager (v2.0 feature)
1544    pub fn schema_evolution(&self) -> Arc<SchemaEvolutionManager> {
1545        self.schema_evolution.clone()
1546    }
1547
1548    /// Get a read-locked snapshot of all events (for EventQL/GraphQL queries).
1549    ///
1550    /// Returns an `Arc` reference to the internal events vec, avoiding a full
1551    /// clone. The caller holds a read lock for the duration of the `Arc`
1552    /// lifetime — prefer short-lived usage.
1553    pub fn snapshot_events(&self) -> Vec<Event> {
1554        self.events.read().clone()
1555    }
1556
1557    /// Compact token events for an entity by replacing matching events with a
1558    /// single merged event. Used by the embedded streaming feature.
1559    ///
1560    /// Returns `Ok(true)` if compaction was performed, `Ok(false)` if no
1561    /// matching events were found.
1562    ///
1563    /// **Note:** The merged event is processed through projections *without*
1564    /// clearing the removed events' projection state first. Projections that
1565    /// accumulate state (e.g., counters) should be designed to handle this
1566    /// (the merged event replaces individual tokens, not adds to them).
1567    ///
1568    /// **The merged event is a derived view and is never made durable.**
1569    /// Compaction reclaims memory; it does not rewrite history. The token
1570    /// events stay in the WAL and Parquet exactly as they were ingested, so a
1571    /// restart — or any reader that goes to the durable log — sees the original
1572    /// stream, not the merge. A caller that needs the merged result to survive
1573    /// must ingest it as an event of its own.
1574    ///
1575    /// The write lock is held for the swap + WAL write + index rebuild.
1576    /// The index rebuild is O(N) over all events, which is acceptable for
1577    /// embedded workloads but should not be called in hot paths for large stores.
1578    pub fn compact_entity_tokens(
1579        &self,
1580        entity_id: &str,
1581        token_event_type: &str,
1582        merged_event: Event,
1583    ) -> Result<bool> {
1584        // Reject writes in read-only (replica) mode before touching the WAL.
1585        self.ensure_writable()?;
1586
1587        // Phase 1: Read-only check — do we have anything to compact?
1588        {
1589            let events = self.events.read();
1590            let has_tokens = events
1591                .iter()
1592                .any(|e| e.entity_id_str() == entity_id && e.event_type_str() == token_event_type);
1593            if !has_tokens {
1594                return Ok(false);
1595            }
1596        }
1597
1598        // Phase 2: Process merged event through projections (no write lock held)
1599        let projections = self.projections.read();
1600        projections.process_event(&merged_event)?;
1601        drop(projections);
1602
1603        // Phase 3: Acquire write lock for the swap + WAL + index rebuild
1604        let mut events = self.events.write();
1605
1606        let affected_tenants: std::collections::BTreeSet<_> = events
1607            .iter()
1608            .filter(|event| {
1609                event.entity_id_str() == entity_id && event.event_type_str() == token_event_type
1610            })
1611            .map(|event| event.tenant_id_str().to_owned())
1612            .collect();
1613        self.events_resident.release_matching(&events, |e| {
1614            e.entity_id_str() == entity_id && e.event_type_str() == token_event_type
1615        });
1616        self.retain_events(&mut events, |e| {
1617            !(e.entity_id_str() == entity_id && e.event_type_str() == token_event_type)
1618        });
1619
1620        self.events_resident.add(merged_event.resident_bytes());
1621        events.push(merged_event);
1622        for tenant in affected_tenants {
1623            self.rebuild_tenant_feed(&tenant, &events);
1624        }
1625
1626        // Rebuild entire index since retain() shifted event positions.
1627        // Errors here indicate a corrupt event (missing entity_id/event_type)
1628        // which should not happen for well-formed events. Log and continue
1629        // rather than failing the entire compaction.
1630        self.index.clear();
1631        for (offset, event) in events.iter().enumerate() {
1632            if let Err(e) = self.index.index_event(
1633                event.id,
1634                event.entity_id_str(),
1635                event.event_type_str(),
1636                event.timestamp,
1637                ValidWindow::of(event),
1638                offset,
1639            ) {
1640                tracing::warn!(
1641                    event_id = %event.id,
1642                    offset,
1643                    "Failed to re-index event during compaction: {e}"
1644                );
1645            }
1646        }
1647
1648        Ok(true)
1649    }
1650
1651    #[cfg(feature = "server")]
1652    pub fn webhook_registry(&self) -> Arc<WebhookRegistry> {
1653        Arc::clone(&self.webhook_registry)
1654    }
1655
1656    /// Set the channel for async webhook delivery.
1657    /// Called during server startup to wire the delivery worker.
1658    #[cfg(feature = "server")]
1659    pub fn set_webhook_tx(&self, tx: mpsc::UnboundedSender<WebhookDeliveryTask>) {
1660        *self.webhook_tx.write() = Some(tx);
1661        tracing::info!("Webhook delivery channel connected");
1662    }
1663
1664    /// Dispatch matching webhooks for a given event (non-blocking).
1665    #[cfg(feature = "server")]
1666    fn dispatch_webhooks(&self, event: &Event) {
1667        let matching = self.webhook_registry.find_matching(event);
1668        if matching.is_empty() {
1669            return;
1670        }
1671
1672        let tx_guard = self.webhook_tx.read();
1673        if let Some(ref tx) = *tx_guard {
1674            for webhook in matching {
1675                let task = WebhookDeliveryTask {
1676                    webhook,
1677                    event: event.clone(),
1678                    _queued: Lease::new(Owner::WebhookQueue, event.resident_bytes()),
1679                };
1680                if let Err(e) = tx.send(task) {
1681                    tracing::warn!("Failed to queue webhook delivery: {}", e);
1682                }
1683            }
1684        }
1685    }
1686
1687    /// Manually flush any pending events to persistent storage
1688    pub fn flush_storage(&self) -> Result<()> {
1689        if let Some(ref storage) = self.storage {
1690            let storage = storage.read();
1691            storage.flush()?;
1692            tracing::info!("✅ Flushed events to persistent storage");
1693        }
1694        Ok(())
1695    }
1696
1697    /// Run a checkpoint: flush pending Parquet batches, then truncate the
1698    /// WAL through the checkpoint point (Step 6 of the sustainable data
1699    /// strategy).
1700    ///
1701    /// Order matters. We flush Parquet first; only on success do we
1702    /// truncate the WAL. If the process crashes between the flush and the
1703    /// truncate, the WAL still contains the events that were just durably
1704    /// written, and recovery will replay them. The dedupe in
1705    /// `append_loaded_event` (index probe) makes that idempotent — the
1706    /// event is already in Parquet, so the lazy-load splice no-ops once
1707    /// the tenant is hydrated.
1708    ///
1709    /// The reverse order would be unsafe: a crash between truncate and
1710    /// flush would lose committed events.
1711    ///
1712    /// This bounds dirty-restart replay time to one checkpoint interval
1713    /// regardless of total dataset size — that's the load-bearing
1714    /// property for cold-start time as ingest rate grows.
1715    ///
1716    /// No-op when no WAL is configured (in-memory-only mode).
1717    pub fn checkpoint(&self) -> Result<()> {
1718        let Some(ref wal) = self.wal else {
1719            // No WAL (in-memory-only mode). Still refresh storage-size metrics in
1720            // case Parquet-only persistence is configured.
1721            #[cfg(feature = "server")]
1722            self.refresh_storage_metrics();
1723            return Ok(());
1724        };
1725
1726        if self.read_only {
1727            return Ok(());
1728        }
1729
1730        // Seal under the gate so every event in a sealed segment has already
1731        // reached the Parquet batch this flush drains. Events that arrive
1732        // after the seal land in the active segment, which is kept.
1733        let active = {
1734            let _sealing = self.durability_gate.write();
1735            wal.seal()?
1736        };
1737        self.flush_storage()?;
1738        self.sync_feed_log()?;
1739        wal.remove_sealed(&active)?;
1740        tracing::debug!("✅ Checkpoint complete: Parquet flushed, sealed WAL segments retired");
1741
1742        // Recompute on-disk storage size now that Parquet is flushed and the WAL
1743        // is truncated — the gauge reflects the post-checkpoint footprint.
1744        #[cfg(feature = "server")]
1745        self.refresh_storage_metrics();
1746
1747        Ok(())
1748    }
1749
1750    /// Public entrypoint to populate the on-disk storage gauges once, e.g. at boot
1751    /// so the dashboard's "storage" card is correct before the first checkpoint
1752    /// tick (and even when the checkpoint loop is disabled). Delegates to the
1753    /// internal refresh. No-op without persistent storage.
1754    #[cfg(feature = "server")]
1755    pub fn refresh_storage_metrics_now(&self) {
1756        self.refresh_storage_metrics();
1757    }
1758
1759    /// Recompute the on-disk storage gauges from the real Parquet + WAL files and
1760    /// publish them to Prometheus: `allsource_storage_size_bytes` (Parquet bytes +
1761    /// WAL segment bytes), `allsource_parquet_files_total`, and
1762    /// `allsource_wal_segments_total`.
1763    ///
1764    /// These gauges were registered but never set, so they read a constant 0 — the
1765    /// dashboard's "storage" card therefore showed `—`. This is the population.
1766    ///
1767    /// HONESTY: this is a **platform/process-wide** figure — the size of the whole
1768    /// data directory across all tenants, not any single tenant's storage. It is
1769    /// surfaced as a platform metric and must not be presented as a tenant number.
1770    ///
1771    /// Called from the checkpoint loop (default every 60s), not the ingest hot
1772    /// path: it does one `statx` per Parquet file + per WAL segment. Best-effort —
1773    /// a stat error logs and leaves the previous gauge value in place rather than
1774    /// resetting it to a misleading 0.
1775    #[cfg(feature = "server")]
1776    fn refresh_storage_metrics(&self) {
1777        let Some(ref storage) = self.storage else {
1778            return;
1779        };
1780
1781        let parquet_stats = match storage.read().stats() {
1782            Ok(stats) => stats,
1783            Err(e) => {
1784                tracing::warn!("storage-size metric refresh: failed to stat Parquet: {e}");
1785                return;
1786            }
1787        };
1788
1789        let (wal_bytes, wal_segments) = match self.wal.as_ref() {
1790            Some(wal) => match wal.on_disk_stats() {
1791                Ok(stats) => stats,
1792                Err(e) => {
1793                    tracing::warn!("storage-size metric refresh: failed to stat WAL: {e}");
1794                    (0, 0)
1795                }
1796            },
1797            None => (0, 0),
1798        };
1799
1800        let total_bytes = parquet_stats.total_size_bytes + wal_bytes;
1801
1802        self.metrics
1803            .storage_size_bytes
1804            .set(total_bytes.min(i64::MAX as u64) as i64);
1805        self.metrics
1806            .parquet_files_total
1807            .set(parquet_stats.total_files as i64);
1808        self.metrics.wal_segments_total.set(wal_segments as i64);
1809
1810        tracing::debug!(
1811            "storage-size metrics refreshed: {} bytes total ({} Parquet files, {} WAL segments)",
1812            total_bytes,
1813            parquet_stats.total_files,
1814            wal_segments
1815        );
1816    }
1817
1818    /// Get the configured checkpoint cadence (used by background tasks).
1819    pub fn checkpoint_interval(&self) -> Option<std::time::Duration> {
1820        self.checkpoint_interval_secs
1821            .map(std::time::Duration::from_secs)
1822    }
1823
1824    /// Hydrate `tenant_id`'s persisted Parquet data into the in-memory
1825    /// pile if it isn't already loaded. Cheap on the warm path
1826    /// (DashMap probe); on the cold path it walks just that tenant's
1827    /// subtree (`load_events_for_tenant`) and splices the events into
1828    /// `events`/`index`/`projections`/`entity_versions`.
1829    ///
1830    /// Concurrent first-callers for the same tenant serialize on a
1831    /// per-tenant Mutex (singleflight) so the disk read happens once.
1832    /// Other tenants are unaffected — distinct lock per tenant.
1833    ///
1834    /// Returns `Err` if the tenant_id fails the path-safety
1835    /// whitelist, directory listing fails, or another in-flight load
1836    /// holds the lock past the configured timeout. The caller (a
1837    /// query handler) is expected to surface that as a 5xx — see
1838    /// Step 2's "no infinite hangs" acceptance criterion. Individual
1839    /// unreadable files retain the tolerant query policy. Conditional
1840    /// writes use the integrity-aware path and require every file to load.
1841    ///
1842    /// On failure, `loaded` is NOT marked, so a transient error is
1843    /// retried on the next request rather than poisoning the tenant
1844    /// permanently. A future commit may add a circuit breaker if
1845    /// thrash becomes an issue.
1846    ///
1847    /// No-op (and Ok) when no Parquet storage is configured — the
1848    /// in-memory-only mode used by tests has nothing to hydrate.
1849    pub fn ensure_tenant_loaded(&self, tenant_id: &str) -> Result<()> {
1850        self.ensure_tenant_loaded_with_integrity(tenant_id, false)
1851    }
1852
1853    fn ensure_tenant_loaded_with_integrity(
1854        &self,
1855        tenant_id: &str,
1856        require_complete: bool,
1857    ) -> Result<()> {
1858        self.ensure_tenant_loaded_budgeted(tenant_id, require_complete, None)
1859    }
1860
1861    /// Limits for folding the version manifest.
1862    ///
1863    /// A fold streams one batch at a time and keeps two columns, so its peak
1864    /// memory is a batch however many files it reads. The cumulative row and
1865    /// decoded-byte ceilings therefore measure nothing it can exhaust, and
1866    /// leaving them in place would bar a file holding more than `max_rows`
1867    /// from ever being folded — a permanent refusal, not a budget.
1868    ///
1869    /// Compressed bytes stay: that one bounds the I/O a single resolve does,
1870    /// and a resolve stopping there resumes from the manifest.
1871    fn version_index_limits(&self) -> ArchiveReadLimits {
1872        ArchiveReadLimits {
1873            max_rows: u64::MAX,
1874            max_uncompressed_bytes: u64::MAX,
1875            ..self.strict_archive_limits.clone()
1876        }
1877    }
1878
1879    /// Fold one entity's archived version into `entity_versions`, once.
1880    ///
1881    /// A conditional write must not assign a version that already exists on
1882    /// disk, so the archive has to be consulted before the first OCC write
1883    /// for an entity. The tenant's version manifest answers that in one file
1884    /// read; only files the manifest does not yet cover are read.
1885    ///
1886    /// The unit is the entity, not the tenant. Resolving the whole tenant
1887    /// made one append's cost scale with the tenant's history, so past the
1888    /// strict budget every conditional write to a large tenant failed and
1889    /// certified nothing, leaving each retry to pay the same cost and fail
1890    /// the same way (gh#321).
1891    ///
1892    /// An incomplete resolve refuses the write and says so as a retry, not a
1893    /// failure: the manifest kept the files it did fold, so the next attempt
1894    /// carries on from there.
1895    ///
1896    /// Concurrent callers for a cold entity may both scan. Folding is a max,
1897    /// so a duplicate scan costs time and changes nothing.
1898    /// Whether a conditional append to this entity would read the archive.
1899    ///
1900    /// A resolved entity's high-water mark is already in `entity_versions`, so
1901    /// the append is a pure in-memory write. One archive work slot is shared
1902    /// by every tenant in the process, so queueing such an append behind it
1903    /// serialises unrelated publishes and fails them on admission rather than
1904    /// on anything they needed (gh#321).
1905    #[cfg(feature = "server")]
1906    pub(crate) fn conditional_append_reads_archive(
1907        &self,
1908        tenant_id: &str,
1909        entity_id: &str,
1910    ) -> bool {
1911        self.storage.is_some()
1912            && !self.version_index_tenants.contains_key(tenant_id)
1913            && !self.version_index_entities.contains_key(entity_id)
1914    }
1915
1916    fn ensure_version_for_entity(
1917        &self,
1918        tenant_id: &str,
1919        entity_id: &str,
1920        cancellation: Option<&Arc<std::sync::atomic::AtomicBool>>,
1921    ) -> Result<()> {
1922        if self.version_index_tenants.contains_key(tenant_id)
1923            || self.version_index_entities.contains_key(entity_id)
1924        {
1925            return Ok(());
1926        }
1927
1928        let Some(storage) = self.storage.as_ref().map(Arc::clone) else {
1929            self.version_entities_charge.ensure(
1930                &self.version_index_entities,
1931                entity_id,
1932                || entity_id.to_string(),
1933                || (),
1934                entity_id.len() as u64,
1935            );
1936            return Ok(());
1937        };
1938
1939        let mut budget = ArchiveReadBudget::new(self.version_index_limits())
1940            .with_cancellation(cancellation.cloned());
1941
1942        match storage
1943            .read()
1944            .resolve_entity_version(tenant_id, entity_id, &mut budget)?
1945        {
1946            ResolvedVersion::Complete(archived) => {
1947                if let Some(version) = archived {
1948                    self.charge_entity_version(entity_id);
1949                    self.entity_versions
1950                        .entry(entity_id.to_string())
1951                        .and_modify(|current| *current = (*current).max(version))
1952                        .or_insert(version);
1953                }
1954                self.version_entities_charge.ensure(
1955                    &self.version_index_entities,
1956                    entity_id,
1957                    || entity_id.to_string(),
1958                    || (),
1959                    entity_id.len() as u64,
1960                );
1961                Ok(())
1962            }
1963            ResolvedVersion::Incomplete { remaining, reason } => {
1964                Err(crate::error::AllSourceError::ArchiveIndexIncomplete { remaining, reason })
1965            }
1966        }
1967    }
1968
1969    fn ensure_tenant_loaded_budgeted(
1970        &self,
1971        tenant_id: &str,
1972        require_complete: bool,
1973        cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
1974    ) -> Result<()> {
1975        self.ensure_tenant_loaded_with_limits(
1976            tenant_id,
1977            require_complete,
1978            cancellation,
1979            &self.strict_archive_limits,
1980        )
1981    }
1982
1983    /// Reject a conditional append before it takes a work slot.
1984    ///
1985    /// This deliberately does NOT warm the tenant's archive. A conditional
1986    /// write reads the versions it needs and nothing else; hydrating the whole
1987    /// tenant to authorise one append is what exhausted memory on a large
1988    /// archive, and the residency it bought was never required.
1989    #[cfg(feature = "server")]
1990    pub(crate) fn prepare_http_append(
1991        &self,
1992        event: &Event,
1993        cancellation: &Arc<std::sync::atomic::AtomicBool>,
1994    ) -> Result<()> {
1995        self.ensure_writable()?;
1996        self.validate_event(event)?;
1997        check_cancelled(Some(cancellation.as_ref()))
1998    }
1999
2000    /// Refuse a cold load the process has no room for, before it allocates.
2001    ///
2002    /// The archive's size on disk is read rather than its decoded size,
2003    /// because the decoded size is only knowable by decoding it — which is
2004    /// the thing being decided. The ratio between them is measured, not
2005    /// derived, so it is an env knob
2006    /// (`hydration_admission::DEFAULT_RESIDENT_BYTES_PER_ARCHIVE_BYTE`).
2007    ///
2008    /// No eviction happens here. Trading warm tenants for a load that may
2009    /// still not fit is a worse outcome than refusing one request, and
2010    /// freeing Rust allocations does not reliably return pages to the
2011    /// kernel, so the eviction might not even move the number this checks.
2012    /// Headroom-driven eviction belongs after a load that succeeded —
2013    /// `enforce_cache_budget`.
2014    fn admit_hydration(
2015        &self,
2016        tenant_id: &str,
2017        storage: &Arc<RwLock<ParquetStorage>>,
2018    ) -> Result<()> {
2019        use crate::infrastructure::{
2020            observability::memory, persistence::hydration_admission as admission,
2021        };
2022
2023        let available = memory::available_bytes();
2024        if available.is_none() {
2025            return Ok(());
2026        }
2027        let (archive_bytes, file_count) = storage.read().tenant_archive_bytes(tenant_id)?;
2028        let reserve = admission::reserve_from_env();
2029        let ratio = admission::ratio_from_env();
2030        match admission::admit(archive_bytes, available, reserve, ratio) {
2031            Ok(()) => Ok(()),
2032            Err(refusal) => {
2033                #[cfg(feature = "server")]
2034                self.metrics.hydration_refusals_total.inc();
2035                tracing::warn!(
2036                    tenant_id = tenant_id,
2037                    archive_bytes = archive_bytes,
2038                    file_count = file_count,
2039                    needed_bytes = refusal.needed_bytes,
2040                    available_bytes = refusal.available_bytes,
2041                    resident_estimate_bytes = self.tenant_loader.total_bytes(),
2042                    "refusing to hydrate tenant: no room for its archive"
2043                );
2044                Err(AllSourceError::ArchiveHydrationRefused {
2045                    needed_bytes: refusal.needed_bytes,
2046                    available_bytes: refusal.available_bytes,
2047                })
2048            }
2049        }
2050    }
2051
2052    fn ensure_tenant_loaded_with_limits(
2053        &self,
2054        tenant_id: &str,
2055        require_complete: bool,
2056        cancellation: Option<Arc<std::sync::atomic::AtomicBool>>,
2057        limits: &ArchiveReadLimits,
2058    ) -> Result<()> {
2059        let is_loaded = || {
2060            self.tenant_loader.is_loaded(tenant_id)
2061                && (!require_complete || self.tenant_loader.is_complete(tenant_id))
2062        };
2063        // Fast path: warm tenant. Avoids the Mutex altogether.
2064        if is_loaded() {
2065            return Ok(());
2066        }
2067
2068        let mut budget = require_complete
2069            .then(|| ArchiveReadBudget::new(limits.clone()).with_cancellation(cancellation));
2070
2071        let Some(storage) = self.storage.as_ref().map(Arc::clone) else {
2072            // No persistent storage to load from. Mark loaded so we
2073            // don't keep re-entering the slow path.
2074            self.tenant_loader
2075                .mark_loaded_with_integrity(tenant_id, true);
2076            return Ok(());
2077        };
2078
2079        // Singleflight: get-or-insert the per-tenant lock and try to
2080        // acquire it within the timeout budget.
2081        let lock = self.tenant_loader.lock_for(tenant_id);
2082        let timeout = if let Some(budget) = &budget {
2083            self.tenant_loader.load_timeout().min(budget.remaining()?)
2084        } else {
2085            self.tenant_loader.load_timeout()
2086        };
2087        let _guard = lock.try_lock_for(timeout).ok_or_else(|| {
2088            AllSourceError::StorageError(format!(
2089                "ensure_tenant_loaded timed out after {timeout:?} waiting for in-flight load of \
2090                 tenant {tenant_id:?}"
2091            ))
2092        })?;
2093
2094        // Re-check inside the lock — another thread may have completed
2095        // the load while we were waiting.
2096        if is_loaded() {
2097            return Ok(());
2098        }
2099
2100        self.admit_hydration(tenant_id, &storage)?;
2101
2102        let generation = {
2103            let _resident = if let Some(budget) = &budget {
2104                self.cache_residency_gate
2105                    .try_read_for(budget.remaining()?)
2106                    .ok_or_else(|| {
2107                        AllSourceError::StorageError(
2108                            "Strict archive residency lock timed out".into(),
2109                        )
2110                    })?
2111            } else {
2112                self.cache_residency_gate.read()
2113            };
2114            self.cache_generations
2115                .get(tenant_id)
2116                .map_or(0, |value| *value)
2117        };
2118        let started = std::time::Instant::now();
2119        let (events, complete) = {
2120            let storage = if let Some(budget) = &budget {
2121                storage.try_read_for(budget.remaining()?).ok_or_else(|| {
2122                    AllSourceError::StorageError("Strict archive storage lock timed out".into())
2123                })?
2124            } else {
2125                storage.read()
2126            };
2127            storage.load_events_for_tenant_with_integrity(tenant_id, budget.as_mut())?
2128        };
2129        let read_count = events.len();
2130
2131        let resident = if let Some(budget) = &budget {
2132            self.cache_residency_gate
2133                .try_read_for(budget.remaining()?)
2134                .ok_or_else(|| {
2135                    AllSourceError::StorageError("Strict archive residency lock timed out".into())
2136                })?
2137        } else {
2138            self.cache_residency_gate.read()
2139        };
2140        if self
2141            .cache_generations
2142            .get(tenant_id)
2143            .map_or(0, |value| *value)
2144            != generation
2145        {
2146            return Err(AllSourceError::StorageError(
2147                "Archive cache changed while loading retained history".into(),
2148            ));
2149        }
2150        let mut applied = 0;
2151        let load_result = (|| -> Result<()> {
2152            for event in events {
2153                if let Some(budget) = &budget {
2154                    budget.check()?;
2155                }
2156                if complete {
2157                    if event.version < 0 {
2158                        return Err(AllSourceError::StorageError(
2159                            "Archived entity version cannot be represented".into(),
2160                        ));
2161                    }
2162                    self.observe_entity_version(&event);
2163                }
2164                applied += usize::from(self.append_loaded_event(event));
2165            }
2166            if let Some(budget) = &budget {
2167                budget.check()?;
2168            }
2169            Ok(())
2170        })();
2171        load_result?;
2172        self.tenant_loader
2173            .mark_loaded_with_integrity(tenant_id, complete);
2174        if complete {
2175            self.version_tenants_charge.ensure(
2176                &self.version_index_tenants,
2177                tenant_id,
2178                || tenant_id.to_string(),
2179                || (),
2180                tenant_id.len() as u64,
2181            );
2182        }
2183        drop(resident);
2184
2185        tracing::info!(
2186            tenant_id = tenant_id,
2187            read = read_count,
2188            applied = applied,
2189            elapsed_ms = started.elapsed().as_millis() as u64,
2190            rss_bytes = crate::infrastructure::observability::memory::resident_set_bytes(),
2191            "ensure_tenant_loaded: tenant hydrated"
2192        );
2193
2194        // Budget check (Step 3 #3). After splicing the new
2195        // tenant in, evict LRU tenants until we're back under
2196        // budget. Excludes the just-loaded tenant from the
2197        // candidate set — otherwise a single oversized tenant
2198        // would evict itself in a tight loop. If no other tenant
2199        // is loaded, accept the over-budget state and log a
2200        // warning so ops can see it.
2201        self.enforce_cache_budget(tenant_id);
2202
2203        // Refresh the resident-bytes gauge — covers both the
2204        // load-with-no-eviction case and the post-eviction state.
2205        #[cfg(feature = "server")]
2206        self.metrics
2207            .cache_bytes
2208            .set(self.tenant_loader.total_bytes() as i64);
2209
2210        Ok(())
2211    }
2212
2213    /// Walks the LRU until total resident bytes are within the
2214    /// configured budget, calling `evict_tenant` on each victim.
2215    /// Excludes `recently_touched` from the candidate set so we
2216    /// don't evict the tenant that just triggered the call. Step 3
2217    /// #3 entry point.
2218    ///
2219    /// No-op when no budget is set or when already under budget —
2220    /// most queries take the early-return fast path. Eviction is
2221    /// the cold path; with a well-sized budget this only fires
2222    /// during warm-up of new tenants past the working-set size.
2223    ///
2224    /// Measured headroom triggers it as well as the estimate. The estimate
2225    /// read 554 MB against a 2 GiB budget while the process held 3.3 GB, so
2226    /// on the estimate alone eviction never fired and the cache grew until
2227    /// the kernel intervened (gh#321). The estimate stays because it is
2228    /// per-tenant and so can order the victims; the kernel's figure says
2229    /// whether to start.
2230    fn enforce_cache_budget(&self, recently_touched: &str) {
2231        if !self.tenant_loader.over_budget() && self.has_memory_headroom() {
2232            return;
2233        }
2234        self.evict_lru_until(recently_touched, || {
2235            !self.tenant_loader.over_budget() && self.has_memory_headroom()
2236        });
2237    }
2238
2239    /// Applies the byte budget with no tenant exempt. Called on a timer, so it
2240    /// ignores kernel headroom: when available memory stays under the reserve,
2241    /// evicting frees nothing the kernel can see, and a headroom-driven loop
2242    /// would empty the cache on every tick.
2243    pub fn enforce_cache_budget_now(&self) {
2244        if !self.tenant_loader.over_budget() {
2245            return;
2246        }
2247        self.evict_lru_until("", || !self.tenant_loader.over_budget());
2248    }
2249
2250    fn evict_lru_until(&self, recently_touched: &str, satisfied: impl Fn() -> bool) {
2251        loop {
2252            let Some(victim) = self.tenant_loader.pick_lru_excluding(recently_touched) else {
2253                tracing::warn!(
2254                    cache_bytes = self.tenant_loader.total_bytes(),
2255                    budget = self.tenant_loader.byte_budget(),
2256                    available_bytes =
2257                        crate::infrastructure::observability::memory::available_bytes(),
2258                    recently_touched = recently_touched,
2259                    "cache over budget but no other tenant available to evict — \
2260                     a single tenant exceeds the budget; consider raising it"
2261                );
2262                return;
2263            };
2264            if !self.try_evict_tenant(&victim) {
2265                tracing::warn!(
2266                    tenant_id = victim,
2267                    "cache eviction refused; retaining resident history"
2268                );
2269                return;
2270            }
2271            if satisfied() {
2272                return;
2273            }
2274        }
2275    }
2276
2277    /// True when the kernel still reports the configured reserve free, and
2278    /// when the platform reports nothing.
2279    fn has_memory_headroom(&self) -> bool {
2280        crate::infrastructure::observability::memory::has_headroom(
2281            crate::infrastructure::persistence::hydration_admission::reserve_from_env(),
2282        )
2283    }
2284
2285    /// True iff this tenant is resident: `ensure_tenant_loaded` succeeded
2286    /// for it, or `hydrate_all_from_storage` found it in the archive, and
2287    /// it has not been evicted since. Diagnostic / testing API.
2288    pub fn is_tenant_loaded(&self, tenant_id: &str) -> bool {
2289        self.tenant_loader.is_loaded(tenant_id)
2290    }
2291
2292    /// Drop `tenant_id` from the in-memory cache. Step 3 #2 of the
2293    /// sustainable data strategy.
2294    ///
2295    /// Removes every event for this tenant from the events Vec,
2296    /// rebuilds the index for the retained events
2297    /// (Vec offsets shift on remove, so the index has to be
2298    /// rebuilt), and resets the tenant_loader bookkeeping so a
2299    /// subsequent query triggers a fresh `ensure_tenant_loaded`.
2300    ///
2301    /// **Parquet is canonical, in-memory is just cache.** This
2302    /// only affects the in-memory side. Pending or in-flight archive writes,
2303    /// read-only stores and stores without an archive retain their cache.
2304    /// Eviction is best-effort; a later query reloads completed archive writes.
2305    ///
2306    /// Projection state is NOT rolled back. Projections accumulate
2307    /// across boots and tenants (their durability story is
2308    /// separate); subtracting them would need replay support that
2309    /// doesn't exist in this commit. After eviction + re-load,
2310    /// projections may double-count the re-loaded events. Step 3
2311    /// #4's stress test only asserts the cache budget is held; a
2312    /// future commit will tackle projection-aware eviction.
2313    ///
2314    /// Locking: takes the events write lock for the full duration
2315    /// of the filter + re-index. Concurrent ingest blocks until
2316    /// done. Eviction is the cold path; the working set should
2317    /// stay in budget so this rarely fires.
2318    pub fn evict_tenant(&self, tenant_id: &str) {
2319        self.try_evict_tenant(tenant_id);
2320    }
2321
2322    fn try_evict_tenant(&self, tenant_id: &str) -> bool {
2323        let _resident = self.cache_residency_gate.write();
2324        let Some(storage) = &self.storage else {
2325            // There is no archive from which to reconstruct an in-memory store.
2326            return false;
2327        };
2328        if self.read_only {
2329            return false;
2330        }
2331        // Never perform or wait for disk I/O under the exclusive cache gate.
2332        // A pending or in-flight flush means memory still owns queryable data.
2333        let Some(storage) = storage.try_write() else {
2334            return false;
2335        };
2336        if storage.has_pending_tenant_events(tenant_id) {
2337            return false;
2338        }
2339        {
2340            self.cache_generations_charge.ensure(
2341                &self.cache_generations,
2342                tenant_id,
2343                || tenant_id.to_string(),
2344                || 0,
2345                tenant_id.len() as u64,
2346            );
2347            let mut generation = self
2348                .cache_generations
2349                .entry(tenant_id.to_string())
2350                .or_insert(0);
2351            let Some(next) = generation.checked_add(1) else {
2352                return false;
2353            };
2354            *generation = next;
2355        }
2356        let mut events = self.events.write();
2357        let before = events.len();
2358        let evicted_bytes = self.tenant_loader.bytes_for(tenant_id);
2359
2360        self.events_resident
2361            .release_matching(&events, |e| e.tenant_id_str() == tenant_id);
2362        self.retain_events(&mut events, |e| e.tenant_id_str() != tenant_id);
2363        self.feed_indexes_charge
2364            .forget(&self.feed_indexes, tenant_id, tenant_id.len() as u64);
2365        self.feed_indexes.remove(tenant_id);
2366        let after = events.len();
2367        let dropped = before - after;
2368
2369        if dropped == 0 {
2370            // Tenant had no events in memory. Still clear loader
2371            // state (e.g. a "loaded with zero events" marker) so
2372            // is_tenant_loaded reports the right thing.
2373            self.tenant_loader.mark_unloaded(tenant_id);
2374            return true;
2375        }
2376
2377        // Rebuild the index — Vec offsets shifted under retain().
2378        //
2379        // entity_versions is global and must NOT be rebuilt here: it is a
2380        // high-water mark of persisted versions, not a census of resident
2381        // events, and dropping one tenant's cache lowers no entity's version
2382        // on disk.
2383        self.index.clear();
2384        for (offset, event) in events.iter().enumerate() {
2385            if let Err(e) = self.index.index_event(
2386                event.id,
2387                event.entity_id_str(),
2388                event.event_type_str(),
2389                event.timestamp,
2390                ValidWindow::of(event),
2391                offset,
2392            ) {
2393                tracing::error!(
2394                    "Failed to re-index event during eviction of {}: {}",
2395                    tenant_id,
2396                    e
2397                );
2398            }
2399        }
2400        // retain() keeps the old capacity, which is the memory an eviction
2401        // exists to return.
2402        events.shrink_to_fit();
2403        self.tenant_loader.mark_unloaded(tenant_id);
2404
2405        // total_ingested under Steps 2-3 means "events currently
2406        // resident in memory". Subtract what we just dropped.
2407        let mut t = self.total_ingested.write();
2408        *t = t.saturating_sub(dropped as u64);
2409        drop(t);
2410        drop(events);
2411
2412        // Step 3 #4: cache observability. Increment the eviction
2413        // counter, refresh the resident-bytes gauge.
2414        #[cfg(feature = "server")]
2415        {
2416            self.metrics.cache_evictions_total.inc();
2417            self.metrics
2418                .cache_bytes
2419                .set(self.tenant_loader.total_bytes() as i64);
2420        }
2421
2422        tracing::info!(
2423            tenant_id = tenant_id,
2424            events_dropped = dropped,
2425            bytes_freed = evicted_bytes,
2426            "evicted tenant from memory cache"
2427        );
2428        true
2429    }
2430
2431    /// Approximate resident bytes a single tenant occupies in the
2432    /// in-memory cache. Step 3 budget-tracking input. 0 for cold
2433    /// or evicted tenants.
2434    pub fn tenant_resident_bytes(&self, tenant_id: &str) -> u64 {
2435        self.tenant_loader.bytes_for(tenant_id)
2436    }
2437
2438    /// Sum of resident-byte estimates across every loaded tenant.
2439    /// What the budget check compares against.
2440    pub fn cache_resident_bytes(&self) -> u64 {
2441        self.tenant_loader.total_bytes()
2442    }
2443
2444    /// Splice a single loaded event into the in-memory structures
2445    /// (events vec, index, projections, entity_versions) atomically
2446    /// w.r.t. concurrent ingest. Used by `ensure_tenant_loaded`.
2447    ///
2448    /// The WAL recovery path on boot has its own (single-threaded)
2449    /// variant inline because boot can't race with ingest. This
2450    /// helper is the variant safe to call while traffic is flowing
2451    /// — it holds the events write lock across the index/offset
2452    /// assignment so (offset, push) stays atomic.
2453    ///
2454    /// Dedupes against events already in memory by event ID. Two
2455    /// paths can surface the same event:
2456    /// 1. WAL recovery on boot pushed it into memory.
2457    /// 2. The event was then checkpointed to Parquet and the
2458    ///    WAL truncated. A later ensure_tenant_loaded re-reads
2459    ///    the Parquet file, including this event.
2460    ///
2461    /// Without the dedupe, step 2 would double-count the event.
2462    /// The check is O(1) — DashMap probe by UUID — and the
2463    /// alternative (loading every tenant before truncating WAL)
2464    /// would defeat the lazy-load.
2465    fn append_loaded_event(&self, event: Event) -> bool {
2466        let mut events = self.events.write();
2467        if self.index.get_by_id(&event.id).is_some() {
2468            return false;
2469        }
2470
2471        let event_bytes = event.estimated_size_bytes();
2472        let tenant = event.tenant_id_str().to_string();
2473
2474        let offset = events.len();
2475
2476        if let Err(e) = self.index.index_event(
2477            event.id,
2478            event.entity_id_str(),
2479            event.event_type_str(),
2480            event.timestamp,
2481            ValidWindow::of(&event),
2482            offset,
2483        ) {
2484            tracing::error!("Failed to index loaded event {}: {}", event.id, e);
2485        }
2486
2487        if let Err(e) = self.projections.read().process_event(&event) {
2488            tracing::error!("Failed to project loaded event {}: {}", event.id, e);
2489        }
2490
2491        self.observe_entity_version(&event);
2492
2493        self.observe_feed_head(&event, events.len() + 1);
2494        self.events_resident.add(event.resident_bytes());
2495        events.push(event);
2496        // Account for the bytes AFTER the push so a panic in the
2497        // index/projection path doesn't leave the counter inflated.
2498        // The DashMap update is itself the last fallible step.
2499        self.tenant_loader.add_bytes(&tenant, event_bytes);
2500        *self.total_ingested.write() += 1;
2501        true
2502    }
2503
2504    /// Validate an event before ingestion
2505    fn validate_event(&self, event: &Event) -> Result<()> {
2506        // EntityId and EventType value objects already validate non-empty in their constructors
2507        // So these checks are now redundant, but we keep them for explicit validation
2508        if event.entity_id_str().is_empty() {
2509            return Err(AllSourceError::ValidationError(
2510                "entity_id cannot be empty".to_string(),
2511            ));
2512        }
2513
2514        if event.event_type_str().is_empty() {
2515            return Err(AllSourceError::ValidationError(
2516                "event_type cannot be empty".to_string(),
2517            ));
2518        }
2519
2520        // Reject system namespace events from user-facing ingestion.
2521        // System events are written exclusively via SystemMetadataStore.
2522        if event.event_type().is_system() {
2523            return Err(AllSourceError::ValidationError(
2524                "Event types starting with '_system.' are reserved for internal use".to_string(),
2525            ));
2526        }
2527
2528        Ok(())
2529    }
2530
2531    /// Reset a projection by clearing its state and reprocessing all events
2532    pub fn reset_projection(&self, name: &str) -> Result<usize> {
2533        let projection_manager = self.projections.read();
2534        let projection = projection_manager.get_projection(name).ok_or_else(|| {
2535            AllSourceError::EntityNotFound(format!("Projection '{name}' not found"))
2536        })?;
2537
2538        // Clear existing state
2539        projection.clear();
2540
2541        // Reprocess all events through this projection
2542        let events = self.events.read();
2543        let mut reprocessed = 0usize;
2544        for event in events.iter() {
2545            if projection.process(event).is_ok() {
2546                reprocessed += 1;
2547            }
2548        }
2549
2550        Ok(reprocessed)
2551    }
2552
2553    /// Get a single event by its UUID
2554    pub fn get_event_by_id(&self, event_id: &uuid::Uuid) -> Result<Option<Event>> {
2555        if let Some(offset) = self.index.get_by_id(event_id) {
2556            let events = self.events.read();
2557            Ok(events.get(offset).cloned())
2558        } else {
2559            Ok(None)
2560        }
2561    }
2562
2563    /// A resident event by UUID, cloned only when it belongs to `tenant`.
2564    pub fn resident_event_for_tenant(&self, event_id: &uuid::Uuid, tenant: &str) -> Option<Event> {
2565        let offset = self.index.get_by_id(event_id)?;
2566        let events = self.events.read();
2567        let event = events.get(offset)?;
2568        (event.id == *event_id && event.tenant_id_str() == tenant).then(|| event.clone())
2569    }
2570
2571    /// Geo query within `tenant`, with the resident bytes of every event it cloned.
2572    pub fn geo_query_for_tenant(
2573        &self,
2574        request: &crate::infrastructure::query::geospatial::GeoQueryRequest,
2575        tenant: &str,
2576    ) -> (
2577        Vec<crate::infrastructure::query::geospatial::GeoEventResult>,
2578        u64,
2579    ) {
2580        let geo_index = self.geo_index();
2581        let cloned = std::cell::Cell::new(0u64);
2582        let results = crate::infrastructure::query::geospatial::execute_geo_query(
2583            &|id| {
2584                let event = self.resident_event_for_tenant(&id, tenant)?;
2585                cloned.set(cloned.get() + event.resident_bytes());
2586                Some(event)
2587            },
2588            &geo_index,
2589            request,
2590        );
2591        (results, cloned.get())
2592    }
2593
2594    /// Query events based on filters (optimized with indices).
2595    ///
2596    /// Ascending by `(timestamp, version)`, windowed by `request.limit`.
2597    #[cfg_attr(feature = "hotpath", hotpath::measure)]
2598    pub fn query(&self, request: &QueryEventsRequest) -> Result<Vec<Event>> {
2599        self.query_window(request, 0, false)
2600            .map(|(events, _)| events)
2601    }
2602
2603    /// [`Self::query`] under a read scope the request body cannot widen.
2604    pub fn query_scoped(
2605        &self,
2606        request: &QueryEventsRequest,
2607        scope: &ReadScope,
2608    ) -> Result<Vec<Event>> {
2609        self.query_window_scoped(request, 0, false, scope)
2610            .map(|(events, _)| events)
2611    }
2612
2613    /// Query events and return only the requested window, plus the total number
2614    /// of matches the window was taken from.
2615    ///
2616    /// `request.limit` bounds the window; `offset` skips that many matches
2617    /// first; `descending` returns newest first. The returned total is the
2618    /// pre-window match count, which is what `total_count`/`has_more` need.
2619    ///
2620    /// Cost (issue #251). Matching still costs an O(N) index scan over the
2621    /// entity's/type's entries — that is inherent to reporting `total`, and this
2622    /// method does not pretend otherwise. What `limit` *does* bound is the
2623    /// ordering and the materialization: matches are held as borrowed
2624    /// references, the `offset + limit` window is partitioned off with
2625    /// `select_nth_unstable_by` (O(N)) and only that window is sorted
2626    /// (O(k log k)) and cloned. So a `limit=1` read over a 100k-event entity
2627    /// scans 100k index entries but sorts and clones one event, where it
2628    /// previously sorted and cloned 100k.
2629    #[cfg_attr(feature = "hotpath", hotpath::measure)]
2630    pub fn query_window(
2631        &self,
2632        request: &QueryEventsRequest,
2633        offset: usize,
2634        descending: bool,
2635    ) -> Result<(Vec<Event>, usize)> {
2636        self.query_window_scoped(request, offset, descending, &ReadScope::unrestricted())
2637    }
2638
2639    /// [`Self::query_window`] under a [`ReadScope`].
2640    ///
2641    /// Every read path in this store funnels through here, which is the point:
2642    /// a scope enforced in one API surface leaves the others open, and the
2643    /// surfaces that matter (HTTP, the embedded API, MCP) all end up on this
2644    /// method. The scope is a separate argument rather than a field on
2645    /// `QueryEventsRequest` **because that type is deserialized from the
2646    /// request body** — a caller could then widen its own scope by omitting the
2647    /// field.
2648    pub fn query_window_scoped(
2649        &self,
2650        request: &QueryEventsRequest,
2651        offset: usize,
2652        descending: bool,
2653        scope: &ReadScope,
2654    ) -> Result<(Vec<Event>, usize)> {
2655        self.query_window_scoped_ordered(
2656            request,
2657            offset,
2658            descending,
2659            scope,
2660            WindowOrder::RecordTime,
2661        )
2662    }
2663
2664    /// [`Self::query_window_scoped`] ordered by `order` instead of record time.
2665    pub fn query_window_scoped_ordered(
2666        &self,
2667        request: &QueryEventsRequest,
2668        offset: usize,
2669        descending: bool,
2670        scope: &ReadScope,
2671        order: WindowOrder,
2672    ) -> Result<(Vec<Event>, usize)> {
2673        // Reject a payload filter that cannot be applied, BEFORE doing any
2674        // work. `apply_filters` parses it per event with `if let Ok(..)`, so an
2675        // unparseable filter degraded into NO filter: the query answered with
2676        // every event the caller had asked to exclude, `total_count` agreed,
2677        // and nothing in the response said the filter had been dropped. A
2678        // filter must fail closed — loudly — not open.
2679        if let Some(filter) = &request.payload_filter
2680            && serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(filter).is_err()
2681        {
2682            return Err(AllSourceError::InvalidInput(format!(
2683                "invalid 'payload_filter': expected a JSON object of field/value \
2684                 pairs, got '{filter}'"
2685            )));
2686        }
2687
2688        // Lazy-load gate (Step 2): if the request scopes to a tenant,
2689        // make sure that tenant's persisted data is in memory before
2690        // running the in-memory index lookup. First call for a cold
2691        // tenant blocks here for the disk read (single-digit seconds
2692        // on ~100k events); warm tenants take the DashMap fast path
2693        // and add no measurable latency.
2694        //
2695        // Errors propagate as `Err`; the HTTP layer turns that into
2696        // a 5xx, which is the explicit "no infinite hangs" contract
2697        // from the Step 2 acceptance criteria.
2698        //
2699        // Unfiltered (cross-tenant) queries — `tenant_id = None` —
2700        // run against whatever is currently in memory. They cannot
2701        // pre-load every tenant without defeating the whole point
2702        // of the lazy-load model. In practice the gateway always
2703        // injects an auth-derived `tenant_id`; an unfiltered query
2704        // is admin-only and gets degraded results until a future
2705        // commit adds an explicit "load all tenants" admin path.
2706        if let Some(ref tenant_id) = request.tenant_id {
2707            match self.ensure_tenant_loaded(tenant_id) {
2708                Ok(()) => {
2709                    // LRU touch — the most-recently-queried tenant moves
2710                    // to the back of the eviction queue. Cheap (single
2711                    // DashMap insert), called on every per-tenant query.
2712                    self.tenant_loader.touch(tenant_id);
2713                }
2714                // A tenant too large to be resident can still answer a
2715                // question about one entity, and that is the question the
2716                // publish path asks. Reading the entity out of the archive
2717                // costs the entity's events, not the tenant's history.
2718                Err(AllSourceError::ArchiveHydrationRefused { .. })
2719                    if request.entity_id.is_some() =>
2720                {
2721                    return self
2722                        .query_window_from_archive(request, offset, descending, scope, order);
2723                }
2724                Err(error) => return Err(error),
2725            }
2726        }
2727
2728        // Determine query type for metrics (v0.6 feature)
2729        let query_type = if request.entity_id.is_some() {
2730            "entity"
2731        } else if request.event_type.is_some() {
2732            "type"
2733        } else if request.event_type_prefix.is_some() {
2734            "type_prefix"
2735        } else {
2736            "full_scan"
2737        };
2738
2739        // Start metrics timer (v0.6 feature)
2740        #[cfg(feature = "server")]
2741        let timer = self
2742            .metrics
2743            .query_duration_seconds
2744            .with_label_values(&[query_type])
2745            .start_timer();
2746
2747        // Increment query counter (v0.6 feature)
2748        #[cfg(feature = "server")]
2749        self.metrics
2750            .queries_total
2751            .with_label_values(&[query_type])
2752            .inc();
2753
2754        let events = self.events.read();
2755
2756        // Use index for fast lookups
2757        let offsets: Vec<usize> = if let Some(entity_id) = &request.entity_id {
2758            // Use entity index
2759            self.index
2760                .get_by_entity(entity_id)
2761                .map(|entries| self.filter_entries(entries, request))
2762                .unwrap_or_default()
2763        } else if let Some(event_type) = &request.event_type {
2764            // Use type index (exact match)
2765            self.index
2766                .get_by_type(event_type)
2767                .map(|entries| self.filter_entries(entries, request))
2768                .unwrap_or_default()
2769        } else if let Some(prefix) = &request.event_type_prefix {
2770            // Use type index (prefix match)
2771            let entries = self.index.get_by_type_prefix(prefix);
2772            self.filter_entries(entries, request)
2773        } else {
2774            // Full scan (less efficient but necessary for complex queries)
2775            (0..events.len()).collect()
2776        };
2777
2778        // Apply remaining filters against BORROWED events — cloning happens
2779        // only for the window that survives the selection below. Each match
2780        // carries its scan position, which is the final tie-breaker and makes
2781        // the ordering a *total* order; that is what lets the partial selection
2782        // below produce exactly what a stable full sort would have.
2783        let mut matches: Vec<(usize, &Event)> = offsets
2784            .iter()
2785            .filter_map(|&event_offset| events.get(event_offset))
2786            .filter(|event| scope.permits(event.entity_id().as_str()))
2787            .filter(|event| self.apply_filters(event, request))
2788            .enumerate()
2789            .collect();
2790
2791        // Total is the match count before windowing — callers surface it as
2792        // `total_count`/`has_more`.
2793        let total = matches.len();
2794
2795        let comparator = |a: &(usize, &Event), b: &(usize, &Event)| {
2796            let ascending = compare_query_order(a.1, b.1, order).then_with(|| a.0.cmp(&b.0));
2797            if descending {
2798                ascending.reverse()
2799            } else {
2800                ascending
2801            }
2802        };
2803
2804        // Bounded selection (issue #251): sort only the requested window.
2805        select_window(&mut matches, offset, request.limit, comparator);
2806
2807        // Apply the offset. `limit` is already accounted for: either the window
2808        // was truncated by `select_window`, or it covered the whole match set.
2809        let results: Vec<Event> = matches
2810            .into_iter()
2811            .skip(offset)
2812            .map(|(_, event)| event.clone())
2813            .collect();
2814
2815        // Record query results count (v0.6 feature)
2816        #[cfg(feature = "server")]
2817        {
2818            self.metrics
2819                .query_results_total
2820                .with_label_values(&[query_type])
2821                .inc_by(results.len() as u64);
2822            timer.observe_duration();
2823        }
2824
2825        Ok((results, total))
2826    }
2827
2828    /// Answer an entity-scoped query out of the archive, for a tenant that
2829    /// cannot be made resident.
2830    ///
2831    /// Filters, ordering and windowing are the resident path's: the predicate
2832    /// is `apply_filters` itself and the comparator is `compare_query_order`
2833    /// with the same scan-position tie-breaker, so the two paths cannot disagree
2834    /// about what matches or in what order. For a single entity `version` is
2835    /// already unique, so the scan position never decides anything here.
2836    ///
2837    /// Unreadable files are skipped and logged, which is the tolerant query
2838    /// policy the resident path also applies — a corrupt file must not brick
2839    /// every read for the tenant. A skipped file means the answer may be
2840    /// short, and nothing in the response can distinguish that from the
2841    /// entity having no more events, so it is logged at `warn`.
2842    fn query_window_from_archive(
2843        &self,
2844        request: &QueryEventsRequest,
2845        offset: usize,
2846        descending: bool,
2847        scope: &ReadScope,
2848        order: WindowOrder,
2849    ) -> Result<(Vec<Event>, usize)> {
2850        let (Some(tenant_id), Some(entity_id)) =
2851            (request.tenant_id.as_deref(), request.entity_id.as_deref())
2852        else {
2853            return Ok((Vec::new(), 0));
2854        };
2855        if !scope.permits(entity_id) {
2856            return Ok((Vec::new(), 0));
2857        }
2858        let Some(storage) = self.storage.as_ref() else {
2859            return Ok((Vec::new(), 0));
2860        };
2861
2862        let (events, skipped) = storage
2863            .read()
2864            .load_entity_events_for_tenant(tenant_id, entity_id)?;
2865        if skipped > 0 {
2866            tracing::warn!(
2867                tenant_id = tenant_id,
2868                entity_id = entity_id,
2869                skipped_files = skipped,
2870                "entity-scoped archive read skipped unreadable files; result may be short"
2871            );
2872        }
2873
2874        for event in &events {
2875            self.observe_entity_version(event);
2876        }
2877
2878        let mut matches: Vec<(usize, Event)> = events
2879            .into_iter()
2880            .filter(|event| self.apply_filters(event, request))
2881            .enumerate()
2882            .collect();
2883        let total = matches.len();
2884
2885        let comparator = |a: &(usize, Event), b: &(usize, Event)| {
2886            let ascending = compare_query_order(&a.1, &b.1, order).then_with(|| a.0.cmp(&b.0));
2887            if descending {
2888                ascending.reverse()
2889            } else {
2890                ascending
2891            }
2892        };
2893        select_window(&mut matches, offset, request.limit, comparator);
2894
2895        let results: Vec<Event> = matches
2896            .into_iter()
2897            .skip(offset)
2898            .map(|(_, event)| event)
2899            .collect();
2900        Ok((results, total))
2901    }
2902
2903    /// Both time axes, shared by the indexed and full-scan paths so they cannot
2904    /// disagree. Record bounds (`as_of`, `since`, `until`) read `recorded`;
2905    /// valid bounds read `valid`.
2906    fn within_time_axes(
2907        recorded: DateTime<Utc>,
2908        valid: ValidWindow,
2909        request: &QueryEventsRequest,
2910    ) -> bool {
2911        if let Some(as_of) = request.as_of
2912            && recorded > as_of
2913        {
2914            return false;
2915        }
2916        if let Some(since) = request.since
2917            && recorded < since
2918        {
2919            return false;
2920        }
2921        if let Some(until) = request.until
2922            && recorded > until
2923        {
2924            return false;
2925        }
2926        if let Some(as_of_valid) = request.as_of_valid
2927            && (valid.from > as_of_valid || valid.to.is_some_and(|to| to <= as_of_valid))
2928        {
2929            return false;
2930        }
2931        if let Some(since_valid) = request.since_valid
2932            && valid.from < since_valid
2933        {
2934            return false;
2935        }
2936        if let Some(until_valid) = request.until_valid
2937            && valid.from > until_valid
2938        {
2939            return false;
2940        }
2941        true
2942    }
2943
2944    /// Filter index entries based on query parameters
2945    #[cfg_attr(feature = "hotpath", hotpath::measure)]
2946    fn filter_entries(&self, entries: Vec<IndexEntry>, request: &QueryEventsRequest) -> Vec<usize> {
2947        entries
2948            .into_iter()
2949            .filter(|entry| Self::within_time_axes(entry.timestamp, entry.valid, request))
2950            .map(|entry| entry.offset)
2951            .collect()
2952    }
2953
2954    /// Apply filters to an event
2955    #[cfg_attr(feature = "hotpath", hotpath::measure)]
2956    fn apply_filters(&self, event: &Event, request: &QueryEventsRequest) -> bool {
2957        // Tenant isolation: if a tenant_id is specified, only return events from that tenant
2958        if let Some(ref tid) = request.tenant_id
2959            && event.tenant_id_str() != tid
2960        {
2961            return false;
2962        }
2963
2964        // Time ranges. `filter_entries` applies the same bounds to index entries
2965        // on the indexed branches only; the full-scan branch has no index entry
2966        // and must check the event itself. An index entry's window is its
2967        // event's, so the re-check on indexed paths is idempotent.
2968        if !Self::within_time_axes(event.timestamp, ValidWindow::of(event), request) {
2969            return false;
2970        }
2971
2972        // Exclusion: drop events whose type starts with any excluded prefix
2973        // (comma-separated). Applied here, before sort+limit, so excluded events
2974        // never consume the result window.
2975        if let Some(ref excludes) = request.exclude_event_type_prefix {
2976            let et = event.event_type_str();
2977            if excludes
2978                .split(',')
2979                .map(str::trim)
2980                .filter(|p| !p.is_empty())
2981                .any(|p| et.starts_with(p))
2982            {
2983                return false;
2984            }
2985        }
2986
2987        // Additional type filter if entity was primary
2988        if request.entity_id.is_some()
2989            && let Some(ref event_type) = request.event_type
2990            && event.event_type_str() != event_type
2991        {
2992            return false;
2993        }
2994
2995        // Additional prefix filter if entity was primary
2996        if request.entity_id.is_some()
2997            && let Some(ref prefix) = request.event_type_prefix
2998            && !event.event_type_str().starts_with(prefix)
2999        {
3000            return false;
3001        }
3002
3003        // Payload field filtering
3004        if let Some(ref filter_str) = request.payload_filter
3005            && let Ok(filter_obj) =
3006                serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(filter_str)
3007        {
3008            let payload = event.payload();
3009            for (key, expected_value) in &filter_obj {
3010                match payload.get(key) {
3011                    Some(actual_value) if actual_value == expected_value => {}
3012                    _ => return false,
3013                }
3014            }
3015        }
3016
3017        true
3018    }
3019
3020    /// Reconstruct entity state as of a specific timestamp, across every
3021    /// tenant, with the folded events in `history`.
3022    #[cfg_attr(feature = "hotpath", hotpath::measure)]
3023    pub fn reconstruct_state(
3024        &self,
3025        entity_id: &str,
3026        as_of: Option<DateTime<Utc>>,
3027    ) -> Result<serde_json::Value> {
3028        self.entity_state(entity_id, as_of, None, true)
3029    }
3030
3031    /// Fold an entity's events into its state. `tenant_id: None` folds every
3032    /// tenant's events for that entity id. `version` equals `event_count`, the
3033    /// number of events folded, so it is tenant-scoped whenever the fold is.
3034    pub fn entity_state(
3035        &self,
3036        entity_id: &str,
3037        as_of: Option<DateTime<Utc>>,
3038        tenant_id: Option<&str>,
3039        include_history: bool,
3040    ) -> Result<serde_json::Value> {
3041        self.entity_state_at(entity_id, as_of, None, tenant_id, include_history)
3042    }
3043
3044    /// [`Self::entity_state`] on both time axes.
3045    ///
3046    /// With `as_of_valid` set, the events true at that instant are folded in
3047    /// valid-time order, so a correction with an earlier `valid_from` lands at
3048    /// its own position rather than at its record position. Without it the fold
3049    /// is in record order, as before. `as_of_valid` with no `as_of_recorded`
3050    /// bounds recording at now.
3051    pub fn entity_state_at(
3052        &self,
3053        entity_id: &str,
3054        as_of_recorded: Option<DateTime<Utc>>,
3055        as_of_valid: Option<DateTime<Utc>>,
3056        tenant_id: Option<&str>,
3057        include_history: bool,
3058    ) -> Result<serde_json::Value> {
3059        let order = if as_of_valid.is_some() {
3060            WindowOrder::ValidTime
3061        } else {
3062            WindowOrder::RecordTime
3063        };
3064        let (events, _) = self.query_window_scoped_ordered(
3065            &QueryEventsRequest {
3066                as_of_valid,
3067                since_valid: None,
3068                until_valid: None,
3069                entity_id: Some(entity_id.to_string()),
3070                event_type: None,
3071                tenant_id: tenant_id.map(str::to_string),
3072                as_of: as_of_recorded.or_else(|| as_of_valid.map(|_| Utc::now())),
3073                since: None,
3074                until: None,
3075                limit: None,
3076                event_type_prefix: None,
3077                exclude_event_type_prefix: None,
3078                payload_filter: None,
3079            },
3080            0,
3081            false,
3082            &ReadScope::unrestricted(),
3083            order,
3084        )?;
3085
3086        if events.is_empty() {
3087            return Err(AllSourceError::EntityNotFound(entity_id.to_string()));
3088        }
3089
3090        let mut merged_state = serde_json::json!({});
3091        for event in &events {
3092            if let serde_json::Value::Object(ref mut state_map) = merged_state
3093                && let serde_json::Value::Object(ref payload_map) = event.payload
3094            {
3095                for (key, value) in payload_map {
3096                    state_map.insert(key.clone(), value.clone());
3097                }
3098            }
3099        }
3100
3101        let mut state = serde_json::json!({
3102            "entity_id": entity_id,
3103            "last_updated": events.last().map(|e| e.timestamp),
3104            "event_count": events.len(),
3105            "as_of": as_of_recorded,
3106            "current_state": merged_state,
3107            "version": events.len(),
3108        });
3109        if let Some(valid) = as_of_valid {
3110            state["as_of_valid"] = serde_json::json!(valid);
3111        }
3112        if include_history {
3113            state["history"] = serde_json::Value::Array(
3114                events
3115                    .iter()
3116                    .map(|e| {
3117                        serde_json::json!({
3118                            "event_id": e.id,
3119                            "type": e.event_type,
3120                            "timestamp": e.timestamp,
3121                            "payload": e.payload
3122                        })
3123                    })
3124                    .collect(),
3125            );
3126        }
3127
3128        Ok(state)
3129    }
3130
3131    /// Get snapshot from projection (faster than reconstructing)
3132    pub fn get_snapshot(&self, entity_id: &str) -> Result<serde_json::Value> {
3133        let projections = self.projections.read();
3134
3135        if let Some(snapshot_projection) = projections.get_projection("entity_snapshots")
3136            && let Some(state) = snapshot_projection.get_state(entity_id)
3137        {
3138            return Ok(serde_json::json!({
3139                "entity_id": entity_id,
3140                "snapshot": state,
3141                "from_projection": "entity_snapshots"
3142            }));
3143        }
3144
3145        Err(AllSourceError::EntityNotFound(entity_id.to_string()))
3146    }
3147
3148    /// Get statistics about the event store
3149    pub fn stats(&self) -> StoreStats {
3150        let events = self.events.read();
3151        let index_stats = self.index.stats();
3152
3153        StoreStats {
3154            total_events: events.len(),
3155            total_entities: index_stats.total_entities,
3156            total_event_types: index_stats.total_event_types,
3157            total_ingested: *self.total_ingested.read(),
3158        }
3159    }
3160
3161    /// Get all unique streams (entity_ids) in the store
3162    pub fn list_streams(&self) -> Vec<StreamInfo> {
3163        self.index
3164            .get_all_entities()
3165            .into_iter()
3166            .map(|entity_id| {
3167                let event_count = self
3168                    .index
3169                    .get_by_entity(&entity_id)
3170                    .map_or(0, |entries| entries.len());
3171                let last_event_at = self
3172                    .index
3173                    .get_by_entity(&entity_id)
3174                    .and_then(|entries| entries.last().map(|e| e.timestamp));
3175                StreamInfo {
3176                    stream_id: entity_id,
3177                    event_count,
3178                    last_event_at,
3179                    estimated_bytes: None,
3180                    events_last_7d: None,
3181                }
3182            })
3183            .collect()
3184    }
3185
3186    /// Get all unique event types in the store
3187    pub fn list_event_types(&self) -> Vec<EventTypeInfo> {
3188        self.index
3189            .get_all_types()
3190            .into_iter()
3191            .map(|event_type| {
3192                let event_count = self
3193                    .index
3194                    .get_by_type(&event_type)
3195                    .map_or(0, |entries| entries.len());
3196                let last_event_at = self
3197                    .index
3198                    .get_by_type(&event_type)
3199                    .and_then(|entries| entries.last().map(|e| e.timestamp));
3200                EventTypeInfo {
3201                    event_type,
3202                    event_count,
3203                    last_event_at,
3204                }
3205            })
3206            .collect()
3207    }
3208
3209    // Tenant-scoped variants. The entity_index / type_index are GLOBAL (no tenant
3210    // dimension), so `list_streams` / `list_event_types` above span every tenant —
3211    // wrong + a cross-tenant spill on the per-tenant dashboard. These filter by the
3212    // event's tenant_id so the dashboard's "your" streams / event types / totals
3213    // reflect only the caller's tenant.
3214
3215    /// Distinct entities (+ per-entity event count) for ONE tenant.
3216    ///
3217    /// A tenant that cannot be hydrated is `Err`, never zero streams; one
3218    /// evicted between hydration and the end of the read is `complete: false`.
3219    pub fn list_streams_for_tenant(&self, tenant_id: &str) -> Result<StreamSizes> {
3220        self.list_streams_for_tenant_seamed(tenant_id, &mut || {}, &mut || {})
3221    }
3222
3223    fn list_streams_for_tenant_seamed(
3224        &self,
3225        tenant_id: &str,
3226        after_hydrate: &mut dyn FnMut(),
3227        after_read: &mut dyn FnMut(),
3228    ) -> Result<StreamSizes> {
3229        let (streams, complete) = self.read_tenant(tenant_id, after_hydrate, after_read, || {
3230            self.collect_streams_for_tenant(tenant_id)
3231        })?;
3232        Ok(StreamSizes { streams, complete })
3233    }
3234
3235    fn collect_streams_for_tenant(&self, tenant_id: &str) -> Vec<StreamInfo> {
3236        let events = self.events.read();
3237        let mut by_entity: std::collections::HashMap<&str, (usize, chrono::DateTime<chrono::Utc>)> =
3238            std::collections::HashMap::new();
3239        for ev in events.iter() {
3240            if ev.tenant_id_str() != tenant_id {
3241                continue;
3242            }
3243            let e = by_entity
3244                .entry(ev.entity_id_str())
3245                .or_insert((0, ev.timestamp));
3246            e.0 += 1;
3247            if ev.timestamp > e.1 {
3248                e.1 = ev.timestamp;
3249            }
3250        }
3251        by_entity
3252            .into_iter()
3253            .map(|(entity_id, (count, last))| StreamInfo {
3254                stream_id: entity_id.to_string(),
3255                event_count: count,
3256                last_event_at: Some(last),
3257                estimated_bytes: None,
3258                events_last_7d: None,
3259            })
3260            .collect()
3261    }
3262
3263    /// Hydrates `tenant_id`, then runs `read`. The flag is whether the tenant
3264    /// stayed resident and unevicted from before hydration until `read` ended.
3265    fn read_tenant<T>(
3266        &self,
3267        tenant_id: &str,
3268        after_hydrate: &mut dyn FnMut(),
3269        after_read: &mut dyn FnMut(),
3270        read: impl FnOnce() -> T,
3271    ) -> Result<(T, bool)> {
3272        let generation = self.cache_generation(tenant_id);
3273        self.ensure_tenant_loaded(tenant_id)?;
3274        after_hydrate();
3275        let value = read();
3276        after_read();
3277        let resident =
3278            self.is_tenant_loaded(tenant_id) && self.cache_generation(tenant_id) == generation;
3279        Ok((value, resident))
3280    }
3281
3282    /// `read` over a tenant that stayed resident throughout; one retry, then
3283    /// `Err` rather than counts that may miss the tenant's events.
3284    fn read_resident_tenant<T>(&self, tenant_id: &str, mut read: impl FnMut() -> T) -> Result<T> {
3285        for _ in 0..2 {
3286            let (value, resident) =
3287                self.read_tenant(tenant_id, &mut || {}, &mut || {}, &mut read)?;
3288            if resident {
3289                return Ok(value);
3290            }
3291        }
3292        // No tenant id: this text reaches the `tenant read failed` log line.
3293        Err(AllSourceError::StorageError(
3294            "tenant left the cache during every read".to_owned(),
3295        ))
3296    }
3297
3298    /// Every removal from `events` goes through here, so a chunked reader can
3299    /// tell that positions shifted under its cursor.
3300    fn retain_events(&self, events: &mut Vec<Event>, keep: impl FnMut(&Event) -> bool) {
3301        let before = events.len();
3302        events.retain(keep);
3303        if events.len() != before {
3304            self.events_removed
3305                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3306        }
3307    }
3308
3309    /// Every stream of ONE tenant, or of every tenant when `None`, with its heap
3310    /// bytes and last-seven-days count. Unordered.
3311    ///
3312    /// The events lock is held per chunk of `STREAM_SIZE_CHUNK` events, which
3313    /// are sized in place, and released between chunks. Removing events shifts
3314    /// positions under the cursor, so a removal mid-scan restarts the scan once;
3315    /// a second one returns what was counted with `complete: false`.
3316    ///
3317    /// A tenant that cannot be hydrated is `Err`, never zero streams. Each
3318    /// pass hydrates the tenant first and is complete only if the tenant was
3319    /// still resident, and not evicted, when the pass ended.
3320    pub fn stream_sizes(&self, tenant: Option<&str>) -> Result<StreamSizes> {
3321        self.stream_sizes_seamed(
3322            tenant,
3323            &mut ScanSeams {
3324                after_hydrate: &mut || {},
3325                between_chunks: &mut || {},
3326                after_scan: &mut || {},
3327            },
3328        )
3329    }
3330
3331    #[cfg(test)]
3332    fn stream_sizes_between(
3333        &self,
3334        tenant: Option<&str>,
3335        mut between_chunks: impl FnMut(),
3336    ) -> Result<StreamSizes> {
3337        self.stream_sizes_seamed(
3338            tenant,
3339            &mut ScanSeams {
3340                after_hydrate: &mut || {},
3341                between_chunks: &mut between_chunks,
3342                after_scan: &mut || {},
3343            },
3344        )
3345    }
3346
3347    /// `stream_sizes` with `after_hydrate` run once a tenant is hydrated and
3348    /// `after_scan` once its events are counted, on every pass.
3349    #[cfg(test)]
3350    fn stream_sizes_racing(
3351        &self,
3352        tenant: Option<&str>,
3353        mut after_hydrate: impl FnMut(),
3354        mut after_scan: impl FnMut(),
3355    ) -> Result<StreamSizes> {
3356        self.stream_sizes_seamed(
3357            tenant,
3358            &mut ScanSeams {
3359                after_hydrate: &mut after_hydrate,
3360                between_chunks: &mut || {},
3361                after_scan: &mut after_scan,
3362            },
3363        )
3364    }
3365
3366    fn stream_sizes_seamed(
3367        &self,
3368        tenant: Option<&str>,
3369        seams: &mut ScanSeams<'_>,
3370    ) -> Result<StreamSizes> {
3371        let last_week = chrono::Utc::now() - chrono::Duration::days(7);
3372        let (streams, stable) = self.stream_sizes_pass(tenant, last_week, seams, false)?;
3373        if stable {
3374            return Ok(StreamSizes {
3375                streams,
3376                complete: true,
3377            });
3378        }
3379        let (streams, stable) = self.stream_sizes_pass(tenant, last_week, seams, true)?;
3380        Ok(StreamSizes {
3381            streams,
3382            complete: stable,
3383        })
3384    }
3385
3386    fn stream_sizes_pass(
3387        &self,
3388        tenant: Option<&str>,
3389        last_week: chrono::DateTime<chrono::Utc>,
3390        seams: &mut ScanSeams<'_>,
3391        finish_when_moved: bool,
3392    ) -> Result<(Vec<StreamInfo>, bool)> {
3393        let Some(tenant_id) = tenant else {
3394            return Ok(self.scan_stream_sizes(
3395                None,
3396                last_week,
3397                seams.between_chunks,
3398                finish_when_moved,
3399            ));
3400        };
3401        let between_chunks = &mut *seams.between_chunks;
3402        let ((streams, stable), resident) =
3403            self.read_tenant(tenant_id, seams.after_hydrate, seams.after_scan, || {
3404                self.scan_stream_sizes(tenant, last_week, between_chunks, finish_when_moved)
3405            })?;
3406        Ok((streams, stable && resident))
3407    }
3408
3409    /// Bumped by every eviction of `tenant_id`.
3410    fn cache_generation(&self, tenant_id: &str) -> u64 {
3411        self.cache_generations
3412            .get(tenant_id)
3413            .map_or(0, |value| *value)
3414    }
3415
3416    /// One pass of `stream_sizes`. Returns early with `false` when events were
3417    /// removed mid-scan, unless `finish_when_moved`.
3418    ///
3419    /// Nothing allocates while the events lock is held: ids of streams first
3420    /// seen in a chunk are copied into `fresh_ids`, reserved beforehand, and
3421    /// become owned keys after the lock is released. A chunk ends early when
3422    /// an id does not fit or two fresh ids share a hash.
3423    fn scan_stream_sizes(
3424        &self,
3425        tenant: Option<&str>,
3426        last_week: chrono::DateTime<chrono::Utc>,
3427        between_chunks: &mut dyn FnMut(),
3428        finish_when_moved: bool,
3429    ) -> (Vec<StreamInfo>, bool) {
3430        use std::hash::BuildHasher;
3431
3432        #[derive(Default, Clone, Copy)]
3433        struct Totals {
3434            events: usize,
3435            bytes: u64,
3436            last_7d: usize,
3437            last_event_at: Option<chrono::DateTime<chrono::Utc>>,
3438        }
3439        let mut slots: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
3440        let mut totals: Vec<Totals> = Vec::new();
3441        let mut fresh_ids = String::new();
3442        let mut fresh: Vec<std::ops::Range<usize>> = Vec::new();
3443        let mut fresh_by_hash: std::collections::HashMap<u64, usize> =
3444            std::collections::HashMap::new();
3445        let mut id_room = STREAM_ID_BYTES;
3446        let mut removals = None;
3447        let mut stable = true;
3448        let mut cursor = 0;
3449        loop {
3450            // A chunk adds at most STREAM_SIZE_CHUNK streams, so these never
3451            // reallocate under the lock.
3452            totals.reserve(STREAM_SIZE_CHUNK);
3453            fresh.reserve(STREAM_SIZE_CHUNK);
3454            fresh_by_hash.reserve(STREAM_SIZE_CHUNK);
3455            fresh_ids.reserve(id_room);
3456            let base = totals.len();
3457            let events = self.events.read();
3458            let removed = self
3459                .events_removed
3460                .load(std::sync::atomic::Ordering::Relaxed);
3461            if *removals.get_or_insert(removed) != removed || events.len() < cursor {
3462                stable = false;
3463                if !finish_when_moved {
3464                    return (Vec::new(), false);
3465                }
3466                removals = Some(removed);
3467            }
3468            let end = (cursor + STREAM_SIZE_CHUNK).min(events.len());
3469            let start = cursor.min(end);
3470            let mut stop = end;
3471            for (offset, ev) in events[start..end].iter().enumerate() {
3472                if tenant.is_some_and(|t| ev.tenant_id_str() != t) {
3473                    continue;
3474                }
3475                let id = ev.entity_id_str();
3476                let slot = if let Some(&slot) = slots.get(id) {
3477                    slot
3478                } else {
3479                    let hash = slots.hasher().hash_one(id);
3480                    match fresh_by_hash.get(&hash) {
3481                        Some(&index) if &fresh_ids[fresh[index].clone()] == id => base + index,
3482                        Some(_) => {
3483                            stop = start + offset;
3484                            break;
3485                        }
3486                        None if fresh_ids.capacity() - fresh_ids.len() < id.len() => {
3487                            id_room = id_room.max(id.len());
3488                            stop = start + offset;
3489                            break;
3490                        }
3491                        None => {
3492                            let at = fresh_ids.len();
3493                            fresh_ids.push_str(id);
3494                            fresh_by_hash.insert(hash, fresh.len());
3495                            fresh.push(at..fresh_ids.len());
3496                            totals.push(Totals::default());
3497                            totals.len() - 1
3498                        }
3499                    }
3500                };
3501                let stream = &mut totals[slot];
3502                stream.events += 1;
3503                stream.bytes += ev.resident_header_bytes()
3504                    + (value_heap_bytes(&ev.payload)
3505                        + ev.metadata.as_ref().map_or(0, value_heap_bytes))
3506                        as u64;
3507                if ev.timestamp >= last_week {
3508                    stream.last_7d += 1;
3509                }
3510                if stream.last_event_at.is_none_or(|last| ev.timestamp > last) {
3511                    stream.last_event_at = Some(ev.timestamp);
3512                }
3513            }
3514            let done = stop >= events.len();
3515            drop(events);
3516            for (index, range) in fresh.drain(..).enumerate() {
3517                slots.insert(fresh_ids[range].to_owned(), base + index);
3518            }
3519            fresh_ids.clear();
3520            fresh_by_hash.clear();
3521            cursor = stop;
3522            if done {
3523                break;
3524            }
3525            between_chunks();
3526        }
3527        let streams = slots
3528            .into_iter()
3529            .map(|(stream_id, slot)| (stream_id, totals[slot]))
3530            .map(|(stream_id, totals)| StreamInfo {
3531                stream_id,
3532                event_count: totals.events,
3533                last_event_at: totals.last_event_at,
3534                estimated_bytes: Some(totals.bytes),
3535                events_last_7d: Some(totals.last_7d),
3536            })
3537            .collect();
3538        (streams, stable)
3539    }
3540
3541    /// `stream_sizes` ordered by `sort` and cut to `limit`.
3542    pub fn list_streams_with_bytes(
3543        &self,
3544        tenant: Option<&str>,
3545        sort: StreamSort,
3546        limit: usize,
3547    ) -> Result<StreamSizes> {
3548        let mut sizes = self.stream_sizes(tenant)?;
3549        sort_streams(&mut sizes.streams, sort);
3550        sizes.streams.truncate(limit);
3551        Ok(sizes)
3552    }
3553
3554    /// Distinct event types (+ per-type event count) for ONE tenant. `Err`
3555    /// when the tenant cannot be hydrated or keeps leaving the cache.
3556    pub fn list_event_types_for_tenant(&self, tenant_id: &str) -> Result<Vec<EventTypeInfo>> {
3557        self.read_resident_tenant(tenant_id, || self.collect_event_types_for_tenant(tenant_id))
3558    }
3559
3560    fn collect_event_types_for_tenant(&self, tenant_id: &str) -> Vec<EventTypeInfo> {
3561        let events = self.events.read();
3562        let mut by_type: std::collections::HashMap<&str, (usize, chrono::DateTime<chrono::Utc>)> =
3563            std::collections::HashMap::new();
3564        for ev in events.iter() {
3565            if ev.tenant_id_str() != tenant_id {
3566                continue;
3567            }
3568            let e = by_type
3569                .entry(ev.event_type_str())
3570                .or_insert((0, ev.timestamp));
3571            e.0 += 1;
3572            if ev.timestamp > e.1 {
3573                e.1 = ev.timestamp;
3574            }
3575        }
3576        by_type
3577            .into_iter()
3578            .map(|(event_type, (count, last))| EventTypeInfo {
3579                event_type: event_type.to_string(),
3580                event_count: count,
3581                last_event_at: Some(last),
3582            })
3583            .collect()
3584    }
3585
3586    /// Event-store statistics for ONE tenant.
3587    ///
3588    /// `stats()` above is global (`events.len()` + the global index), so it must
3589    /// never be served to a tenant — it would leak whole-fleet totals. This is
3590    /// the scoped equivalent the gateway exposes as `GET /api/v1/stats` with an
3591    /// auth-derived `tenant_id` (#230).
3592    ///
3593    /// Returns the same four counters as `StoreStats`, plus the per-type census
3594    /// and time range that callers otherwise reconstruct by paging events.
3595    /// `Err` when the tenant cannot be hydrated or keeps leaving the cache,
3596    /// never zero counts.
3597    pub fn stats_for_tenant(&self, tenant_id: &str) -> Result<TenantStoreStats> {
3598        self.read_resident_tenant(tenant_id, || self.collect_stats_for_tenant(tenant_id))
3599    }
3600
3601    fn collect_stats_for_tenant(&self, tenant_id: &str) -> TenantStoreStats {
3602        let events = self.events.read();
3603
3604        let mut entities: std::collections::HashSet<&str> = std::collections::HashSet::new();
3605        let mut census: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
3606        let mut total_events = 0usize;
3607        let mut oldest: Option<chrono::DateTime<chrono::Utc>> = None;
3608        let mut newest: Option<chrono::DateTime<chrono::Utc>> = None;
3609
3610        for ev in events.iter() {
3611            if ev.tenant_id_str() != tenant_id {
3612                continue;
3613            }
3614
3615            total_events += 1;
3616            entities.insert(ev.entity_id_str());
3617            *census.entry(ev.event_type_str()).or_insert(0) += 1;
3618
3619            let ts = ev.timestamp;
3620            if oldest.is_none_or(|o| ts < o) {
3621                oldest = Some(ts);
3622            }
3623            if newest.is_none_or(|n| ts > n) {
3624                newest = Some(ts);
3625            }
3626        }
3627
3628        TenantStoreStats {
3629            total_events,
3630            total_entities: entities.len(),
3631            total_event_types: census.len(),
3632            // Scoped equivalent of `total_ingested`: that counter is a global
3633            // process-lifetime tally with no tenant dimension, so reporting it
3634            // here would leak. The tenant's own total is the honest answer.
3635            total_ingested: total_events as u64,
3636            event_types: census
3637                .into_iter()
3638                .map(|(k, v)| (k.to_string(), v))
3639                .collect(),
3640            oldest_event: oldest,
3641            newest_event: newest,
3642        }
3643    }
3644
3645    /// Reconstruct entity state for ONE tenant, folding only that tenant's
3646    /// events (#230).
3647    pub fn reconstruct_state_for_tenant(
3648        &self,
3649        entity_id: &str,
3650        as_of: Option<DateTime<Utc>>,
3651        tenant_id: &str,
3652    ) -> Result<serde_json::Value> {
3653        self.entity_state(entity_id, as_of, Some(tenant_id), true)
3654    }
3655
3656    /// Attach a broadcast sender to the WAL for replication.
3657    ///
3658    /// Thread-safe: can be called through `Arc<EventStore>` at runtime.
3659    /// Used during initial setup and during follower → leader promotion.
3660    /// When set, every WAL append publishes the entry to the broadcast
3661    /// channel so the WAL shipper can stream it to followers.
3662    pub fn enable_wal_replication(
3663        &self,
3664        tx: tokio::sync::broadcast::Sender<crate::infrastructure::persistence::wal::WALEntry>,
3665    ) {
3666        if let Some(ref wal_arc) = self.wal {
3667            wal_arc.set_replication_tx(tx);
3668            tracing::info!("WAL replication broadcast enabled");
3669        } else {
3670            tracing::warn!("Cannot enable WAL replication: WAL is not configured");
3671        }
3672    }
3673
3674    /// Get a reference to the WAL (if configured).
3675    /// Used by the replication catch-up protocol to determine oldest available offset.
3676    pub fn wal(&self) -> Option<&Arc<WriteAheadLog>> {
3677        self.wal.as_ref()
3678    }
3679
3680    /// Get a reference to the Parquet storage (if configured).
3681    /// Used by the replication catch-up protocol to stream snapshot files to followers.
3682    pub fn parquet_storage(&self) -> Option<&Arc<RwLock<ParquetStorage>>> {
3683        self.storage.as_ref()
3684    }
3685}
3686
3687/// Configuration for EventStore
3688#[derive(Debug, Clone, Default)]
3689pub struct EventStoreConfig {
3690    /// Limits for cold integrity-sensitive loads. Generic queries retain their
3691    /// existing policy. Configured by the embedding service, never by callers.
3692    pub strict_archive_limits: ArchiveReadLimits,
3693    /// Optional service-owned HTTP cache warmup deadline. It reuses strict
3694    /// input caps and may outlive its caller, but cannot complete a cancelled
3695    /// operation. Embedded stores default off; server config enables 30 seconds.
3696    pub http_archive_warmup_timeout: Option<std::time::Duration>,
3697    /// Optional directory for persistent Parquet storage (v0.2 feature)
3698    pub storage_dir: Option<PathBuf>,
3699
3700    /// Optional directory for WAL (Write-Ahead Log) (v0.2 feature)
3701    pub wal_dir: Option<PathBuf>,
3702
3703    /// WAL configuration (v0.2 feature)
3704    pub wal_config: WALConfig,
3705
3706    /// Compaction configuration (v0.2 feature)
3707    pub compaction_config: CompactionConfig,
3708
3709    /// Schema registry configuration (v0.5 feature)
3710    pub schema_registry_config: SchemaRegistryConfig,
3711
3712    /// Optional directory for system metadata storage (dogfood feature).
3713    /// When set, operational metadata (tenants, config, audit) is stored
3714    /// using AllSource's own event store rather than an external database.
3715    /// Defaults to `{storage_dir}/__system/` when storage_dir is set.
3716    pub system_data_dir: Option<PathBuf>,
3717
3718    /// Name of the default tenant to auto-create on first boot.
3719    pub bootstrap_tenant: Option<String>,
3720
3721    /// In-memory cache budget in bytes (Step 3). When the resident
3722    /// total exceeds this after a load, the LRU tenant is evicted
3723    /// until the cache fits. `None` (the default in tests) disables
3724    /// the budget — every loaded tenant stays resident. Production
3725    /// reads this from the `ALLSOURCE_CACHE_BYTES` env var; see
3726    /// `from_env`.
3727    pub cache_byte_budget: Option<u64>,
3728
3729    /// Cadence of the runtime checkpoint loop, in seconds (Step 6).
3730    /// Each tick flushes pending Parquet batches and, on success,
3731    /// truncates the WAL up through the checkpoint. This bounds
3732    /// dirty-restart replay time to one interval of writes
3733    /// regardless of total dataset size.
3734    ///
3735    /// `None` disables the loop — the WAL still grows but is only
3736    /// truncated at boot, which is the pre-Step-6 behavior. Tests
3737    /// default to `None`; production reads
3738    /// `ALLSOURCE_CHECKPOINT_INTERVAL_SECONDS` (default 60s) via
3739    /// `from_env_vars`.
3740    pub checkpoint_interval_secs: Option<u64>,
3741
3742    /// Open the store read-only (replica mode). See `EventStore::read_only`.
3743    /// Defaults to `false` (read-write owner). Set by Prime when it fails to
3744    /// acquire the exclusive data-dir lock because another process owns it.
3745    pub read_only: bool,
3746
3747    /// Flush file stem for Parquet storage. `None` keeps the default name.
3748    pub parquet_file_namer: Option<FileNamer>,
3749
3750    /// Register the `entity_snapshots` projection. Defaults to `false`, so
3751    /// server stores do not hold its state; embedded configs set it.
3752    pub register_entity_snapshots: bool,
3753}
3754
3755impl EventStoreConfig {
3756    /// Create config with persistent storage enabled
3757    pub fn with_persistence(storage_dir: impl Into<PathBuf>) -> Self {
3758        Self {
3759            storage_dir: Some(storage_dir.into()),
3760            ..Self::default()
3761        }
3762    }
3763
3764    /// Create config with WAL enabled
3765    pub fn with_wal(wal_dir: impl Into<PathBuf>, wal_config: WALConfig) -> Self {
3766        Self {
3767            wal_dir: Some(wal_dir.into()),
3768            wal_config,
3769            ..Self::default()
3770        }
3771    }
3772
3773    /// Create production config with all features enabled
3774    pub fn production(
3775        storage_dir: impl Into<PathBuf>,
3776        wal_dir: impl Into<PathBuf>,
3777        wal_config: WALConfig,
3778        compaction_config: CompactionConfig,
3779    ) -> Self {
3780        let storage_dir = storage_dir.into();
3781        let system_data_dir = storage_dir.join("__system");
3782        Self {
3783            storage_dir: Some(storage_dir),
3784            wal_dir: Some(wal_dir.into()),
3785            wal_config,
3786            compaction_config,
3787            system_data_dir: Some(system_data_dir),
3788            ..Self::default()
3789        }
3790    }
3791
3792    /// Resolve the effective system data directory.
3793    ///
3794    /// If explicitly set, returns that. Otherwise, derives from storage_dir.
3795    /// Returns None if neither is configured (in-memory mode).
3796    pub fn effective_system_data_dir(&self) -> Option<PathBuf> {
3797        self.system_data_dir
3798            .clone()
3799            .or_else(|| self.storage_dir.as_ref().map(|d| d.join("__system")))
3800    }
3801
3802    /// Build config from environment variables.
3803    ///
3804    /// Reads `ALLSOURCE_DATA_DIR`, `ALLSOURCE_STORAGE_DIR`, `ALLSOURCE_WAL_DIR`,
3805    /// and `ALLSOURCE_WAL_ENABLED` to determine persistence mode.
3806    ///
3807    /// Returns `(config, description)` where description is a human-readable
3808    /// summary of the persistence mode for logging.
3809    pub fn from_env() -> (Self, &'static str) {
3810        let (config, mode) = Self::from_env_vars(
3811            std::env::var("ALLSOURCE_DATA_DIR")
3812                .ok()
3813                .filter(|s| !s.is_empty()),
3814            std::env::var("ALLSOURCE_STORAGE_DIR")
3815                .ok()
3816                .filter(|s| !s.is_empty()),
3817            std::env::var("ALLSOURCE_WAL_DIR")
3818                .ok()
3819                .filter(|s| !s.is_empty()),
3820            std::env::var("ALLSOURCE_WAL_ENABLED").ok(),
3821            std::env::var("ALLSOURCE_CACHE_BYTES").ok(),
3822            std::env::var("ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS").ok(),
3823            std::env::var("ALLSOURCE_RETENTION_SYSTEM_DAYS").ok(),
3824            std::env::var("ALLSOURCE_CHECKPOINT_INTERVAL_SECONDS").ok(),
3825        );
3826        let config = config.with_strict_archive_overrides(
3827            std::env::var("ALLSOURCE_STRICT_ARCHIVE_MAX_DECODED_BYTES").ok(),
3828            std::env::var("ALLSOURCE_STRICT_ARCHIVE_TIMEOUT_SECONDS").ok(),
3829        );
3830        (config, mode)
3831    }
3832
3833    /// Strict whole-tenant reads (the event feed and read models) refuse a
3834    /// tenant whose decoded archive exceeds `max_uncompressed_bytes`, so its
3835    /// feed and read models fail on every request. The default was measured
3836    /// on a 4 GiB machine; a larger machine raises it here. Unparseable or
3837    /// zero values keep the default.
3838    pub fn with_strict_archive_overrides(
3839        mut self,
3840        max_decoded_bytes: Option<String>,
3841        timeout_seconds: Option<String>,
3842    ) -> Self {
3843        if let Some(bytes) = positive_override(
3844            "ALLSOURCE_STRICT_ARCHIVE_MAX_DECODED_BYTES",
3845            max_decoded_bytes,
3846        ) {
3847            self.strict_archive_limits.max_uncompressed_bytes = bytes;
3848        }
3849        if let Some(seconds) =
3850            positive_override("ALLSOURCE_STRICT_ARCHIVE_TIMEOUT_SECONDS", timeout_seconds)
3851        {
3852            self.strict_archive_limits.timeout = std::time::Duration::from_secs(seconds);
3853        }
3854        tracing::info!(
3855            max_decoded_bytes = self.strict_archive_limits.max_uncompressed_bytes,
3856            timeout_seconds = self.strict_archive_limits.timeout.as_secs(),
3857            "strict archive read limits"
3858        );
3859        self
3860    }
3861
3862    /// Build config from explicit env-var values (testable without mutating process env).
3863    pub fn from_env_vars(
3864        data_dir: Option<String>,
3865        explicit_storage_dir: Option<String>,
3866        explicit_wal_dir: Option<String>,
3867        wal_enabled_var: Option<String>,
3868        cache_bytes_var: Option<String>,
3869        snapshot_interval_var: Option<String>,
3870        retention_system_days_var: Option<String>,
3871        checkpoint_interval_var: Option<String>,
3872    ) -> (Self, &'static str) {
3873        let data_dir = data_dir.filter(|s| !s.is_empty());
3874        let storage_dir = explicit_storage_dir
3875            .filter(|s| !s.is_empty())
3876            .or_else(|| data_dir.as_ref().map(|d| format!("{d}/storage")));
3877        let wal_dir = explicit_wal_dir
3878            .filter(|s| !s.is_empty())
3879            .or_else(|| data_dir.as_ref().map(|d| format!("{d}/wal")));
3880        let wal_enabled = wal_enabled_var.is_none_or(|v| v == "true");
3881        let cache_byte_budget = parse_cache_byte_budget(cache_bytes_var);
3882        let compaction_config =
3883            CompactionConfig::from_env_vars(snapshot_interval_var, retention_system_days_var);
3884
3885        // ALLSOURCE_CHECKPOINT_INTERVAL_SECONDS: parse decimal seconds. The
3886        // default (60s) only applies when WAL is enabled — there's no
3887        // checkpoint loop to run otherwise. Unparseable input is logged
3888        // and falls back to the default rather than failing boot.
3889        let checkpoint_interval_secs = if wal_enabled {
3890            checkpoint_interval_var
3891                .filter(|s| !s.is_empty())
3892                .map(|s| match s.parse::<u64>() {
3893                    Ok(v) => v,
3894                    Err(e) => {
3895                        tracing::warn!(
3896                            "ALLSOURCE_CHECKPOINT_INTERVAL_SECONDS={s:?} could not be parsed as \
3897                             u64: {e}; falling back to default 60s"
3898                        );
3899                        60
3900                    }
3901                })
3902                .or(Some(60))
3903        } else {
3904            None
3905        };
3906
3907        let mut config = match (&storage_dir, &wal_dir) {
3908            (Some(sd), Some(wd)) if wal_enabled => {
3909                Self::production(sd, wd, WALConfig::default(), compaction_config)
3910            }
3911            (Some(sd), _) => Self::with_persistence(sd),
3912            (_, Some(wd)) if wal_enabled => Self::with_wal(wd, WALConfig::default()),
3913            _ => Self::default(),
3914        };
3915        config.cache_byte_budget = cache_byte_budget;
3916        config.checkpoint_interval_secs = checkpoint_interval_secs;
3917        config.http_archive_warmup_timeout = storage_dir
3918            .as_ref()
3919            .map(|_| std::time::Duration::from_secs(30));
3920
3921        let mode = match (&storage_dir, &wal_dir) {
3922            (Some(_), Some(_)) if wal_enabled => "wal+parquet",
3923            (Some(_), _) => "parquet-only",
3924            (_, Some(_)) if wal_enabled => "wal-only",
3925            _ => "in-memory",
3926        };
3927        (config, mode)
3928    }
3929}
3930
3931/// ALLSOURCE_CACHE_BYTES: decimal bytes. Unparseable input is logged and
3932/// ignored rather than failing boot; the unbounded fallback is safe (worst case
3933/// is the original pre-Step-3 behavior). Part of the eviction policy: its
3934/// digest is frozen by `eviction_policy_unchanged`.
3935fn parse_cache_byte_budget(cache_bytes_var: Option<String>) -> Option<u64> {
3936    cache_bytes_var
3937        .filter(|s| !s.is_empty())
3938        .and_then(|s| match s.parse::<u64>() {
3939            Ok(v) => Some(v),
3940            Err(e) => {
3941                tracing::warn!(
3942                    "ALLSOURCE_CACHE_BYTES={s:?} could not be parsed as u64: {e}; \
3943                     cache budget disabled"
3944                );
3945                None
3946            }
3947        })
3948}
3949
3950fn positive_override(name: &str, value: Option<String>) -> Option<u64> {
3951    let value = value.filter(|s| !s.is_empty())?;
3952    match value.parse::<u64>() {
3953        Ok(parsed) if parsed > 0 => Some(parsed),
3954        _ => {
3955            tracing::warn!("{name}={value:?} is not a positive integer; keeping the default");
3956            None
3957        }
3958    }
3959}
3960
3961#[derive(Debug, serde::Serialize)]
3962pub struct StoreStats {
3963    pub total_events: usize,
3964    pub total_entities: usize,
3965    pub total_event_types: usize,
3966    pub total_ingested: u64,
3967}
3968
3969/// Tenant-scoped event-store statistics (#230).
3970///
3971/// Mirrors `StoreStats`' counters so existing consumers keep working, and adds
3972/// the per-type census and time range that clients previously derived by paging
3973/// the whole event stream.
3974#[derive(Debug, Clone, serde::Serialize)]
3975pub struct TenantStoreStats {
3976    pub total_events: usize,
3977    pub total_entities: usize,
3978    pub total_event_types: usize,
3979    pub total_ingested: u64,
3980    /// event_type -> count, for this tenant only.
3981    pub event_types: std::collections::HashMap<String, usize>,
3982    pub oldest_event: Option<chrono::DateTime<chrono::Utc>>,
3983    pub newest_event: Option<chrono::DateTime<chrono::Utc>>,
3984}
3985
3986/// Information about a stream (entity_id)
3987#[derive(Debug, Clone, serde::Serialize)]
3988pub struct StreamInfo {
3989    /// The stream identifier (entity_id)
3990    pub stream_id: String,
3991    /// Total number of events in this stream
3992    pub event_count: usize,
3993    /// Timestamp of the last event in this stream
3994    pub last_event_at: Option<chrono::DateTime<chrono::Utc>>,
3995    /// Heap bytes held for this stream. Set only by `list_streams_with_bytes`.
3996    #[serde(skip_serializing_if = "Option::is_none")]
3997    pub estimated_bytes: Option<u64>,
3998    /// Events in this stream from the last seven days. Set only by `list_streams_with_bytes`.
3999    #[serde(skip_serializing_if = "Option::is_none")]
4000    pub events_last_7d: Option<usize>,
4001}
4002
4003/// Ordering for `list_streams_with_bytes`; ties break on `stream_id`.
4004#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Deserialize)]
4005#[serde(rename_all = "lowercase")]
4006pub enum StreamSort {
4007    #[default]
4008    Events,
4009    Bytes,
4010}
4011
4012/// Events sized per events-lock hold in `EventStore::stream_sizes`.
4013const STREAM_SIZE_CHUNK: usize = 4096;
4014/// Bytes of new stream ids one chunk may copy before it ends early.
4015const STREAM_ID_BYTES: usize = 64 * 1024;
4016
4017/// Points where a test interleaves work with a `stream_sizes` pass.
4018struct ScanSeams<'a> {
4019    after_hydrate: &'a mut dyn FnMut(),
4020    between_chunks: &'a mut dyn FnMut(),
4021    after_scan: &'a mut dyn FnMut(),
4022}
4023
4024/// What `EventStore::stream_sizes` or `list_streams_for_tenant` counted.
4025#[derive(Debug, Clone, Default, serde::Serialize)]
4026pub struct StreamSizes {
4027    pub streams: Vec<StreamInfo>,
4028    /// `false` when events were removed during the scan and its retry, or
4029    /// the tenant was evicted between its hydration and the end of the read,
4030    /// so an event can be skipped or counted twice.
4031    pub complete: bool,
4032}
4033
4034fn stream_order(sort: StreamSort, a: &StreamInfo, b: &StreamInfo) -> std::cmp::Ordering {
4035    let by_key = match sort {
4036        StreamSort::Events => b.event_count.cmp(&a.event_count),
4037        StreamSort::Bytes => b.estimated_bytes.cmp(&a.estimated_bytes),
4038    };
4039    by_key.then_with(|| a.stream_id.cmp(&b.stream_id))
4040}
4041
4042/// Orders streams by `sort`, largest first; ties break on `stream_id`.
4043pub fn sort_streams(streams: &mut [StreamInfo], sort: StreamSort) {
4044    streams.sort_by(|a, b| stream_order(sort, a, b));
4045}
4046
4047/// The `limit` streams after `offset` in [`sort_streams`] order. Selects the
4048/// page without sorting or cloning the rest, so its cost tracks the page.
4049pub fn page_streams(
4050    streams: &[StreamInfo],
4051    sort: StreamSort,
4052    offset: usize,
4053    limit: usize,
4054) -> Vec<StreamInfo> {
4055    let end = offset.saturating_add(limit).min(streams.len());
4056    if offset >= end {
4057        return Vec::new();
4058    }
4059    let mut ranked: Vec<&StreamInfo> = streams.iter().collect();
4060    if end < ranked.len() {
4061        ranked.select_nth_unstable_by(end - 1, |a, b| stream_order(sort, a, b));
4062        ranked.truncate(end);
4063    }
4064    ranked.sort_unstable_by(|a, b| stream_order(sort, a, b));
4065    ranked[offset..].iter().map(|&info| info.clone()).collect()
4066}
4067
4068/// Information about an event type
4069#[derive(Debug, Clone, serde::Serialize)]
4070pub struct EventTypeInfo {
4071    /// The event type name
4072    pub event_type: String,
4073    /// Total number of events of this type
4074    pub event_count: usize,
4075    /// Timestamp of the last event of this type
4076    pub last_event_at: Option<chrono::DateTime<chrono::Utc>>,
4077}
4078
4079impl Default for EventStore {
4080    fn default() -> Self {
4081        Self::new()
4082    }
4083}
4084
4085#[path = "store_strict_read.rs"]
4086mod strict_read;
4087
4088#[path = "store_prefix_read.rs"]
4089mod prefix_read;
4090
4091#[path = "store_refresh.rs"]
4092mod refresh;
4093
4094#[path = "store_resident.rs"]
4095mod resident;
4096pub use refresh::RefreshReport;
4097
4098#[cfg(all(test, feature = "server"))]
4099#[path = "store_archive_work_tests.rs"]
4100mod archive_work_tests;
4101
4102#[cfg(test)]
4103#[path = "store_archive_consistency_tests.rs"]
4104mod archive_consistency_tests;
4105
4106#[cfg(test)]
4107#[path = "store_version_index_reuse_tests.rs"]
4108mod version_index_reuse_tests;
4109
4110#[cfg(test)]
4111#[path = "store_tie_break_tests.rs"]
4112mod tie_break_tests;
4113
4114#[cfg(test)]
4115#[path = "store_stream_sizes_tests.rs"]
4116mod stream_sizes_tests;
4117
4118#[cfg(test)]
4119mod tests {
4120    use super::*;
4121    use crate::domain::entities::Event;
4122    use tempfile::TempDir;
4123
4124    /// Recursively walk `dir` looking for `*.parquet` files.
4125    /// Tests that pre-date Step 1's tenant-partitioned layout used a
4126    /// flat `read_dir` here; after the move to <root>/<tenant>/<yyyy-mm>/
4127    /// they need to walk subdirectories.
4128    fn find_parquet_files(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
4129        let mut out = Vec::new();
4130        let mut stack = vec![dir.to_path_buf()];
4131        while let Some(d) = stack.pop() {
4132            let Ok(entries) = std::fs::read_dir(&d) else {
4133                continue;
4134            };
4135            for e in entries.flatten() {
4136                let p = e.path();
4137                if p.is_dir() {
4138                    stack.push(p);
4139                } else if p.extension().and_then(|s| s.to_str()) == Some("parquet") {
4140                    out.push(p);
4141                }
4142            }
4143        }
4144        out
4145    }
4146
4147    fn create_test_event(entity_id: &str, event_type: &str) -> Event {
4148        Event::from_strings(
4149            event_type.to_string(),
4150            entity_id.to_string(),
4151            "default".to_string(),
4152            serde_json::json!({"name": "Test", "value": 42}),
4153            None,
4154        )
4155        .unwrap()
4156    }
4157
4158    fn create_test_event_with_payload(
4159        entity_id: &str,
4160        event_type: &str,
4161        payload: serde_json::Value,
4162    ) -> Event {
4163        Event::from_strings(
4164            event_type.to_string(),
4165            entity_id.to_string(),
4166            "default".to_string(),
4167            payload,
4168            None,
4169        )
4170        .unwrap()
4171    }
4172
4173    #[test]
4174    fn test_event_store_new() {
4175        let store = EventStore::new();
4176        assert_eq!(store.stats().total_events, 0);
4177        assert_eq!(store.stats().total_entities, 0);
4178    }
4179
4180    // -----------------------------------------------------------------
4181    // Step 2: ensure_tenant_loaded smoke tests. The full
4182    // cold-boot/lazy-hydrate paths land in commit #2 (skip boot
4183    // load) and commit #4 (integration test).
4184    // -----------------------------------------------------------------
4185
4186    #[test]
4187    fn test_ensure_tenant_loaded_no_storage_is_a_noop() {
4188        // An in-memory-only store (no ParquetStorage configured) has
4189        // nothing to hydrate. The method must succeed and mark the
4190        // tenant loaded so subsequent calls hit the fast path.
4191        let store = EventStore::new();
4192        assert!(!store.is_tenant_loaded("alice"));
4193        store.ensure_tenant_loaded("alice").unwrap();
4194        assert!(store.is_tenant_loaded("alice"));
4195        // Other tenants stay cold — the call is per-tenant.
4196        assert!(!store.is_tenant_loaded("bob"));
4197    }
4198
4199    #[test]
4200    fn test_ensure_tenant_loaded_warm_path_is_idempotent() {
4201        let store = EventStore::new();
4202        store.ensure_tenant_loaded("alice").unwrap();
4203        // Second call hits the DashMap fast path and returns Ok.
4204        store.ensure_tenant_loaded("alice").unwrap();
4205    }
4206
4207    #[test]
4208    fn test_ensure_tenant_loaded_rejects_unsafe_tenant_id() {
4209        // With persistence configured, the call has to walk a
4210        // tenant subtree, so the path-safety whitelist applies.
4211        // The error must propagate; the tenant must NOT be marked
4212        // loaded (otherwise an attacker probing path-traversal
4213        // strings could spam the loaded-set with junk).
4214        let temp_dir = TempDir::new().unwrap();
4215        let store = EventStore::with_config(EventStoreConfig::with_persistence(temp_dir.path()));
4216        for unsafe_tid in ["..", "a/b", "a\\b", ""] {
4217            let result = store.ensure_tenant_loaded(unsafe_tid);
4218            assert!(
4219                result.is_err(),
4220                "tenant_id {unsafe_tid:?} should have been rejected"
4221            );
4222            assert!(
4223                !store.is_tenant_loaded(unsafe_tid),
4224                "rejected tenant {unsafe_tid:?} must not be marked loaded"
4225            );
4226        }
4227    }
4228
4229    #[test]
4230    fn test_ensure_tenant_loaded_no_subtree_marks_loaded_with_zero_events() {
4231        // A tenant that has no on-disk data (fresh tenant, never
4232        // persisted) must still succeed — load_events_for_tenant
4233        // returns empty, ensure_tenant_loaded marks it loaded so we
4234        // don't re-walk the empty subtree on every query.
4235        let temp_dir = TempDir::new().unwrap();
4236        let store = EventStore::with_config(EventStoreConfig::with_persistence(temp_dir.path()));
4237        assert!(!store.is_tenant_loaded("never-existed"));
4238        store.ensure_tenant_loaded("never-existed").unwrap();
4239        assert!(store.is_tenant_loaded("never-existed"));
4240    }
4241
4242    #[test]
4243    fn test_evict_tenant_drops_events_and_resets_bytes() {
4244        // After eviction, the tenant's events are gone from memory,
4245        // its byte counter is reset, and is_tenant_loaded returns
4246        // false. Other tenants are untouched.
4247        let temp_dir = TempDir::new().unwrap();
4248        let storage_dir = temp_dir.path().to_path_buf();
4249
4250        {
4251            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4252            for i in 0..3 {
4253                store
4254                    .ingest(
4255                        &Event::from_strings(
4256                            "test.event".to_string(),
4257                            format!("a-{i}"),
4258                            "alice".to_string(),
4259                            serde_json::json!({"i": i}),
4260                            None,
4261                        )
4262                        .unwrap(),
4263                    )
4264                    .unwrap();
4265            }
4266            for i in 0..2 {
4267                store
4268                    .ingest(
4269                        &Event::from_strings(
4270                            "test.event".to_string(),
4271                            format!("b-{i}"),
4272                            "bob".to_string(),
4273                            serde_json::json!({"i": i}),
4274                            None,
4275                        )
4276                        .unwrap(),
4277                    )
4278                    .unwrap();
4279            }
4280            store.flush_storage().unwrap();
4281        }
4282
4283        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4284        store.ensure_tenant_loaded("alice").unwrap();
4285        store.ensure_tenant_loaded("bob").unwrap();
4286        assert_eq!(store.stats().total_events, 5);
4287        let alice_bytes = store.tenant_resident_bytes("alice");
4288        let bob_bytes = store.tenant_resident_bytes("bob");
4289        assert!(alice_bytes > 0 && bob_bytes > 0);
4290
4291        store.evict_tenant("alice");
4292
4293        assert!(!store.is_tenant_loaded("alice"));
4294        assert!(store.is_tenant_loaded("bob"));
4295        assert_eq!(store.tenant_resident_bytes("alice"), 0);
4296        assert_eq!(store.tenant_resident_bytes("bob"), bob_bytes);
4297        assert_eq!(store.stats().total_events, 2, "only bob's 2 events remain");
4298    }
4299
4300    #[test]
4301    fn test_evict_tenant_then_query_re_loads_from_disk() {
4302        // The transparent re-load behavior the bead's AC #5 calls
4303        // out: evict, then query the same tenant — its data comes
4304        // back via ensure_tenant_loaded, sourced from Parquet.
4305        let temp_dir = TempDir::new().unwrap();
4306        let storage_dir = temp_dir.path().to_path_buf();
4307
4308        {
4309            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4310            for i in 0..4 {
4311                store
4312                    .ingest(
4313                        &Event::from_strings(
4314                            "test.event".to_string(),
4315                            format!("a-{i}"),
4316                            "alice".to_string(),
4317                            serde_json::json!({"i": i}),
4318                            None,
4319                        )
4320                        .unwrap(),
4321                    )
4322                    .unwrap();
4323            }
4324            store.flush_storage().unwrap();
4325        }
4326
4327        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4328        store.ensure_tenant_loaded("alice").unwrap();
4329        store.evict_tenant("alice");
4330        assert_eq!(store.stats().total_events, 0);
4331
4332        // Query — re-load happens transparently.
4333        let results = store
4334            .query(&QueryEventsRequest {
4335                as_of_valid: None,
4336                since_valid: None,
4337                until_valid: None,
4338                entity_id: None,
4339                event_type: None,
4340                tenant_id: Some("alice".to_string()),
4341                as_of: None,
4342                since: None,
4343                until: None,
4344                limit: None,
4345                event_type_prefix: None,
4346                exclude_event_type_prefix: None,
4347                payload_filter: None,
4348            })
4349            .unwrap();
4350        assert_eq!(results.len(), 4);
4351        assert!(store.is_tenant_loaded("alice"));
4352    }
4353
4354    #[test]
4355    fn test_evict_tenant_rebuilds_index_with_new_offsets() {
4356        // After eviction, the events Vec is compacted. The index
4357        // must be rebuilt against the new offsets — otherwise
4358        // queries return stale or wrong events. This test checks
4359        // index correctness end-to-end via a query for the
4360        // surviving tenant after the evicted tenant's events are
4361        // gone.
4362        let temp_dir = TempDir::new().unwrap();
4363        let store = EventStore::with_config(EventStoreConfig::with_persistence(temp_dir.path()));
4364
4365        // Interleave: alice, bob, alice, bob, alice. After
4366        // evicting alice, the events Vec compacts to [bob, bob]
4367        // and the index must reflect the new layout.
4368        for i in 0..3 {
4369            store
4370                .ingest(
4371                    &Event::from_strings(
4372                        "test.event".to_string(),
4373                        format!("a-{i}"),
4374                        "alice".to_string(),
4375                        serde_json::json!({"i": i}),
4376                        None,
4377                    )
4378                    .unwrap(),
4379                )
4380                .unwrap();
4381            if i < 2 {
4382                store
4383                    .ingest(
4384                        &Event::from_strings(
4385                            "test.event".to_string(),
4386                            format!("b-{i}"),
4387                            "bob".to_string(),
4388                            serde_json::json!({"i": i}),
4389                            None,
4390                        )
4391                        .unwrap(),
4392                    )
4393                    .unwrap();
4394            }
4395        }
4396        // Mark both as loaded for accurate eviction bookkeeping.
4397        store.tenant_loader.mark_loaded("alice");
4398        store.tenant_loader.mark_loaded("bob");
4399
4400        store.evict_tenant("alice");
4401
4402        let bob_results = store
4403            .query(&QueryEventsRequest {
4404                as_of_valid: None,
4405                since_valid: None,
4406                until_valid: None,
4407                entity_id: None,
4408                event_type: None,
4409                tenant_id: Some("bob".to_string()),
4410                as_of: None,
4411                since: None,
4412                until: None,
4413                limit: None,
4414                event_type_prefix: None,
4415                exclude_event_type_prefix: None,
4416                payload_filter: None,
4417            })
4418            .unwrap();
4419        assert_eq!(bob_results.len(), 2);
4420        for e in &bob_results {
4421            assert_eq!(e.tenant_id_str(), "bob");
4422        }
4423    }
4424
4425    #[test]
4426    fn test_budget_eviction_keeps_resident_set_bounded() {
4427        // Configure a tiny budget. Load three tenants in sequence;
4428        // the third load must evict the LRU tenant, keeping the
4429        // resident set under (or near) the budget.
4430        let temp_dir = TempDir::new().unwrap();
4431        let storage_dir = temp_dir.path().to_path_buf();
4432
4433        // Persist 5 events per tenant with ~1 KiB payloads. Each
4434        // tenant ends up at ~5 KiB + overhead.
4435        let big_payload = serde_json::json!({"data": "x".repeat(1000)});
4436        {
4437            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4438            for tenant in ["alice", "bob", "carol"] {
4439                for i in 0..5 {
4440                    store
4441                        .ingest(
4442                            &Event::from_strings(
4443                                "test.event".to_string(),
4444                                format!("{tenant}-{i}"),
4445                                tenant.to_string(),
4446                                big_payload.clone(),
4447                                None,
4448                            )
4449                            .unwrap(),
4450                        )
4451                        .unwrap();
4452                }
4453            }
4454            store.flush_storage().unwrap();
4455        }
4456
4457        // Budget = 12 KiB. Two tenants (~6 KiB each = ~12 KiB) is
4458        // tight; loading a third must evict.
4459        let mut config = EventStoreConfig::with_persistence(&storage_dir);
4460        config.cache_byte_budget = Some(12_000);
4461        let store = EventStore::with_config(config);
4462
4463        // Load alice — under budget, no eviction.
4464        store.ensure_tenant_loaded("alice").unwrap();
4465        assert!(store.is_tenant_loaded("alice"));
4466
4467        // Touch alice and immediately load bob. Bob is the
4468        // freshly-loaded one, so bob is excluded from eviction.
4469        // Alice is the next-oldest. After the load, total may
4470        // exceed budget — if so, evict alice.
4471        store.tenant_loader.touch("alice");
4472        std::thread::sleep(std::time::Duration::from_millis(10));
4473        store.ensure_tenant_loaded("bob").unwrap();
4474        assert!(store.is_tenant_loaded("bob"));
4475
4476        // Touch bob, load carol. Carol is freshly-loaded; the LRU
4477        // candidate is the older of {alice, bob} — alice (since
4478        // bob was just touched).
4479        store.tenant_loader.touch("bob");
4480        std::thread::sleep(std::time::Duration::from_millis(10));
4481        store.ensure_tenant_loaded("carol").unwrap();
4482        assert!(store.is_tenant_loaded("carol"));
4483
4484        // After all loads, the cache must respect the budget OR
4485        // (if a single tenant alone exceeds it) we should at most
4486        // hold the just-loaded tenant. The test budget is small
4487        // enough that we expect at least one eviction.
4488        let resident = store.cache_resident_bytes();
4489        let budget = 12_000u64;
4490
4491        // Either we're within the budget, or only the freshly-loaded
4492        // tenant is left (the "single oversized tenant" fallback).
4493        if resident > budget {
4494            let loaded_count = ["alice", "bob", "carol"]
4495                .iter()
4496                .filter(|t| store.is_tenant_loaded(t))
4497                .count();
4498            assert_eq!(
4499                loaded_count, 1,
4500                "over budget but more than one tenant loaded — eviction policy didn't fire"
4501            );
4502        }
4503
4504        // Carol must still be loaded — it's the most recent and
4505        // never picked as a victim.
4506        assert!(store.is_tenant_loaded("carol"));
4507    }
4508
4509    #[test]
4510    fn test_query_after_eviction_re_loads_transparently() {
4511        // The end-to-end shape of AC #5: query → evict → query
4512        // again returns the right data.
4513        let temp_dir = TempDir::new().unwrap();
4514        let storage_dir = temp_dir.path().to_path_buf();
4515
4516        let big_payload = serde_json::json!({"data": "x".repeat(2000)});
4517        {
4518            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4519            for tenant in ["alice", "bob"] {
4520                for i in 0..3 {
4521                    store
4522                        .ingest(
4523                            &Event::from_strings(
4524                                "test.event".to_string(),
4525                                format!("{tenant}-{i}"),
4526                                tenant.to_string(),
4527                                big_payload.clone(),
4528                                None,
4529                            )
4530                            .unwrap(),
4531                        )
4532                        .unwrap();
4533                }
4534            }
4535            store.flush_storage().unwrap();
4536        }
4537
4538        // Budget = 5 KiB — one tenant fits, two don't.
4539        let mut config = EventStoreConfig::with_persistence(&storage_dir);
4540        config.cache_byte_budget = Some(5_000);
4541        let store = EventStore::with_config(config);
4542
4543        // Query alice — sized at ~6 KiB, so over budget but no
4544        // peer to evict; alice stays as the single-oversized-tenant
4545        // case.
4546        let alice_first = store
4547            .query(&QueryEventsRequest {
4548                as_of_valid: None,
4549                since_valid: None,
4550                until_valid: None,
4551                entity_id: None,
4552                event_type: None,
4553                tenant_id: Some("alice".to_string()),
4554                as_of: None,
4555                since: None,
4556                until: None,
4557                limit: None,
4558                event_type_prefix: None,
4559                exclude_event_type_prefix: None,
4560                payload_filter: None,
4561            })
4562            .unwrap();
4563        assert_eq!(alice_first.len(), 3);
4564
4565        // Sleep to make alice older than bob in the LRU ordering.
4566        std::thread::sleep(std::time::Duration::from_millis(15));
4567        // Query bob — alice will get evicted.
4568        let _bob = store
4569            .query(&QueryEventsRequest {
4570                as_of_valid: None,
4571                since_valid: None,
4572                until_valid: None,
4573                entity_id: None,
4574                event_type: None,
4575                tenant_id: Some("bob".to_string()),
4576                as_of: None,
4577                since: None,
4578                until: None,
4579                limit: None,
4580                event_type_prefix: None,
4581                exclude_event_type_prefix: None,
4582                payload_filter: None,
4583            })
4584            .unwrap();
4585        assert!(
4586            !store.is_tenant_loaded("alice"),
4587            "alice should have been evicted"
4588        );
4589
4590        // Re-query alice — must transparently re-load.
4591        let alice_second = store
4592            .query(&QueryEventsRequest {
4593                as_of_valid: None,
4594                since_valid: None,
4595                until_valid: None,
4596                entity_id: None,
4597                event_type: None,
4598                tenant_id: Some("alice".to_string()),
4599                as_of: None,
4600                since: None,
4601                until: None,
4602                limit: None,
4603                event_type_prefix: None,
4604                exclude_event_type_prefix: None,
4605                payload_filter: None,
4606            })
4607            .unwrap();
4608        assert_eq!(
4609            alice_second.len(),
4610            3,
4611            "alice's events come back via re-load"
4612        );
4613        assert!(store.is_tenant_loaded("alice"));
4614    }
4615
4616    #[test]
4617    #[cfg(feature = "server")]
4618    fn test_cache_metrics_track_evictions_and_bytes() {
4619        // Smoke test for the Step 3 #4 Prometheus metrics —
4620        // confirms the counter increments on eviction and the
4621        // gauge tracks the resident bytes.
4622        let temp_dir = TempDir::new().unwrap();
4623        let storage_dir = temp_dir.path().to_path_buf();
4624
4625        let big_payload = serde_json::json!({"data": "x".repeat(2000)});
4626        {
4627            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4628            for tenant in ["alice", "bob"] {
4629                for i in 0..3 {
4630                    store
4631                        .ingest(
4632                            &Event::from_strings(
4633                                "test.event".to_string(),
4634                                format!("{tenant}-{i}"),
4635                                tenant.to_string(),
4636                                big_payload.clone(),
4637                                None,
4638                            )
4639                            .unwrap(),
4640                        )
4641                        .unwrap();
4642                }
4643            }
4644            store.flush_storage().unwrap();
4645        }
4646
4647        let mut config = EventStoreConfig::with_persistence(&storage_dir);
4648        config.cache_byte_budget = Some(5_000); // forces eviction
4649        let store = EventStore::with_config(config);
4650
4651        assert_eq!(store.metrics.cache_evictions_total.get(), 0);
4652        assert_eq!(store.metrics.cache_bytes.get(), 0);
4653
4654        store.ensure_tenant_loaded("alice").unwrap();
4655        // After loading alice, gauge reflects her bytes.
4656        let after_alice = store.metrics.cache_bytes.get();
4657        assert!(after_alice > 0, "gauge should reflect alice's bytes");
4658        // Single oversized tenant — no eviction yet.
4659        assert_eq!(store.metrics.cache_evictions_total.get(), 0);
4660
4661        std::thread::sleep(std::time::Duration::from_millis(10));
4662        store.ensure_tenant_loaded("bob").unwrap();
4663
4664        // Bob's load pushed total over budget; alice (older) was
4665        // evicted. Counter increments.
4666        assert_eq!(
4667            store.metrics.cache_evictions_total.get(),
4668            1,
4669            "exactly one tenant evicted after bob's load"
4670        );
4671        // Gauge now reflects only bob's bytes.
4672        let after_bob = store.metrics.cache_bytes.get();
4673        assert!(after_bob > 0);
4674        assert!(after_bob <= after_alice, "gauge dropped after eviction");
4675    }
4676
4677    #[test]
4678    #[cfg(feature = "server")]
4679    fn test_storage_size_gauge_populated_from_on_disk_bytes() {
4680        // The allsource_storage_size_bytes / _parquet_files_total / _wal_segments_total
4681        // gauges used to be registered but never set (constant 0), so the dashboard's
4682        // "storage" card showed "—". refresh_storage_metrics must populate them from
4683        // the real on-disk footprint (Parquet bytes + WAL segment bytes).
4684        let temp_dir = TempDir::new().unwrap();
4685        // Configure BOTH Parquet persistence and a WAL so the gauge exercises the
4686        // full `parquet_bytes + wal_bytes` summation (production runs with both).
4687        let config = EventStoreConfig {
4688            storage_dir: Some(temp_dir.path().join("parquet")),
4689            wal_dir: Some(temp_dir.path().join("wal")),
4690            ..EventStoreConfig::default()
4691        };
4692        let store = EventStore::with_config(config);
4693
4694        // Gauge starts at 0 before anything is written/refreshed.
4695        assert_eq!(store.metrics.storage_size_bytes.get(), 0);
4696
4697        let payload = serde_json::json!({ "data": "x".repeat(2000) });
4698        for i in 0..10 {
4699            store
4700                .ingest(
4701                    &Event::from_strings(
4702                        "test.event".to_string(),
4703                        format!("entity-{i}"),
4704                        "tenant-a".to_string(),
4705                        payload.clone(),
4706                        None,
4707                    )
4708                    .unwrap(),
4709                )
4710                .unwrap();
4711        }
4712        store.flush_storage().unwrap();
4713
4714        // Populate the gauges from disk (what the boot hook + checkpoint loop call).
4715        store.refresh_storage_metrics_now();
4716
4717        let size = store.metrics.storage_size_bytes.get();
4718        assert!(
4719            size > 0,
4720            "storage_size_bytes must reflect real on-disk bytes, got {size}"
4721        );
4722        assert!(
4723            store.metrics.parquet_files_total.get() >= 1,
4724            "at least one Parquet file should exist after a flush"
4725        );
4726
4727        // WAL segment count is surfaced too: with a WAL configured and writes done,
4728        // there is at least one segment on disk.
4729        assert!(
4730            store.metrics.wal_segments_total.get() >= 1,
4731            "at least one WAL segment should exist after writes"
4732        );
4733
4734        // Sanity: the reported size is the Parquet bytes plus the WAL bytes — i.e.
4735        // it's the real on-disk footprint, not a stale/placeholder value.
4736        let parquet_stats = store.storage.as_ref().unwrap().read().stats().unwrap();
4737        let (wal_bytes, _) = store.wal.as_ref().unwrap().on_disk_stats().unwrap();
4738        assert_eq!(
4739            size as u64,
4740            parquet_stats.total_size_bytes + wal_bytes,
4741            "gauge should equal Parquet bytes ({}) + WAL bytes ({wal_bytes})",
4742            parquet_stats.total_size_bytes
4743        );
4744    }
4745
4746    #[test]
4747    fn budget_enforced_without_hydration() {
4748        let temp_dir = TempDir::new().unwrap();
4749        let storage_dir = temp_dir.path().to_path_buf();
4750        let big_payload = serde_json::json!({"data": "x".repeat(1000)});
4751        {
4752            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4753            for tenant in ["alice", "bob"] {
4754                for i in 0..5 {
4755                    store
4756                        .ingest(
4757                            &Event::from_strings(
4758                                "test.event".to_string(),
4759                                format!("{tenant}-{i}"),
4760                                tenant.to_string(),
4761                                big_payload.clone(),
4762                                None,
4763                            )
4764                            .unwrap(),
4765                        )
4766                        .unwrap();
4767                }
4768            }
4769            store.flush_storage().unwrap();
4770        }
4771
4772        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4773        store.ensure_tenant_loaded("alice").unwrap();
4774        std::thread::sleep(std::time::Duration::from_millis(10));
4775        store.ensure_tenant_loaded("bob").unwrap();
4776        assert!(store.is_tenant_loaded("alice") && store.is_tenant_loaded("bob"));
4777
4778        // A budget one byte under what both tenants hold: no hydration runs,
4779        // so only the timer's enforcement can evict.
4780        store
4781            .tenant_loader
4782            .set_byte_budget(store.tenant_loader.total_bytes() - 1);
4783        store.enforce_cache_budget_now();
4784
4785        assert!(!store.is_tenant_loaded("alice"), "LRU tenant is evicted");
4786        assert!(store.is_tenant_loaded("bob"), "the newer tenant stays");
4787    }
4788
4789    #[test]
4790    fn test_stress_resident_set_stays_near_budget_under_rolling_queries() {
4791        // Scaled-down version of the bead's stress test: the
4792        // bead's 10 × 50 MB / 100 MB ratio (10× tenants vs
4793        // budget-headroom) preserved at 500 KB / 1 MB to stay
4794        // unit-test-fast. The same correctness property: after
4795        // many rolling queries across more tenants than fit, the
4796        // resident set must stay at-or-near the budget.
4797        let temp_dir = TempDir::new().unwrap();
4798        let storage_dir = temp_dir.path().to_path_buf();
4799
4800        const TENANT_COUNT: usize = 10;
4801        const EVENTS_PER_TENANT: usize = 50;
4802        // Per-event payload ~10 KiB → tenant ~ 500 KiB.
4803        let big_payload = serde_json::json!({"data": "x".repeat(10_000)});
4804
4805        // Persist all tenants. Each ends up at ~500 KiB on disk
4806        // (and roughly the same in memory once loaded).
4807        {
4808            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4809            for t in 0..TENANT_COUNT {
4810                let tenant = format!("tenant-{t}");
4811                for i in 0..EVENTS_PER_TENANT {
4812                    store
4813                        .ingest(
4814                            &Event::from_strings(
4815                                "test.event".to_string(),
4816                                format!("{tenant}-{i}"),
4817                                tenant.clone(),
4818                                big_payload.clone(),
4819                                None,
4820                            )
4821                            .unwrap(),
4822                        )
4823                        .unwrap();
4824                }
4825            }
4826            store.flush_storage().unwrap();
4827        }
4828
4829        // Budget = 1 MiB → fits ~2 tenants. We're going to query
4830        // all 10, so the LRU policy must hold the resident set
4831        // near 1 MiB across the rolling sequence.
4832        const BUDGET: u64 = 1_048_576;
4833        let mut config = EventStoreConfig::with_persistence(&storage_dir);
4834        config.cache_byte_budget = Some(BUDGET);
4835        let store = EventStore::with_config(config);
4836
4837        // Sweep through tenants in order. Each query loads its
4838        // tenant; if budget is exceeded after the load, an LRU
4839        // eviction fires.
4840        let mut peak_resident: u64 = 0;
4841        for t in 0..TENANT_COUNT {
4842            let tenant = format!("tenant-{t}");
4843            let results = store
4844                .query(&QueryEventsRequest {
4845                    as_of_valid: None,
4846                    since_valid: None,
4847                    until_valid: None,
4848                    entity_id: None,
4849                    event_type: None,
4850                    tenant_id: Some(tenant.clone()),
4851                    as_of: None,
4852                    since: None,
4853                    until: None,
4854                    limit: None,
4855                    event_type_prefix: None,
4856                    exclude_event_type_prefix: None,
4857                    payload_filter: None,
4858                })
4859                .unwrap();
4860            assert_eq!(
4861                results.len(),
4862                EVENTS_PER_TENANT,
4863                "every per-tenant query must return all of that tenant's events"
4864            );
4865            // Track peak resident bytes seen during the sweep.
4866            let resident = store.cache_resident_bytes();
4867            if resident > peak_resident {
4868                peak_resident = resident;
4869            }
4870        }
4871
4872        let final_resident = store.cache_resident_bytes();
4873
4874        // Tolerance: a tenant's bytes get added before eviction
4875        // fires, so peak transiently exceeds the budget by at
4876        // most one tenant's worth (~500 KiB). The final state
4877        // after the sweep should be well-bounded.
4878        let tolerance = BUDGET; // generous: 2× budget upper bound
4879        assert!(
4880            peak_resident <= BUDGET + tolerance,
4881            "peak resident {peak_resident} exceeds budget {BUDGET} by more than {tolerance} \
4882             — eviction policy not keeping up with the working-set churn"
4883        );
4884        assert!(
4885            final_resident <= BUDGET + tolerance,
4886            "final resident {final_resident} exceeds budget {BUDGET} by more than {tolerance}"
4887        );
4888
4889        // The most-recently-queried tenant must still be loaded
4890        // (it was just touched).
4891        let last_tenant = format!("tenant-{}", TENANT_COUNT - 1);
4892        assert!(
4893            store.is_tenant_loaded(&last_tenant),
4894            "the most-recent tenant must remain loaded after the sweep"
4895        );
4896
4897        // At least some tenants must have been evicted — otherwise
4898        // the budget didn't fire.
4899        let still_loaded = (0..TENANT_COUNT)
4900            .filter(|t| store.is_tenant_loaded(&format!("tenant-{t}")))
4901            .count();
4902        assert!(
4903            still_loaded < TENANT_COUNT,
4904            "no tenants evicted ({still_loaded}/{TENANT_COUNT} still loaded) — \
4905             budget enforcement didn't engage"
4906        );
4907    }
4908
4909    #[test]
4910    fn test_evict_tenant_when_not_loaded_is_a_noop() {
4911        // Eviction of a never-loaded tenant must not panic and
4912        // must not affect other tenants.
4913        let store = EventStore::new();
4914        store.evict_tenant("nobody"); // should not panic
4915        assert!(!store.is_tenant_loaded("nobody"));
4916    }
4917
4918    #[test]
4919    fn test_lazy_load_accounts_bytes_per_tenant() {
4920        // Step 3 #1: per-tenant byte tracking. Loading a tenant
4921        // should accumulate bytes proportional to its event
4922        // payload sizes; another tenant's counter must stay 0.
4923        let temp_dir = TempDir::new().unwrap();
4924        let storage_dir = temp_dir.path().to_path_buf();
4925
4926        // Persist 5 events for alice with measurable-size payloads.
4927        {
4928            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4929            for i in 0..5 {
4930                store
4931                    .ingest(
4932                        &Event::from_strings(
4933                            "test.event".to_string(),
4934                            format!("a-{i}"),
4935                            "alice".to_string(),
4936                            serde_json::json!({"data": "x".repeat(1000)}),
4937                            None,
4938                        )
4939                        .unwrap(),
4940                    )
4941                    .unwrap();
4942            }
4943            store.flush_storage().unwrap();
4944        }
4945
4946        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4947        // Cold: zero bytes accounted.
4948        assert_eq!(store.tenant_resident_bytes("alice"), 0);
4949        assert_eq!(store.cache_resident_bytes(), 0);
4950
4951        store.ensure_tenant_loaded("alice").unwrap();
4952
4953        // After load: alice's counter is non-trivial (5 events
4954        // each carrying ~1000 bytes of payload + overhead).
4955        let alice_bytes = store.tenant_resident_bytes("alice");
4956        assert!(
4957            alice_bytes >= 5 * 1000,
4958            "alice should have at least 5 KiB resident; got {alice_bytes}"
4959        );
4960        // Bob never loaded → 0.
4961        assert_eq!(store.tenant_resident_bytes("bob"), 0);
4962        // Total equals alice's portion (only loaded tenant).
4963        assert_eq!(store.cache_resident_bytes(), alice_bytes);
4964    }
4965
4966    #[test]
4967    fn test_query_lazy_loads_tenant_on_first_call() {
4968        // The end-to-end shape of Step 2: persist events for a
4969        // tenant in session 1, restart, and confirm session 2 boots
4970        // empty but a query for that tenant pulls them in.
4971        let temp_dir = TempDir::new().unwrap();
4972        let storage_dir = temp_dir.path().to_path_buf();
4973
4974        // Session 1: ingest 3 events for tenant "alice", flush, drop.
4975        {
4976            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4977            for i in 0..3 {
4978                let event = Event::from_strings(
4979                    "test.event".to_string(),
4980                    format!("e-{i}"),
4981                    "alice".to_string(),
4982                    serde_json::json!({"i": i}),
4983                    None,
4984                )
4985                .unwrap();
4986                store.ingest(&event).unwrap();
4987            }
4988            store.flush_storage().unwrap();
4989        }
4990
4991        // Session 2: fresh boot. Events on disk, nothing in memory.
4992        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
4993        assert_eq!(
4994            store.stats().total_events,
4995            0,
4996            "boot must be O(1) — no Parquet pre-load"
4997        );
4998        assert!(!store.is_tenant_loaded("alice"));
4999        assert!(!store.is_tenant_loaded("bob"));
5000
5001        // First query for alice: triggers ensure_tenant_loaded.
5002        let results = store
5003            .query(&QueryEventsRequest {
5004                as_of_valid: None,
5005                since_valid: None,
5006                until_valid: None,
5007                entity_id: None,
5008                event_type: None,
5009                tenant_id: Some("alice".to_string()),
5010                as_of: None,
5011                since: None,
5012                until: None,
5013                limit: None,
5014                event_type_prefix: None,
5015                exclude_event_type_prefix: None,
5016                payload_filter: None,
5017            })
5018            .unwrap();
5019        assert_eq!(results.len(), 3, "alice's 3 events are returned");
5020        assert!(store.is_tenant_loaded("alice"), "alice now warm");
5021        // bob untouched — load is per-tenant, so a query for alice
5022        // must not have hydrated bob.
5023        assert!(!store.is_tenant_loaded("bob"), "bob still cold");
5024    }
5025
5026    #[test]
5027    fn test_query_invalid_tenant_id_returns_error_no_hang() {
5028        // Step 2 acceptance criterion: in-flight load failures
5029        // surface as errors, not infinite hangs. Path-traversal
5030        // input fails fast at sanitization and propagates.
5031        let temp_dir = TempDir::new().unwrap();
5032        let store = EventStore::with_config(EventStoreConfig::with_persistence(temp_dir.path()));
5033
5034        let result = store.query(&QueryEventsRequest {
5035            as_of_valid: None,
5036            since_valid: None,
5037            until_valid: None,
5038            entity_id: None,
5039            event_type: None,
5040            tenant_id: Some("../etc".to_string()),
5041            as_of: None,
5042            since: None,
5043            until: None,
5044            limit: None,
5045            event_type_prefix: None,
5046            exclude_event_type_prefix: None,
5047            payload_filter: None,
5048        });
5049        assert!(result.is_err(), "unsafe tenant_id must surface as error");
5050    }
5051
5052    #[test]
5053    fn test_query_concurrent_first_queries_for_same_tenant_all_succeed() {
5054        // Singleflight: N threads racing to query the same cold
5055        // tenant must all return the same correct result. The
5056        // tenant-load must happen exactly once (verified
5057        // structurally by the per-tenant Mutex in tenant_loader,
5058        // tested directly in test_singleflight_blocks_second_caller).
5059        // This integration test confirms the wiring at the query
5060        // level — no thread observes a half-loaded state.
5061        let temp_dir = TempDir::new().unwrap();
5062        let storage_dir = temp_dir.path().to_path_buf();
5063
5064        // Persist 25 events for tenant "alice".
5065        {
5066            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
5067            for i in 0..25 {
5068                let event = Event::from_strings(
5069                    "test.event".to_string(),
5070                    format!("e-{i}"),
5071                    "alice".to_string(),
5072                    serde_json::json!({"i": i}),
5073                    None,
5074                )
5075                .unwrap();
5076                store.ingest(&event).unwrap();
5077            }
5078            store.flush_storage().unwrap();
5079        }
5080
5081        // Fresh boot, then 8 threads simultaneously query alice.
5082        let store = Arc::new(EventStore::with_config(EventStoreConfig::with_persistence(
5083            &storage_dir,
5084        )));
5085        assert!(!store.is_tenant_loaded("alice"));
5086
5087        let mut handles = Vec::new();
5088        for _ in 0..8 {
5089            let s = store.clone();
5090            handles.push(std::thread::spawn(move || {
5091                s.query(&QueryEventsRequest {
5092                    as_of_valid: None,
5093                    since_valid: None,
5094                    until_valid: None,
5095                    entity_id: None,
5096                    event_type: None,
5097                    tenant_id: Some("alice".to_string()),
5098                    as_of: None,
5099                    since: None,
5100                    until: None,
5101                    limit: None,
5102                    event_type_prefix: None,
5103                    exclude_event_type_prefix: None,
5104                    payload_filter: None,
5105                })
5106            }));
5107        }
5108
5109        for h in handles {
5110            let result = h.join().unwrap().unwrap();
5111            assert_eq!(
5112                result.len(),
5113                25,
5114                "every concurrent caller must see all 25 events"
5115            );
5116        }
5117        assert!(store.is_tenant_loaded("alice"));
5118        // Memory has exactly 25 events — no double-load.
5119        assert_eq!(store.stats().total_events, 25);
5120    }
5121
5122    #[test]
5123    fn test_query_two_cold_tenants_load_independently() {
5124        // Querying tenant A loads only A; querying B then loads
5125        // only B. State after both queries: both tenants warm,
5126        // memory has exactly the expected event counts.
5127        let temp_dir = TempDir::new().unwrap();
5128        let storage_dir = temp_dir.path().to_path_buf();
5129
5130        {
5131            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
5132            for i in 0..3 {
5133                store
5134                    .ingest(
5135                        &Event::from_strings(
5136                            "test.event".to_string(),
5137                            format!("a-{i}"),
5138                            "alice".to_string(),
5139                            serde_json::json!({"i": i}),
5140                            None,
5141                        )
5142                        .unwrap(),
5143                    )
5144                    .unwrap();
5145            }
5146            for i in 0..5 {
5147                store
5148                    .ingest(
5149                        &Event::from_strings(
5150                            "test.event".to_string(),
5151                            format!("b-{i}"),
5152                            "bob".to_string(),
5153                            serde_json::json!({"i": i}),
5154                            None,
5155                        )
5156                        .unwrap(),
5157                    )
5158                    .unwrap();
5159            }
5160            store.flush_storage().unwrap();
5161        }
5162
5163        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
5164        assert_eq!(store.stats().total_events, 0);
5165
5166        // Query alice — bob stays cold.
5167        let alice = store
5168            .query(&QueryEventsRequest {
5169                as_of_valid: None,
5170                since_valid: None,
5171                until_valid: None,
5172                entity_id: None,
5173                event_type: None,
5174                tenant_id: Some("alice".to_string()),
5175                as_of: None,
5176                since: None,
5177                until: None,
5178                limit: None,
5179                event_type_prefix: None,
5180                exclude_event_type_prefix: None,
5181                payload_filter: None,
5182            })
5183            .unwrap();
5184        assert_eq!(alice.len(), 3);
5185        assert!(store.is_tenant_loaded("alice"));
5186        assert!(!store.is_tenant_loaded("bob"));
5187        assert_eq!(store.stats().total_events, 3);
5188
5189        // Query bob — both warm now.
5190        let bob = store
5191            .query(&QueryEventsRequest {
5192                as_of_valid: None,
5193                since_valid: None,
5194                until_valid: None,
5195                entity_id: None,
5196                event_type: None,
5197                tenant_id: Some("bob".to_string()),
5198                as_of: None,
5199                since: None,
5200                until: None,
5201                limit: None,
5202                event_type_prefix: None,
5203                exclude_event_type_prefix: None,
5204                payload_filter: None,
5205            })
5206            .unwrap();
5207        assert_eq!(bob.len(), 5);
5208        assert!(store.is_tenant_loaded("bob"));
5209        assert_eq!(store.stats().total_events, 8);
5210    }
5211
5212    #[test]
5213    fn test_boot_with_persisted_data_is_o1() {
5214        // Step 2's headline acceptance criterion: boot time does
5215        // not scale with persisted-data size. The 5M-events / <2s
5216        // target is too large for a unit test, so this asserts the
5217        // weaker but structural property: boot reads zero events
5218        // into memory regardless of how many are on disk.
5219        //
5220        // We persist 50 events across 3 tenants in session 1,
5221        // restart in session 2, and verify session 2's
5222        // total_events is 0. The actual boot wall-clock isn't
5223        // asserted here — it's machine-dependent — but the absence
5224        // of any in-memory data is the structural proxy that the
5225        // boot path no longer iterates Parquet.
5226        let temp_dir = TempDir::new().unwrap();
5227        let storage_dir = temp_dir.path().to_path_buf();
5228
5229        {
5230            let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
5231            for tenant in ["alice", "bob", "carol"] {
5232                for i in 0..50 / 3 {
5233                    store
5234                        .ingest(
5235                            &Event::from_strings(
5236                                "test.event".to_string(),
5237                                format!("{tenant}-{i}"),
5238                                tenant.to_string(),
5239                                serde_json::json!({"i": i}),
5240                                None,
5241                            )
5242                            .unwrap(),
5243                        )
5244                        .unwrap();
5245                }
5246            }
5247            store.flush_storage().unwrap();
5248        }
5249
5250        // Confirm there is in fact data on disk to load.
5251        let on_disk = find_parquet_files(&storage_dir);
5252        assert!(
5253            !on_disk.is_empty(),
5254            "session 1 should have produced parquet files; pre-condition for the test"
5255        );
5256
5257        let started = std::time::Instant::now();
5258        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
5259        let boot_elapsed = started.elapsed();
5260
5261        assert_eq!(
5262            store.stats().total_events,
5263            0,
5264            "boot must not pre-load any Parquet events"
5265        );
5266
5267        // Sanity: even on a slow CI box, an O(1) boot finishes in
5268        // well under a second. If this trips it's a strong signal
5269        // the boot path regressed to scanning the Parquet tree.
5270        assert!(
5271            boot_elapsed < std::time::Duration::from_secs(2),
5272            "boot took {boot_elapsed:?} — Step 2 boot should be O(1)"
5273        );
5274    }
5275
5276    #[test]
5277    fn test_query_warm_tenant_does_not_re_read_disk() {
5278        // Performance contract: a warm tenant query goes through the
5279        // DashMap fast path. We can't easily assert "no disk read"
5280        // directly in a unit test, but we CAN assert the call
5281        // succeeds in O(in-memory-events) time even after the
5282        // on-disk file is removed — proving we didn't re-walk it.
5283        let temp_dir = TempDir::new().unwrap();
5284        let storage_dir = temp_dir.path().to_path_buf();
5285
5286        let store = EventStore::with_config(EventStoreConfig::with_persistence(&storage_dir));
5287        for i in 0..3 {
5288            let event = Event::from_strings(
5289                "test.event".to_string(),
5290                format!("e-{i}"),
5291                "alice".to_string(),
5292                serde_json::json!({"i": i}),
5293                None,
5294            )
5295            .unwrap();
5296            store.ingest(&event).unwrap();
5297        }
5298        store.flush_storage().unwrap();
5299
5300        // First query: cold, hits disk.
5301        let _ = store
5302            .query(&QueryEventsRequest {
5303                as_of_valid: None,
5304                since_valid: None,
5305                until_valid: None,
5306                entity_id: None,
5307                event_type: None,
5308                tenant_id: Some("alice".to_string()),
5309                as_of: None,
5310                since: None,
5311                until: None,
5312                limit: None,
5313                event_type_prefix: None,
5314                exclude_event_type_prefix: None,
5315                payload_filter: None,
5316            })
5317            .unwrap();
5318        assert!(store.is_tenant_loaded("alice"));
5319
5320        // Now wipe the on-disk file. A warm-path query must still
5321        // succeed because it doesn't need disk.
5322        let parquet_files = find_parquet_files(&storage_dir);
5323        for f in parquet_files {
5324            std::fs::remove_file(&f).unwrap();
5325        }
5326
5327        let results = store
5328            .query(&QueryEventsRequest {
5329                as_of_valid: None,
5330                since_valid: None,
5331                until_valid: None,
5332                entity_id: None,
5333                event_type: None,
5334                tenant_id: Some("alice".to_string()),
5335                as_of: None,
5336                since: None,
5337                until: None,
5338                limit: None,
5339                event_type_prefix: None,
5340                exclude_event_type_prefix: None,
5341                payload_filter: None,
5342            })
5343            .unwrap();
5344        assert_eq!(
5345            results.len(),
5346            3,
5347            "warm tenant query must not need disk; got {} events from a deleted parquet",
5348            results.len()
5349        );
5350    }
5351
5352    #[test]
5353    fn test_event_store_default() {
5354        let store = EventStore::default();
5355        assert_eq!(store.stats().total_events, 0);
5356    }
5357
5358    #[test]
5359    fn test_ingest_single_event() {
5360        let store = EventStore::new();
5361        let event = create_test_event("entity-1", "user.created");
5362
5363        store.ingest(&event).unwrap();
5364
5365        assert_eq!(store.stats().total_events, 1);
5366        assert_eq!(store.stats().total_ingested, 1);
5367    }
5368
5369    #[test]
5370    fn test_ingest_multiple_events() {
5371        let store = EventStore::new();
5372
5373        for i in 0..10 {
5374            let event = create_test_event(&format!("entity-{i}"), "user.created");
5375            store.ingest(&event).unwrap();
5376        }
5377
5378        assert_eq!(store.stats().total_events, 10);
5379        assert_eq!(store.stats().total_ingested, 10);
5380    }
5381
5382    #[test]
5383    fn test_query_by_entity_id() {
5384        let store = EventStore::new();
5385
5386        store
5387            .ingest(&create_test_event("entity-1", "user.created"))
5388            .unwrap();
5389        store
5390            .ingest(&create_test_event("entity-2", "user.created"))
5391            .unwrap();
5392        store
5393            .ingest(&create_test_event("entity-1", "user.updated"))
5394            .unwrap();
5395
5396        let results = store
5397            .query(&QueryEventsRequest {
5398                as_of_valid: None,
5399                since_valid: None,
5400                until_valid: None,
5401                entity_id: Some("entity-1".to_string()),
5402                event_type: None,
5403                tenant_id: None,
5404                as_of: None,
5405                since: None,
5406                until: None,
5407                limit: None,
5408                event_type_prefix: None,
5409                exclude_event_type_prefix: None,
5410                payload_filter: None,
5411            })
5412            .unwrap();
5413
5414        assert_eq!(results.len(), 2);
5415    }
5416
5417    #[test]
5418    fn test_query_by_event_type() {
5419        let store = EventStore::new();
5420
5421        store
5422            .ingest(&create_test_event("entity-1", "user.created"))
5423            .unwrap();
5424        store
5425            .ingest(&create_test_event("entity-2", "user.updated"))
5426            .unwrap();
5427        store
5428            .ingest(&create_test_event("entity-3", "user.created"))
5429            .unwrap();
5430
5431        let results = store
5432            .query(&QueryEventsRequest {
5433                as_of_valid: None,
5434                since_valid: None,
5435                until_valid: None,
5436                entity_id: None,
5437                event_type: Some("user.created".to_string()),
5438                tenant_id: None,
5439                as_of: None,
5440                since: None,
5441                until: None,
5442                limit: None,
5443                event_type_prefix: None,
5444                exclude_event_type_prefix: None,
5445                payload_filter: None,
5446            })
5447            .unwrap();
5448
5449        assert_eq!(results.len(), 2);
5450    }
5451
5452    #[test]
5453    fn test_query_with_limit() {
5454        let store = EventStore::new();
5455
5456        for i in 0..10 {
5457            let event = create_test_event(&format!("entity-{i}"), "user.created");
5458            store.ingest(&event).unwrap();
5459        }
5460
5461        let results = store
5462            .query(&QueryEventsRequest {
5463                as_of_valid: None,
5464                since_valid: None,
5465                until_valid: None,
5466                entity_id: None,
5467                event_type: None,
5468                tenant_id: None,
5469                as_of: None,
5470                since: None,
5471                until: None,
5472                limit: Some(5),
5473                event_type_prefix: None,
5474                exclude_event_type_prefix: None,
5475                payload_filter: None,
5476            })
5477            .unwrap();
5478
5479        assert_eq!(results.len(), 5);
5480    }
5481
5482    #[test]
5483    fn test_query_empty_store() {
5484        let store = EventStore::new();
5485
5486        let results = store
5487            .query(&QueryEventsRequest {
5488                as_of_valid: None,
5489                since_valid: None,
5490                until_valid: None,
5491                entity_id: Some("non-existent".to_string()),
5492                event_type: None,
5493                tenant_id: None,
5494                as_of: None,
5495                since: None,
5496                until: None,
5497                limit: None,
5498                event_type_prefix: None,
5499                exclude_event_type_prefix: None,
5500                payload_filter: None,
5501            })
5502            .unwrap();
5503
5504        assert!(results.is_empty());
5505    }
5506
5507    #[test]
5508    fn test_reconstruct_state() {
5509        let store = EventStore::new();
5510
5511        store
5512            .ingest(&create_test_event("entity-1", "user.created"))
5513            .unwrap();
5514
5515        let state = store.reconstruct_state("entity-1", None).unwrap();
5516        // The state is wrapped with metadata
5517        assert_eq!(state["current_state"]["name"], "Test");
5518        assert_eq!(state["current_state"]["value"], 42);
5519    }
5520
5521    #[test]
5522    fn test_reconstruct_state_not_found() {
5523        let store = EventStore::new();
5524
5525        let result = store.reconstruct_state("non-existent", None);
5526        assert!(result.is_err());
5527    }
5528
5529    #[test]
5530    fn test_get_snapshot_empty() {
5531        let store = EventStore::new();
5532
5533        let result = store.get_snapshot("non-existent");
5534        // Entity not found error is expected
5535        assert!(result.is_err());
5536    }
5537
5538    #[test]
5539    fn entity_state_without_history_omits_history_and_reports_version() {
5540        let store = EventStore::new();
5541        for _ in 0..3 {
5542            store
5543                .ingest(&create_test_event("entity-1", "user.updated"))
5544                .unwrap();
5545        }
5546
5547        let state = store.entity_state("entity-1", None, None, false).unwrap();
5548
5549        assert!(state.get("history").is_none());
5550        assert_eq!(state["event_count"], 3);
5551        assert_eq!(state["version"], 3);
5552        assert_eq!(state["current_state"]["name"], "Test");
5553    }
5554
5555    #[test]
5556    fn entity_state_with_history_lists_every_folded_event() {
5557        let store = EventStore::new();
5558        for _ in 0..2 {
5559            store
5560                .ingest(&create_test_event("entity-1", "user.updated"))
5561                .unwrap();
5562        }
5563
5564        let state = store.entity_state("entity-1", None, None, true).unwrap();
5565
5566        assert_eq!(state["history"].as_array().unwrap().len(), 2);
5567        assert_eq!(state["version"], 2);
5568    }
5569
5570    #[test]
5571    fn reconstruct_state_folds_every_event_on_each_read() {
5572        let store = EventStore::new();
5573        for _ in 0..250 {
5574            store
5575                .ingest(&create_test_event("entity-1", "user.updated"))
5576                .unwrap();
5577        }
5578
5579        let state = store.reconstruct_state("entity-1", None).unwrap();
5580
5581        assert_eq!(state["event_count"], 250);
5582        assert_eq!(state["history"].as_array().unwrap().len(), 250);
5583    }
5584
5585    #[test]
5586    fn entity_state_at_answers_what_was_believed_and_what_was_true() {
5587        let store = EventStore::new();
5588        let base = Utc::now() - chrono::Duration::hours(24);
5589        let at = |minutes: i64| base + chrono::Duration::minutes(minutes);
5590
5591        // Filed at 0 and true from 0: the renewal is in June.
5592        let mut original = create_test_event("contract-1", "contract.renewal");
5593        original.timestamp = at(0);
5594        original.version = 1;
5595        original.payload = serde_json::json!({"renews": "june"});
5596        let original = original.with_valid_time(Some(at(0)), None).unwrap();
5597        store.ingest(&original).unwrap();
5598
5599        // Filed at 300, same valid time: the renewal is in September.
5600        let mut correction = create_test_event("contract-1", "contract.renewal");
5601        correction.timestamp = at(300);
5602        correction.version = 2;
5603        correction.payload = serde_json::json!({"renews": "september"});
5604        let correction = correction.with_valid_time(Some(at(0)), None).unwrap();
5605        store.ingest(&correction).unwrap();
5606
5607        // What we believed at 100: only the original was on file.
5608        let believed = store
5609            .entity_state_at("contract-1", Some(at(100)), None, None, false)
5610            .unwrap();
5611        assert_eq!(believed["current_state"]["renews"], "june");
5612
5613        // What was true at 50, given everything filed so far.
5614        let now_known = store
5615            .entity_state_at("contract-1", None, Some(at(50)), None, false)
5616            .unwrap();
5617        assert_eq!(now_known["current_state"]["renews"], "september");
5618        assert_eq!(now_known["as_of_valid"], serde_json::json!(at(50)));
5619
5620        // What was true at 50, as far as we knew at 100: the correction is not on file yet.
5621        let both = store
5622            .entity_state_at("contract-1", Some(at(100)), Some(at(50)), None, false)
5623            .unwrap();
5624        assert_eq!(both["current_state"]["renews"], "june");
5625    }
5626
5627    #[test]
5628    fn entity_state_at_valid_fold_orders_by_valid_from_not_record_time() {
5629        let store = EventStore::new();
5630        let base = Utc::now() - chrono::Duration::hours(24);
5631        let at = |minutes: i64| base + chrono::Duration::minutes(minutes);
5632
5633        // Recorded first, but true only from 90.
5634        let mut later_fact = create_test_event("contract-2", "contract.renewal");
5635        later_fact.timestamp = at(0);
5636        later_fact.version = 1;
5637        later_fact.payload = serde_json::json!({"renews": "june"});
5638        let later_fact = later_fact.with_valid_time(Some(at(90)), None).unwrap();
5639        store.ingest(&later_fact).unwrap();
5640
5641        // Recorded last, but true from 0: it is the earlier fact.
5642        let mut earlier_fact = create_test_event("contract-2", "contract.renewal");
5643        earlier_fact.timestamp = at(300);
5644        earlier_fact.version = 2;
5645        earlier_fact.payload = serde_json::json!({"renews": "september"});
5646        let earlier_fact = earlier_fact.with_valid_time(Some(at(0)), None).unwrap();
5647        store.ingest(&earlier_fact).unwrap();
5648
5649        let by_valid = store
5650            .entity_state_at("contract-2", None, Some(at(200)), None, true)
5651            .unwrap();
5652        assert_eq!(by_valid["current_state"]["renews"], "june");
5653        assert_eq!(
5654            by_valid["history"][0]["event_id"],
5655            serde_json::json!(earlier_fact.id)
5656        );
5657
5658        let by_record = store.entity_state("contract-2", None, None, true).unwrap();
5659        assert_eq!(by_record["current_state"]["renews"], "september");
5660        assert!(by_record.get("as_of_valid").is_none());
5661    }
5662
5663    #[test]
5664    fn test_websocket_manager() {
5665        let store = EventStore::new();
5666        let manager = store.websocket_manager();
5667        // Manager should be accessible
5668        assert!(Arc::strong_count(&manager) >= 1);
5669    }
5670
5671    #[test]
5672    fn test_compaction_manager_none() {
5673        let store = EventStore::new();
5674        // Without storage_dir, compaction manager should be None
5675        assert!(store.compaction_manager().is_none());
5676    }
5677
5678    #[test]
5679    fn test_schema_registry() {
5680        let store = EventStore::new();
5681        let registry = store.schema_registry();
5682        assert!(Arc::strong_count(&registry) >= 1);
5683    }
5684
5685    #[test]
5686    fn test_replay_manager() {
5687        let store = EventStore::new();
5688        let manager = store.replay_manager();
5689        assert!(Arc::strong_count(&manager) >= 1);
5690    }
5691
5692    #[test]
5693    fn test_pipeline_manager() {
5694        let store = EventStore::new();
5695        let manager = store.pipeline_manager();
5696        assert!(Arc::strong_count(&manager) >= 1);
5697    }
5698
5699    #[test]
5700    fn test_projection_manager() {
5701        let store = EventStore::new();
5702        let manager = store.projection_manager();
5703        assert!(manager.get_projection("event_counters").is_some());
5704        assert!(manager.get_projection("entity_snapshots").is_none());
5705    }
5706
5707    #[test]
5708    fn test_metrics() {
5709        let store = EventStore::new();
5710        let metrics = store.metrics();
5711        assert!(Arc::strong_count(&metrics) >= 1);
5712    }
5713
5714    #[test]
5715    fn test_store_stats() {
5716        let store = EventStore::new();
5717
5718        store
5719            .ingest(&create_test_event("entity-1", "user.created"))
5720            .unwrap();
5721        store
5722            .ingest(&create_test_event("entity-2", "order.placed"))
5723            .unwrap();
5724
5725        let stats = store.stats();
5726        assert_eq!(stats.total_events, 2);
5727        assert_eq!(stats.total_entities, 2);
5728        assert_eq!(stats.total_event_types, 2);
5729        assert_eq!(stats.total_ingested, 2);
5730    }
5731
5732    #[test]
5733    fn test_event_store_config_default() {
5734        let config = EventStoreConfig::default();
5735        assert!(config.storage_dir.is_none());
5736        assert!(config.wal_dir.is_none());
5737    }
5738
5739    #[test]
5740    fn test_event_store_config_with_persistence() {
5741        let temp_dir = TempDir::new().unwrap();
5742        let config = EventStoreConfig::with_persistence(temp_dir.path());
5743
5744        assert!(config.storage_dir.is_some());
5745        assert!(config.wal_dir.is_none());
5746    }
5747
5748    #[test]
5749    fn test_event_store_config_with_wal() {
5750        let temp_dir = TempDir::new().unwrap();
5751        let config = EventStoreConfig::with_wal(temp_dir.path(), WALConfig::default());
5752
5753        assert!(config.storage_dir.is_none());
5754        assert!(config.wal_dir.is_some());
5755    }
5756
5757    #[test]
5758    fn test_event_store_config_production() {
5759        let storage_dir = TempDir::new().unwrap();
5760        let wal_dir = TempDir::new().unwrap();
5761        let config = EventStoreConfig::production(
5762            storage_dir.path(),
5763            wal_dir.path(),
5764            WALConfig::default(),
5765            CompactionConfig::default(),
5766        );
5767
5768        assert!(config.storage_dir.is_some());
5769        assert!(config.wal_dir.is_some());
5770    }
5771
5772    // -----------------------------------------------------------------------
5773    // from_env_vars tests — verifies the env-var-to-config wiring that
5774    // caused the durability bug (events lost on restart) in v0.10.3.
5775    // -----------------------------------------------------------------------
5776
5777    #[test]
5778    fn test_from_env_vars_data_dir_enables_full_persistence() {
5779        let (config, mode) = EventStoreConfig::from_env_vars(
5780            Some("/app/data".to_string()),
5781            None,
5782            None,
5783            None,
5784            None,
5785            None,
5786            None,
5787            None,
5788        );
5789        assert_eq!(mode, "wal+parquet");
5790        assert_eq!(
5791            config.storage_dir.unwrap().to_str().unwrap(),
5792            "/app/data/storage"
5793        );
5794        assert_eq!(config.wal_dir.unwrap().to_str().unwrap(), "/app/data/wal");
5795    }
5796
5797    #[test]
5798    fn test_from_env_vars_explicit_dirs() {
5799        let (config, mode) = EventStoreConfig::from_env_vars(
5800            None,
5801            Some("/custom/storage".to_string()),
5802            Some("/custom/wal".to_string()),
5803            None,
5804            None,
5805            None,
5806            None,
5807            None,
5808        );
5809        assert_eq!(mode, "wal+parquet");
5810        assert_eq!(
5811            config.storage_dir.unwrap().to_str().unwrap(),
5812            "/custom/storage"
5813        );
5814        assert_eq!(config.wal_dir.unwrap().to_str().unwrap(), "/custom/wal");
5815    }
5816
5817    #[test]
5818    fn test_from_env_vars_wal_disabled() {
5819        let (config, mode) = EventStoreConfig::from_env_vars(
5820            Some("/app/data".to_string()),
5821            None,
5822            None,
5823            Some("false".to_string()),
5824            None,
5825            None,
5826            None,
5827            None,
5828        );
5829        assert_eq!(mode, "parquet-only");
5830        assert!(config.storage_dir.is_some());
5831        assert!(config.wal_dir.is_none());
5832    }
5833
5834    #[test]
5835    fn test_from_env_vars_no_dirs_is_in_memory() {
5836        let (config, mode) =
5837            EventStoreConfig::from_env_vars(None, None, None, None, None, None, None, None);
5838        assert_eq!(mode, "in-memory");
5839        assert!(config.storage_dir.is_none());
5840        assert!(config.wal_dir.is_none());
5841    }
5842
5843    #[test]
5844    fn test_from_env_vars_empty_strings_treated_as_none() {
5845        let (_, mode) = EventStoreConfig::from_env_vars(
5846            Some(String::new()),
5847            Some(String::new()),
5848            Some(String::new()),
5849            None,
5850            None,
5851            None,
5852            None,
5853            None,
5854        );
5855        assert_eq!(mode, "in-memory");
5856    }
5857
5858    #[test]
5859    fn test_from_env_vars_explicit_overrides_data_dir() {
5860        let (config, mode) = EventStoreConfig::from_env_vars(
5861            Some("/app/data".to_string()),
5862            Some("/override/storage".to_string()),
5863            Some("/override/wal".to_string()),
5864            None,
5865            None,
5866            None,
5867            None,
5868            None,
5869        );
5870        assert_eq!(mode, "wal+parquet");
5871        assert_eq!(
5872            config.storage_dir.unwrap().to_str().unwrap(),
5873            "/override/storage"
5874        );
5875        assert_eq!(config.wal_dir.unwrap().to_str().unwrap(), "/override/wal");
5876    }
5877
5878    #[test]
5879    fn test_from_env_vars_wal_only() {
5880        let (config, mode) = EventStoreConfig::from_env_vars(
5881            None,
5882            None,
5883            Some("/wal/only".to_string()),
5884            None,
5885            None,
5886            None,
5887            None,
5888            None,
5889        );
5890        assert_eq!(mode, "wal-only");
5891        assert!(config.storage_dir.is_none());
5892        assert_eq!(config.wal_dir.unwrap().to_str().unwrap(), "/wal/only");
5893    }
5894
5895    #[test]
5896    fn test_from_env_vars_cache_bytes_parses_decimal() {
5897        let (config, _) = EventStoreConfig::from_env_vars(
5898            Some("/app/data".to_string()),
5899            None,
5900            None,
5901            None,
5902            Some("536870912".to_string()),
5903            // 512 MiB
5904            None,
5905            None,
5906            None,
5907        );
5908        assert_eq!(config.cache_byte_budget, Some(536_870_912));
5909    }
5910
5911    #[test]
5912    fn test_from_env_vars_cache_bytes_unparseable_disables_budget() {
5913        // Garbage in CACHE_BYTES doesn't fail boot — we log and
5914        // fall back to no-budget. The unbounded fallback is safe
5915        // (just the pre-Step-3 behavior).
5916        let (config, _) = EventStoreConfig::from_env_vars(
5917            Some("/app/data".to_string()),
5918            None,
5919            None,
5920            None,
5921            Some("not-a-number".to_string()),
5922            None,
5923            None,
5924            None,
5925        );
5926        assert_eq!(config.cache_byte_budget, None);
5927    }
5928
5929    #[test]
5930    fn test_from_env_vars_cache_bytes_empty_disables_budget() {
5931        let (config, _) = EventStoreConfig::from_env_vars(
5932            Some("/app/data".to_string()),
5933            None,
5934            None,
5935            None,
5936            Some(String::new()),
5937            None,
5938            None,
5939            None,
5940        );
5941        assert_eq!(config.cache_byte_budget, None);
5942    }
5943
5944    #[test]
5945    fn test_from_env_vars_snapshot_interval_overrides_default() {
5946        // ALLSOURCE_SNAPSHOT_INTERVAL_SECONDS plumbs through to
5947        // CompactionConfig.compaction_interval_seconds. Default is
5948        // 3600s (hourly) per the bead.
5949        let (config, _) = EventStoreConfig::from_env_vars(
5950            Some("/app/data".to_string()),
5951            None,
5952            None,
5953            None,
5954            None,
5955            Some("60".to_string()),
5956            None,
5957            None,
5958        );
5959        assert_eq!(config.compaction_config.compaction_interval_seconds, 60);
5960    }
5961
5962    #[test]
5963    fn test_from_env_vars_snapshot_interval_default_is_hourly() {
5964        let (config, _) = EventStoreConfig::from_env_vars(
5965            Some("/app/data".to_string()),
5966            None,
5967            None,
5968            None,
5969            None,
5970            None,
5971            None,
5972            None,
5973        );
5974        assert_eq!(config.compaction_config.compaction_interval_seconds, 3600);
5975    }
5976
5977    #[test]
5978    fn test_from_env_vars_snapshot_interval_unparseable_falls_back() {
5979        let (config, _) = EventStoreConfig::from_env_vars(
5980            Some("/app/data".to_string()),
5981            None,
5982            None,
5983            None,
5984            None,
5985            Some("not-a-number".to_string()),
5986            None,
5987            None,
5988        );
5989        assert_eq!(config.compaction_config.compaction_interval_seconds, 3600);
5990    }
5991
5992    #[test]
5993    fn test_from_env_vars_retention_system_days_overrides_default() {
5994        // Step 5: ALLSOURCE_RETENTION_SYSTEM_DAYS overrides the
5995        // default 30-day TTL for the system tenant.
5996        let (config, _) = EventStoreConfig::from_env_vars(
5997            Some("/app/data".to_string()),
5998            None,
5999            None,
6000            None,
6001            None,
6002            None,
6003            Some("7".to_string()),
6004            None,
6005        );
6006        let ttl = config
6007            .compaction_config
6008            .retention
6009            .ttl_for("system")
6010            .unwrap();
6011        assert_eq!(ttl.as_secs(), 7 * 24 * 3600);
6012    }
6013
6014    #[test]
6015    fn test_from_env_vars_retention_default_is_30_days_for_system() {
6016        let (config, _) = EventStoreConfig::from_env_vars(
6017            Some("/app/data".to_string()),
6018            None,
6019            None,
6020            None,
6021            None,
6022            None,
6023            None,
6024            None,
6025        );
6026        let ttl = config
6027            .compaction_config
6028            .retention
6029            .ttl_for("system")
6030            .unwrap();
6031        assert_eq!(ttl.as_secs(), 30 * 24 * 3600);
6032        // Other tenants keep forever by default.
6033        assert!(config.compaction_config.retention.ttl_for("acme").is_none());
6034    }
6035
6036    #[test]
6037    fn test_store_stats_serde() {
6038        let stats = StoreStats {
6039            total_events: 100,
6040            total_entities: 50,
6041            total_event_types: 10,
6042            total_ingested: 100,
6043        };
6044
6045        let json = serde_json::to_string(&stats).unwrap();
6046        assert!(json.contains("\"total_events\":100"));
6047        assert!(json.contains("\"total_entities\":50"));
6048    }
6049
6050    #[test]
6051    fn test_query_with_entity_and_type() {
6052        let store = EventStore::new();
6053
6054        store
6055            .ingest(&create_test_event("entity-1", "user.created"))
6056            .unwrap();
6057        store
6058            .ingest(&create_test_event("entity-1", "user.updated"))
6059            .unwrap();
6060        store
6061            .ingest(&create_test_event("entity-2", "user.created"))
6062            .unwrap();
6063
6064        let results = store
6065            .query(&QueryEventsRequest {
6066                as_of_valid: None,
6067                since_valid: None,
6068                until_valid: None,
6069                entity_id: Some("entity-1".to_string()),
6070                event_type: Some("user.created".to_string()),
6071                tenant_id: None,
6072                as_of: None,
6073                since: None,
6074                until: None,
6075                limit: None,
6076                event_type_prefix: None,
6077                exclude_event_type_prefix: None,
6078                payload_filter: None,
6079            })
6080            .unwrap();
6081
6082        assert_eq!(results.len(), 1);
6083        assert_eq!(results[0].event_type_str(), "user.created");
6084    }
6085
6086    #[test]
6087    fn test_query_by_event_type_prefix() {
6088        let store = EventStore::new();
6089
6090        // Ingest events with various types
6091        store
6092            .ingest(&create_test_event("entity-1", "index.created"))
6093            .unwrap();
6094        store
6095            .ingest(&create_test_event("entity-2", "index.updated"))
6096            .unwrap();
6097        store
6098            .ingest(&create_test_event("entity-3", "trade.created"))
6099            .unwrap();
6100        store
6101            .ingest(&create_test_event("entity-4", "trade.completed"))
6102            .unwrap();
6103        store
6104            .ingest(&create_test_event("entity-5", "balance.updated"))
6105            .unwrap();
6106
6107        // Query with prefix "index." should return exactly 2
6108        let results = store
6109            .query(&QueryEventsRequest {
6110                as_of_valid: None,
6111                since_valid: None,
6112                until_valid: None,
6113                entity_id: None,
6114                event_type: None,
6115                tenant_id: None,
6116                as_of: None,
6117                since: None,
6118                until: None,
6119                limit: None,
6120                event_type_prefix: Some("index.".to_string()),
6121                exclude_event_type_prefix: None,
6122                payload_filter: None,
6123            })
6124            .unwrap();
6125
6126        assert_eq!(results.len(), 2);
6127        assert!(
6128            results
6129                .iter()
6130                .all(|e| e.event_type_str().starts_with("index."))
6131        );
6132    }
6133
6134    #[test]
6135    fn test_query_by_event_type_prefix_empty_returns_all() {
6136        let store = EventStore::new();
6137
6138        store
6139            .ingest(&create_test_event("entity-1", "index.created"))
6140            .unwrap();
6141        store
6142            .ingest(&create_test_event("entity-2", "trade.created"))
6143            .unwrap();
6144
6145        // Empty prefix matches all types
6146        let results = store
6147            .query(&QueryEventsRequest {
6148                as_of_valid: None,
6149                since_valid: None,
6150                until_valid: None,
6151                entity_id: None,
6152                event_type: None,
6153                tenant_id: None,
6154                as_of: None,
6155                since: None,
6156                until: None,
6157                limit: None,
6158                event_type_prefix: Some(String::new()),
6159                exclude_event_type_prefix: None,
6160                payload_filter: None,
6161            })
6162            .unwrap();
6163
6164        assert_eq!(results.len(), 2);
6165    }
6166
6167    #[test]
6168    fn test_query_by_event_type_prefix_no_match() {
6169        let store = EventStore::new();
6170
6171        store
6172            .ingest(&create_test_event("entity-1", "index.created"))
6173            .unwrap();
6174
6175        let results = store
6176            .query(&QueryEventsRequest {
6177                as_of_valid: None,
6178                since_valid: None,
6179                until_valid: None,
6180                entity_id: None,
6181                event_type: None,
6182                tenant_id: None,
6183                as_of: None,
6184                since: None,
6185                until: None,
6186                limit: None,
6187                event_type_prefix: Some("nonexistent.".to_string()),
6188                exclude_event_type_prefix: None,
6189                payload_filter: None,
6190            })
6191            .unwrap();
6192
6193        assert!(results.is_empty());
6194    }
6195
6196    #[test]
6197    fn test_query_by_entity_with_type_prefix() {
6198        let store = EventStore::new();
6199
6200        store
6201            .ingest(&create_test_event("entity-1", "index.created"))
6202            .unwrap();
6203        store
6204            .ingest(&create_test_event("entity-1", "trade.created"))
6205            .unwrap();
6206        store
6207            .ingest(&create_test_event("entity-2", "index.updated"))
6208            .unwrap();
6209
6210        // Query entity-1 with prefix "index." should return 1
6211        let results = store
6212            .query(&QueryEventsRequest {
6213                as_of_valid: None,
6214                since_valid: None,
6215                until_valid: None,
6216                entity_id: Some("entity-1".to_string()),
6217                event_type: None,
6218                tenant_id: None,
6219                as_of: None,
6220                since: None,
6221                until: None,
6222                limit: None,
6223                event_type_prefix: Some("index.".to_string()),
6224                exclude_event_type_prefix: None,
6225                payload_filter: None,
6226            })
6227            .unwrap();
6228
6229        assert_eq!(results.len(), 1);
6230        assert_eq!(results[0].event_type_str(), "index.created");
6231    }
6232
6233    #[test]
6234    fn test_query_prefix_with_limit() {
6235        let store = EventStore::new();
6236
6237        for i in 0..5 {
6238            store
6239                .ingest(&create_test_event(&format!("entity-{i}"), "index.created"))
6240                .unwrap();
6241        }
6242
6243        let results = store
6244            .query(&QueryEventsRequest {
6245                as_of_valid: None,
6246                since_valid: None,
6247                until_valid: None,
6248                entity_id: None,
6249                event_type: None,
6250                tenant_id: None,
6251                as_of: None,
6252                since: None,
6253                until: None,
6254                limit: Some(3),
6255                event_type_prefix: Some("index.".to_string()),
6256                exclude_event_type_prefix: None,
6257                payload_filter: None,
6258            })
6259            .unwrap();
6260
6261        assert_eq!(results.len(), 3);
6262    }
6263
6264    #[test]
6265    fn test_query_prefix_alongside_existing_filters() {
6266        let store = EventStore::new();
6267
6268        store
6269            .ingest(&create_test_event("entity-1", "index.created"))
6270            .unwrap();
6271        // Sleep briefly to ensure different timestamps
6272        std::thread::sleep(std::time::Duration::from_millis(10));
6273        store
6274            .ingest(&create_test_event("entity-2", "index.strategy.updated"))
6275            .unwrap();
6276        std::thread::sleep(std::time::Duration::from_millis(10));
6277        store
6278            .ingest(&create_test_event("entity-3", "index.deleted"))
6279            .unwrap();
6280
6281        // Prefix with limit
6282        let results = store
6283            .query(&QueryEventsRequest {
6284                as_of_valid: None,
6285                since_valid: None,
6286                until_valid: None,
6287                entity_id: None,
6288                event_type: None,
6289                tenant_id: None,
6290                as_of: None,
6291                since: None,
6292                until: None,
6293                limit: Some(2),
6294                event_type_prefix: Some("index.".to_string()),
6295                exclude_event_type_prefix: None,
6296                payload_filter: None,
6297            })
6298            .unwrap();
6299
6300        assert_eq!(results.len(), 2);
6301    }
6302
6303    #[test]
6304    fn test_query_with_payload_filter() {
6305        let store = EventStore::new();
6306
6307        // Ingest 5 events with user_id=alice
6308        for i in 0..5 {
6309            store
6310                .ingest(&create_test_event_with_payload(
6311                    &format!("entity-{i}"),
6312                    "user.action",
6313                    serde_json::json!({"user_id": "alice", "action": "click"}),
6314                ))
6315                .unwrap();
6316        }
6317        // Ingest 5 events with user_id=bob
6318        for i in 5..10 {
6319            store
6320                .ingest(&create_test_event_with_payload(
6321                    &format!("entity-{i}"),
6322                    "user.action",
6323                    serde_json::json!({"user_id": "bob", "action": "view"}),
6324                ))
6325                .unwrap();
6326        }
6327
6328        // Filter for alice
6329        let results = store
6330            .query(&QueryEventsRequest {
6331                as_of_valid: None,
6332                since_valid: None,
6333                until_valid: None,
6334                entity_id: None,
6335                event_type: Some("user.action".to_string()),
6336                tenant_id: None,
6337                as_of: None,
6338                since: None,
6339                until: None,
6340                limit: None,
6341                event_type_prefix: None,
6342                exclude_event_type_prefix: None,
6343                payload_filter: Some(r#"{"user_id":"alice"}"#.to_string()),
6344            })
6345            .unwrap();
6346
6347        assert_eq!(results.len(), 5);
6348    }
6349
6350    #[test]
6351    fn test_query_payload_filter_non_existent_field() {
6352        let store = EventStore::new();
6353
6354        store
6355            .ingest(&create_test_event_with_payload(
6356                "entity-1",
6357                "user.action",
6358                serde_json::json!({"user_id": "alice"}),
6359            ))
6360            .unwrap();
6361
6362        // Filter for a field that doesn't exist — returns 0, not error
6363        let results = store
6364            .query(&QueryEventsRequest {
6365                as_of_valid: None,
6366                since_valid: None,
6367                until_valid: None,
6368                entity_id: None,
6369                event_type: None,
6370                tenant_id: None,
6371                as_of: None,
6372                since: None,
6373                until: None,
6374                limit: None,
6375                event_type_prefix: None,
6376                exclude_event_type_prefix: None,
6377                payload_filter: Some(r#"{"nonexistent":"value"}"#.to_string()),
6378            })
6379            .unwrap();
6380
6381        assert!(results.is_empty());
6382    }
6383
6384    #[test]
6385    fn test_query_payload_filter_with_prefix() {
6386        let store = EventStore::new();
6387
6388        store
6389            .ingest(&create_test_event_with_payload(
6390                "entity-1",
6391                "index.created",
6392                serde_json::json!({"status": "active"}),
6393            ))
6394            .unwrap();
6395        store
6396            .ingest(&create_test_event_with_payload(
6397                "entity-2",
6398                "index.created",
6399                serde_json::json!({"status": "inactive"}),
6400            ))
6401            .unwrap();
6402        store
6403            .ingest(&create_test_event_with_payload(
6404                "entity-3",
6405                "trade.created",
6406                serde_json::json!({"status": "active"}),
6407            ))
6408            .unwrap();
6409
6410        // Combine prefix + payload filter
6411        let results = store
6412            .query(&QueryEventsRequest {
6413                as_of_valid: None,
6414                since_valid: None,
6415                until_valid: None,
6416                entity_id: None,
6417                event_type: None,
6418                tenant_id: None,
6419                as_of: None,
6420                since: None,
6421                until: None,
6422                limit: None,
6423                event_type_prefix: Some("index.".to_string()),
6424                exclude_event_type_prefix: None,
6425                payload_filter: Some(r#"{"status":"active"}"#.to_string()),
6426            })
6427            .unwrap();
6428
6429        assert_eq!(results.len(), 1);
6430        assert_eq!(results[0].entity_id().to_string(), "entity-1");
6431    }
6432
6433    #[test]
6434    fn test_flush_storage_no_storage() {
6435        let store = EventStore::new();
6436        // Without storage, flush should succeed (no-op)
6437        let result = store.flush_storage();
6438        assert!(result.is_ok());
6439    }
6440
6441    #[test]
6442    fn test_state_evolution() {
6443        let store = EventStore::new();
6444
6445        // Initial state
6446        store
6447            .ingest(
6448                &Event::from_strings(
6449                    "user.created".to_string(),
6450                    "user-1".to_string(),
6451                    "default".to_string(),
6452                    serde_json::json!({"name": "Alice", "age": 25}),
6453                    None,
6454                )
6455                .unwrap(),
6456            )
6457            .unwrap();
6458
6459        // Update state
6460        store
6461            .ingest(
6462                &Event::from_strings(
6463                    "user.updated".to_string(),
6464                    "user-1".to_string(),
6465                    "default".to_string(),
6466                    serde_json::json!({"age": 26}),
6467                    None,
6468                )
6469                .unwrap(),
6470            )
6471            .unwrap();
6472
6473        let state = store.reconstruct_state("user-1", None).unwrap();
6474        // The state is wrapped with metadata
6475        assert_eq!(state["current_state"]["name"], "Alice");
6476        assert_eq!(state["current_state"]["age"], 26);
6477    }
6478
6479    #[test]
6480    fn test_reject_system_event_types() {
6481        let store = EventStore::new();
6482
6483        // System event types should be rejected via user-facing ingestion
6484        let event = Event::reconstruct_from_strings(
6485            uuid::Uuid::new_v4(),
6486            "_system.tenant.created".to_string(),
6487            "_system:tenant:acme".to_string(),
6488            "_system".to_string(),
6489            serde_json::json!({"name": "ACME"}),
6490            chrono::Utc::now(),
6491            None,
6492            1,
6493        );
6494
6495        let result = store.ingest(&event);
6496        assert!(result.is_err());
6497        let err = result.unwrap_err();
6498        assert!(
6499            err.to_string().contains("reserved for internal use"),
6500            "Expected system namespace rejection, got: {err}"
6501        );
6502    }
6503
6504    // -----------------------------------------------------------------------
6505    // Crash recovery: WAL events survive restart via Parquet checkpoint.
6506    // Regression test for GitHub issue #84 — flush_storage() was a no-op
6507    // during recovery because events were never buffered into Parquet's
6508    // current_batch before flushing.
6509    // -----------------------------------------------------------------------
6510
6511    #[test]
6512    fn test_wal_recovery_checkpoints_to_parquet() {
6513        let data_dir = TempDir::new().unwrap();
6514        let storage_dir = data_dir.path().join("storage");
6515        let wal_dir = data_dir.path().join("wal");
6516
6517        // Session 1: ingest events with WAL + Parquet
6518        {
6519            let config = EventStoreConfig::production(
6520                &storage_dir,
6521                &wal_dir,
6522                WALConfig {
6523                    sync_on_write: true,
6524                    ..WALConfig::default()
6525                },
6526                CompactionConfig::default(),
6527            );
6528            let store = EventStore::with_config(config);
6529
6530            for i in 0..5 {
6531                let event = Event::from_strings(
6532                    "test.created".to_string(),
6533                    format!("entity-{i}"),
6534                    "default".to_string(),
6535                    serde_json::json!({"index": i}),
6536                    None,
6537                )
6538                .unwrap();
6539                store.ingest(&event).unwrap();
6540            }
6541
6542            assert_eq!(store.stats().total_events, 5);
6543
6544            // Do NOT call flush_storage or shutdown — simulate a crash.
6545            // Events are in WAL (sync_on_write: true) but NOT in Parquet.
6546        }
6547
6548        // Verify WAL file has data
6549        let wal_files: Vec<_> = std::fs::read_dir(&wal_dir)
6550            .unwrap()
6551            .filter_map(std::result::Result::ok)
6552            .filter(|e| e.path().extension().is_some_and(|ext| ext == "log"))
6553            .collect();
6554        assert!(!wal_files.is_empty(), "WAL file should exist");
6555        let wal_size = wal_files[0].metadata().unwrap().len();
6556        assert!(wal_size > 0, "WAL file should have data (got 0 bytes)");
6557
6558        // Session 2: reopen — recovery should checkpoint WAL to Parquet, then truncate
6559        {
6560            let config = EventStoreConfig::production(
6561                &storage_dir,
6562                &wal_dir,
6563                WALConfig {
6564                    sync_on_write: true,
6565                    ..WALConfig::default()
6566                },
6567                CompactionConfig::default(),
6568            );
6569            let store = EventStore::with_config(config);
6570
6571            // Events should be recovered
6572            assert_eq!(
6573                store.stats().total_events,
6574                5,
6575                "Session 2 should have all 5 events after WAL recovery"
6576            );
6577
6578            // Parquet should now have files (checkpoint happened).
6579            // After Step 1, files live under <root>/<tenant>/<yyyy-mm>/,
6580            // so walk recursively.
6581            let parquet_files = find_parquet_files(&storage_dir);
6582            assert!(
6583                !parquet_files.is_empty(),
6584                "Parquet file should exist after WAL checkpoint"
6585            );
6586        }
6587
6588        // Session 3: reopen again — events should be reachable via
6589        // lazy-load (Step 2: boot does not pre-load Parquet).
6590        {
6591            let config = EventStoreConfig::production(
6592                &storage_dir,
6593                &wal_dir,
6594                WALConfig {
6595                    sync_on_write: true,
6596                    ..WALConfig::default()
6597                },
6598                CompactionConfig::default(),
6599            );
6600            let store = EventStore::with_config(config);
6601
6602            // Boot is now O(1) — Parquet stays cold until first
6603            // per-tenant query. WAL was truncated in session 2,
6604            // so nothing is pre-loaded.
6605            assert_eq!(
6606                store.stats().total_events,
6607                0,
6608                "Session 3 boot should not pre-load Parquet (lazy-load mode)"
6609            );
6610
6611            // Trigger lazy load for the test tenant (events were
6612            // ingested with tenant_id=\"default\").
6613            store.ensure_tenant_loaded("default").unwrap();
6614            assert_eq!(
6615                store.stats().total_events,
6616                5,
6617                "Session 3 should have all 5 events after ensure_tenant_loaded"
6618            );
6619        }
6620    }
6621
6622    #[test]
6623    fn test_parquet_restore_surfaces_errors_not_silent() {
6624        // Write events with WAL+Parquet, flush to Parquet, then corrupt the
6625        // Parquet file. On reload, the error must be logged (not silently
6626        // swallowed as 0 events).
6627        let data_dir = TempDir::new().unwrap();
6628        let storage_dir = data_dir.path().join("storage");
6629        let wal_dir = data_dir.path().join("wal");
6630
6631        // Session 1: write events and flush to Parquet
6632        {
6633            let config = EventStoreConfig::production(
6634                &storage_dir,
6635                &wal_dir,
6636                WALConfig {
6637                    sync_on_write: true,
6638                    ..WALConfig::default()
6639                },
6640                CompactionConfig::default(),
6641            );
6642            let store = EventStore::with_config(config);
6643
6644            for i in 0..3 {
6645                let event = Event::from_strings(
6646                    "test.created".to_string(),
6647                    format!("entity-{i}"),
6648                    "default".to_string(),
6649                    serde_json::json!({"i": i}),
6650                    None,
6651                )
6652                .unwrap();
6653                store.ingest(&event).unwrap();
6654            }
6655
6656            store.flush_storage().unwrap();
6657            assert_eq!(store.stats().total_events, 3);
6658        }
6659
6660        // Verify parquet file exists. After Step 1 the file lives
6661        // under <root>/<tenant>/<yyyy-mm>/, so walk recursively.
6662        let parquet_files = find_parquet_files(&storage_dir);
6663        assert!(!parquet_files.is_empty(), "Parquet file must exist");
6664
6665        // Corrupt the parquet file
6666        std::fs::write(&parquet_files[0], b"corrupted data").unwrap();
6667
6668        // Truncate WAL so only Parquet matters
6669        for entry in std::fs::read_dir(&wal_dir).unwrap().flatten() {
6670            std::fs::write(entry.path(), b"").unwrap();
6671        }
6672
6673        // Session 2: reload — should NOT silently report 0 events.
6674        // The error is logged via tracing::error! which we can't capture in a
6675        // unit test, but we CAN verify the store has 0 events (previously this
6676        // looked identical to "no data on disk" — now there's an error log).
6677        // The key behavioral change is that with_config no longer uses a
6678        // let-chain that silently drops the Err variant.
6679        {
6680            let config = EventStoreConfig::production(
6681                &storage_dir,
6682                &wal_dir,
6683                WALConfig::default(),
6684                CompactionConfig::default(),
6685            );
6686            let store = EventStore::with_config(config);
6687
6688            // Store has 0 events because Parquet is corrupted — but the error
6689            // is now logged (not silently swallowed).
6690            assert_eq!(store.stats().total_events, 0);
6691        }
6692    }
6693
6694    // -----------------------------------------------------------------------
6695    // Step 6: Bounded WAL replay. Each successful checkpoint truncates the
6696    // WAL so cold-start replay is O(one checkpoint interval) regardless of
6697    // total dataset size.
6698    // -----------------------------------------------------------------------
6699
6700    /// Count entries in every WAL file under `wal_dir` (any line that
6701    /// parses as a valid JSON object — the line format is one
6702    /// JSON-serialized WALEntry per line, see WALFile::write_entry).
6703    fn count_wal_entries(wal_dir: &std::path::Path) -> usize {
6704        use std::io::{BufRead, BufReader};
6705        let mut total = 0usize;
6706        let Ok(entries) = std::fs::read_dir(wal_dir) else {
6707            return 0;
6708        };
6709        for entry in entries.flatten() {
6710            let path = entry.path();
6711            if path.extension().is_none_or(|e| e != "log") {
6712                continue;
6713            }
6714            let Ok(file) = std::fs::File::open(&path) else {
6715                continue;
6716            };
6717            for line in BufReader::new(file)
6718                .lines()
6719                .map_while(std::result::Result::ok)
6720            {
6721                if !line.trim().is_empty() {
6722                    total += 1;
6723                }
6724            }
6725        }
6726        total
6727    }
6728
6729    #[test]
6730    fn test_checkpoint_truncates_wal_after_flush() {
6731        // After a successful checkpoint, every previously-ingested event
6732        // should be in Parquet, and the WAL should be empty (truncated).
6733        // This is the load-bearing invariant for Step 6's bounded-replay
6734        // promise — without truncation, the WAL grows unboundedly.
6735        let data_dir = TempDir::new().unwrap();
6736        let storage_dir = data_dir.path().join("storage");
6737        let wal_dir = data_dir.path().join("wal");
6738
6739        let config = EventStoreConfig::production(
6740            &storage_dir,
6741            &wal_dir,
6742            WALConfig {
6743                sync_on_write: true,
6744                ..WALConfig::default()
6745            },
6746            CompactionConfig::default(),
6747        );
6748        let store = EventStore::with_config(config);
6749
6750        for i in 0..10 {
6751            let event = Event::from_strings(
6752                "test.created".to_string(),
6753                format!("entity-{i}"),
6754                "default".to_string(),
6755                serde_json::json!({"i": i}),
6756                None,
6757            )
6758            .unwrap();
6759            store.ingest(&event).unwrap();
6760        }
6761
6762        // Sanity: all 10 events are in the WAL pre-checkpoint.
6763        assert_eq!(
6764            count_wal_entries(&wal_dir),
6765            10,
6766            "WAL should have 10 events before checkpoint"
6767        );
6768
6769        store.checkpoint().unwrap();
6770
6771        assert_eq!(
6772            count_wal_entries(&wal_dir),
6773            0,
6774            "WAL should be empty after successful checkpoint"
6775        );
6776        let parquet_files = find_parquet_files(&storage_dir);
6777        assert!(!parquet_files.is_empty(), "Parquet should hold the events");
6778    }
6779
6780    #[test]
6781    fn test_replay_only_post_checkpoint_events_after_crash() {
6782        // Headline AC for the bead: write N events, checkpoint, write K
6783        // more, simulate a crash, restart, and verify only K events go
6784        // through replay (not N+K).
6785        //
6786        // Uses small N (50) and K (5) for test speed — the property
6787        // is the same as the spec's 1M+10k example, just scaled down.
6788        let data_dir = TempDir::new().unwrap();
6789        let storage_dir = data_dir.path().join("storage");
6790        let wal_dir = data_dir.path().join("wal");
6791
6792        let config_factory = || {
6793            EventStoreConfig::production(
6794                &storage_dir,
6795                &wal_dir,
6796                WALConfig {
6797                    sync_on_write: true,
6798                    ..WALConfig::default()
6799                },
6800                CompactionConfig::default(),
6801            )
6802        };
6803
6804        // Session 1: ingest N, checkpoint, ingest K, then drop without
6805        // a graceful shutdown — that's the crash.
6806        const N: usize = 50;
6807        const K: usize = 5;
6808        {
6809            let store = EventStore::with_config(config_factory());
6810            for i in 0..N {
6811                store
6812                    .ingest(
6813                        &Event::from_strings(
6814                            "pre.checkpoint".to_string(),
6815                            format!("e-{i}"),
6816                            "default".to_string(),
6817                            serde_json::json!({"i": i}),
6818                            None,
6819                        )
6820                        .unwrap(),
6821                    )
6822                    .unwrap();
6823            }
6824            store.checkpoint().unwrap();
6825            assert_eq!(
6826                count_wal_entries(&wal_dir),
6827                0,
6828                "WAL should be empty immediately after checkpoint"
6829            );
6830
6831            for i in 0..K {
6832                store
6833                    .ingest(
6834                        &Event::from_strings(
6835                            "post.checkpoint".to_string(),
6836                            format!("p-{i}"),
6837                            "default".to_string(),
6838                            serde_json::json!({"i": i}),
6839                            None,
6840                        )
6841                        .unwrap(),
6842                    )
6843                    .unwrap();
6844            }
6845            assert_eq!(
6846                count_wal_entries(&wal_dir),
6847                K,
6848                "WAL should hold only post-checkpoint events"
6849            );
6850            // Drop without flushing — simulates a crash mid-write.
6851        }
6852
6853        // Session 2: reopen. Recovery should replay only the K post-
6854        // checkpoint events from the WAL — the N pre-checkpoint events
6855        // are durable in Parquet and lazy-loaded on demand.
6856        {
6857            let store = EventStore::with_config(config_factory());
6858            // total_events reflects only WAL-recovered events at boot
6859            // (Step 2 — Parquet stays cold until first per-tenant
6860            // query). So the WAL replay size IS exactly K.
6861            assert_eq!(
6862                store.stats().total_events,
6863                K,
6864                "Boot should replay exactly K events from WAL (the post-checkpoint window), not N+K"
6865            );
6866
6867            // Lazy-load brings the rest in.
6868            store.ensure_tenant_loaded("default").unwrap();
6869            assert_eq!(
6870                store.stats().total_events,
6871                N + K,
6872                "After lazy-load, both pre- and post-checkpoint events should be reachable"
6873            );
6874        }
6875    }
6876
6877    #[test]
6878    fn test_checkpoint_is_idempotent() {
6879        // Calling checkpoint() twice in a row is safe: the second call
6880        // finds an empty WAL and an empty Parquet batch, and no-ops.
6881        let data_dir = TempDir::new().unwrap();
6882        let storage_dir = data_dir.path().join("storage");
6883        let wal_dir = data_dir.path().join("wal");
6884
6885        let store = EventStore::with_config(EventStoreConfig::production(
6886            &storage_dir,
6887            &wal_dir,
6888            WALConfig::default(),
6889            CompactionConfig::default(),
6890        ));
6891
6892        for i in 0..5 {
6893            store
6894                .ingest(
6895                    &Event::from_strings(
6896                        "x".to_string(),
6897                        format!("e-{i}"),
6898                        "default".to_string(),
6899                        serde_json::json!({}),
6900                        None,
6901                    )
6902                    .unwrap(),
6903                )
6904                .unwrap();
6905        }
6906
6907        store.checkpoint().unwrap();
6908        // Second call is a no-op and must not error.
6909        store.checkpoint().unwrap();
6910        assert_eq!(count_wal_entries(&wal_dir), 0);
6911    }
6912
6913    #[test]
6914    fn test_checkpoint_noop_in_memory_only_mode() {
6915        // Without WAL configured, checkpoint() is a no-op.
6916        let store = EventStore::new();
6917        store.checkpoint().unwrap();
6918    }
6919
6920    #[test]
6921    fn test_checkpoint_interval_from_env_defaults_to_60s_when_wal_enabled() {
6922        let (config, _) = EventStoreConfig::from_env_vars(
6923            Some("/app/data".to_string()),
6924            None,
6925            None,
6926            None,
6927            None,
6928            None,
6929            None,
6930            None,
6931        );
6932        assert_eq!(config.checkpoint_interval_secs, Some(60));
6933    }
6934
6935    #[test]
6936    fn test_checkpoint_interval_from_env_overrides_default() {
6937        let (config, _) = EventStoreConfig::from_env_vars(
6938            Some("/app/data".to_string()),
6939            None,
6940            None,
6941            None,
6942            None,
6943            None,
6944            None,
6945            Some("15".to_string()),
6946        );
6947        assert_eq!(config.checkpoint_interval_secs, Some(15));
6948    }
6949
6950    #[test]
6951    fn test_checkpoint_interval_disabled_when_wal_disabled() {
6952        // No WAL → no checkpoint loop, regardless of env var value.
6953        let (config, _) = EventStoreConfig::from_env_vars(
6954            Some("/app/data".to_string()),
6955            None,
6956            None,
6957            Some("false".to_string()),
6958            None,
6959            None,
6960            None,
6961            Some("15".to_string()),
6962        );
6963        assert_eq!(config.checkpoint_interval_secs, None);
6964    }
6965
6966    #[test]
6967    fn test_checkpoint_interval_unparseable_falls_back_to_default() {
6968        let (config, _) = EventStoreConfig::from_env_vars(
6969            Some("/app/data".to_string()),
6970            None,
6971            None,
6972            None,
6973            None,
6974            None,
6975            None,
6976            Some("not-a-number".to_string()),
6977        );
6978        assert_eq!(config.checkpoint_interval_secs, Some(60));
6979    }
6980
6981    // ── Tenant-scoped stats + state reconstruction (#230) ──────────────────
6982    //
6983    // `stats()` and `reconstruct_state()` are global. The gateway exposes the
6984    // scoped variants below to tenants, so cross-tenant isolation is the
6985    // property that matters most here.
6986
6987    fn seed_two_tenants() -> EventStore {
6988        let store = EventStore::new();
6989
6990        // alice: 3 events, 2 entities, 2 types
6991        for (entity, etype, payload) in [
6992            (
6993                "a-1",
6994                "created",
6995                serde_json::json!({"colour": "red", "size": 1}),
6996            ),
6997            ("a-1", "updated", serde_json::json!({"colour": "blue"})),
6998            ("a-2", "created", serde_json::json!({"colour": "green"})),
6999        ] {
7000            store
7001                .ingest(
7002                    &Event::from_strings(
7003                        etype.to_string(),
7004                        entity.to_string(),
7005                        "alice".to_string(),
7006                        payload,
7007                        None,
7008                    )
7009                    .unwrap(),
7010                )
7011                .unwrap();
7012        }
7013
7014        // bob: 1 event, and it deliberately reuses alice's entity_id "a-1"
7015        store
7016            .ingest(
7017                &Event::from_strings(
7018                    "created".to_string(),
7019                    "a-1".to_string(),
7020                    "bob".to_string(),
7021                    serde_json::json!({"colour": "BOB_SECRET", "bob_only": true}),
7022                    None,
7023                )
7024                .unwrap(),
7025            )
7026            .unwrap();
7027
7028        store
7029    }
7030
7031    #[test]
7032    fn test_stats_for_tenant_counts_only_that_tenant() {
7033        let store = seed_two_tenants();
7034
7035        let alice = store.stats_for_tenant("alice").unwrap();
7036        assert_eq!(alice.total_events, 3);
7037        assert_eq!(alice.total_entities, 2);
7038        assert_eq!(alice.total_event_types, 2);
7039        assert_eq!(alice.event_types.get("created"), Some(&2));
7040        assert_eq!(alice.event_types.get("updated"), Some(&1));
7041
7042        let bob = store.stats_for_tenant("bob").unwrap();
7043        assert_eq!(bob.total_events, 1);
7044        assert_eq!(bob.total_entities, 1);
7045        assert_eq!(bob.total_event_types, 1);
7046    }
7047
7048    #[test]
7049    fn test_stats_for_tenant_never_reports_global_totals() {
7050        let store = seed_two_tenants();
7051
7052        // The global view sees all 4; neither tenant may.
7053        assert_eq!(store.stats().total_events, 4);
7054        assert_eq!(store.stats_for_tenant("alice").unwrap().total_events, 3);
7055        assert_eq!(store.stats_for_tenant("bob").unwrap().total_events, 1);
7056
7057        // total_ingested is a global process counter, so the scoped form must
7058        // report the tenant's own total rather than leaking the fleet tally.
7059        assert_eq!(store.stats_for_tenant("bob").unwrap().total_ingested, 1);
7060    }
7061
7062    #[test]
7063    fn test_stats_for_tenant_unknown_tenant_is_empty_not_global() {
7064        let store = seed_two_tenants();
7065        let nobody = store.stats_for_tenant("does-not-exist").unwrap();
7066
7067        assert_eq!(nobody.total_events, 0);
7068        assert_eq!(nobody.total_entities, 0);
7069        assert!(nobody.event_types.is_empty());
7070        assert!(nobody.oldest_event.is_none());
7071        assert!(nobody.newest_event.is_none());
7072    }
7073
7074    #[test]
7075    fn test_stats_for_tenant_reports_time_range() {
7076        let store = seed_two_tenants();
7077        let alice = store.stats_for_tenant("alice").unwrap();
7078
7079        let oldest = alice.oldest_event.expect("oldest");
7080        let newest = alice.newest_event.expect("newest");
7081        assert!(oldest <= newest);
7082    }
7083
7084    #[test]
7085    fn test_reconstruct_state_for_tenant_isolates_shared_entity_id() {
7086        let store = seed_two_tenants();
7087
7088        // Both tenants have an entity called "a-1". Each must see only its own.
7089        let alice = store
7090            .reconstruct_state_for_tenant("a-1", None, "alice")
7091            .unwrap();
7092        let alice_state = alice.get("current_state").unwrap();
7093        assert_eq!(alice_state.get("colour").unwrap(), "blue"); // last write wins
7094        assert_eq!(alice_state.get("size").unwrap(), 1);
7095        assert!(
7096            alice_state.get("bob_only").is_none(),
7097            "alice must not see bob's payload keys: {alice_state:?}"
7098        );
7099        assert_eq!(alice.get("event_count").unwrap(), 2);
7100
7101        let bob = store
7102            .reconstruct_state_for_tenant("a-1", None, "bob")
7103            .unwrap();
7104        let bob_state = bob.get("current_state").unwrap();
7105        assert_eq!(bob_state.get("colour").unwrap(), "BOB_SECRET");
7106        assert_eq!(bob.get("event_count").unwrap(), 1);
7107    }
7108
7109    #[test]
7110    fn test_reconstruct_state_for_tenant_rejects_another_tenants_entity() {
7111        let store = seed_two_tenants();
7112
7113        // "a-2" belongs to alice only.
7114        assert!(
7115            store
7116                .reconstruct_state_for_tenant("a-2", None, "alice")
7117                .is_ok()
7118        );
7119        assert!(
7120            store
7121                .reconstruct_state_for_tenant("a-2", None, "bob")
7122                .is_err(),
7123            "bob must not be able to read alice's entity"
7124        );
7125    }
7126
7127    #[test]
7128    fn test_global_reconstruct_state_still_spans_tenants() {
7129        // The unscoped form is unchanged — it is the internal/admin path and the
7130        // gateway never exposes it without a tenant_id.
7131        let store = seed_two_tenants();
7132        let all = store.reconstruct_state("a-1", None).unwrap();
7133        assert_eq!(all.get("event_count").unwrap(), 3);
7134    }
7135
7136    // -----------------------------------------------------------------
7137    // Issue #251: `limit` must bound the store's work, not just its
7138    // response. These guards count `Event` CLONES (crate::clone_probe),
7139    // not returned rows — `query_results_total` is incremented with
7140    // `results.len()`, so it reads 1 both when the store clones one event
7141    // and when it clones the whole history and throws the rest away.
7142    // Revert `query_window` to "clone every match, sort all N, truncate"
7143    // and these go red; row-shaped assertions alone would not.
7144    // -----------------------------------------------------------------
7145
7146    fn seed_hot_entity(history: usize) -> EventStore {
7147        let store = EventStore::new();
7148        for _ in 0..history {
7149            store
7150                .ingest(&create_test_event("entity-hot", "user.updated"))
7151                .unwrap();
7152        }
7153        store
7154    }
7155
7156    fn hot_request(limit: Option<usize>) -> QueryEventsRequest {
7157        QueryEventsRequest {
7158            as_of_valid: None,
7159            since_valid: None,
7160            until_valid: None,
7161            entity_id: Some("entity-hot".to_string()),
7162            limit,
7163            ..QueryEventsRequest::default()
7164        }
7165    }
7166
7167    #[test]
7168    fn query_window_limit_bounds_materialization_not_just_the_response() {
7169        const HISTORY: usize = 400;
7170        let store = seed_hot_entity(HISTORY);
7171
7172        // The documented "latest event for an entity" read.
7173        let ((page, total), materialized) = crate::clone_probe::measure(|| {
7174            store.query_window(&hot_request(Some(1)), 0, true).unwrap()
7175        });
7176        assert_eq!(page.len(), 1, "limit=1 returns one event");
7177        assert_eq!(total, HISTORY, "total is still the full match count");
7178        assert_eq!(
7179            materialized, 1,
7180            "limit=1 cloned {materialized} of {HISTORY} events: `limit` must \
7181             bound what the store materializes, not just what it returns"
7182        );
7183
7184        // An offset page materializes the page, not everything up to it.
7185        let ((page, _), materialized) = crate::clone_probe::measure(|| {
7186            store
7187                .query_window(&hot_request(Some(5)), 300, false)
7188                .unwrap()
7189        });
7190        assert_eq!(page.len(), 5);
7191        assert_eq!(
7192            materialized, 5,
7193            "offset=300&limit=5 cloned {materialized} events, expected 5"
7194        );
7195
7196        // The unbounded query legitimately materializes everything — the
7197        // ceiling only applies where the caller asked for a window.
7198        let ((all, _), materialized) = crate::clone_probe::measure(|| {
7199            store.query_window(&hot_request(None), 0, true).unwrap()
7200        });
7201        assert_eq!(all.len(), HISTORY);
7202        assert_eq!(materialized, HISTORY as u64);
7203    }
7204
7205    #[test]
7206    fn query_window_cost_does_not_grow_with_entity_history() {
7207        // The same bounded page against a 10x longer history. Materialization
7208        // is bounded by the window, so history length must not show up in the
7209        // clone count — only the O(N) index scan that `total` inherently needs
7210        // still scales, and that clones no events.
7211        let short = seed_hot_entity(40);
7212        let long = seed_hot_entity(400);
7213
7214        let (_, short_cost) = crate::clone_probe::measure(|| {
7215            short.query_window(&hot_request(Some(1)), 0, true).unwrap()
7216        });
7217        let (_, long_cost) = crate::clone_probe::measure(|| {
7218            long.query_window(&hot_request(Some(1)), 0, true).unwrap()
7219        });
7220
7221        assert_eq!(
7222            (short_cost, long_cost),
7223            (1, 1),
7224            "a limit=1 page materialized {short_cost} events over a 40-event \
7225             history and {long_cost} over 400 — cost is tracking history length"
7226        );
7227    }
7228
7229    #[test]
7230    fn select_window_orders_only_the_window() {
7231        // The complexity claim in `select_window`'s doc comment, made
7232        // observable: counting comparisons. A full sort of N items costs
7233        // ~N·log2(N); partial selection of a small window costs ~N. Replace the
7234        // `select_nth_unstable_by` with a plain `sort_unstable_by` over all N
7235        // and the ratio collapses, failing this test.
7236        use std::cell::Cell;
7237        const N: usize = 4096;
7238
7239        let comparisons = Cell::new(0usize);
7240        let order = |a: &u64, b: &u64| {
7241            comparisons.set(comparisons.get() + 1);
7242            a.cmp(b)
7243        };
7244        let shuffled = || -> Vec<u64> {
7245            (0..N as u64)
7246                .map(|i| (i * 2_654_435_761) % 1_000_003)
7247                .collect()
7248        };
7249
7250        let mut bounded = shuffled();
7251        select_window(&mut bounded, 0, Some(1), order);
7252        let bounded_cost = comparisons.replace(0);
7253        assert_eq!(bounded.len(), 1, "window of 1 keeps 1 item");
7254
7255        let mut everything = shuffled();
7256        select_window(&mut everything, 0, None, order);
7257        let full_sort_cost = comparisons.get();
7258        assert_eq!(everything.len(), N);
7259
7260        assert!(
7261            bounded_cost < 4 * N,
7262            "selecting a 1-item window out of {N} took {bounded_cost} comparisons \
7263             (~{}·N) — that is sort-shaped, not selection-shaped",
7264            bounded_cost / N
7265        );
7266        assert!(
7267            bounded_cost * 3 < full_sort_cost,
7268            "a 1-item window cost {bounded_cost} comparisons against \
7269             {full_sort_cost} for sorting all {N}: the window is not bounding \
7270             the ordering work"
7271        );
7272    }
7273
7274    #[test]
7275    fn select_window_is_equivalent_to_sort_then_window() {
7276        // Exhaustive small-input check that partial selection cannot diverge
7277        // from sort-then-window, including duplicate keys (the total order is
7278        // supplied by the caller — here (key, position)).
7279        let order = |a: &(u32, usize), b: &(u32, usize)| a.cmp(b);
7280        let source: Vec<(u32, usize)> = [7, 3, 3, 9, 1, 3, 5, 9, 0, 2]
7281            .into_iter()
7282            .enumerate()
7283            .map(|(i, k)| (k, i))
7284            .collect();
7285
7286        let mut sorted = source.clone();
7287        sorted.sort_by(order);
7288
7289        for offset in 0..12 {
7290            for limit in [None, Some(0), Some(1), Some(3), Some(10), Some(50)] {
7291                let mut got = source.clone();
7292                select_window(&mut got, offset, limit, order);
7293                let got: Vec<_> = got.into_iter().skip(offset).collect();
7294                let expected: Vec<_> = sorted
7295                    .iter()
7296                    .copied()
7297                    .skip(offset)
7298                    .take(limit.unwrap_or(usize::MAX))
7299                    .collect();
7300                assert_eq!(got, expected, "offset={offset} limit={limit:?}");
7301            }
7302        }
7303    }
7304
7305    // `as_of`/`since`/`until` are applied in `filter_entries`, which only runs
7306    // on the three INDEXED branches (entity_id / event_type / event_type_prefix).
7307    // The full-scan branch — a query scoped only by tenant, or only by
7308    // `payload_filter`/`exclude_event_type_prefix`, which is exactly what the
7309    // gateway sends for "this tenant's activity since T" — builds its offsets
7310    // as `(0..events.len())` and never calls it, and `apply_filters` did not
7311    // check timestamps either. So the time window was silently dropped: the
7312    // query returned the whole history, and `total`/`has_more` described that
7313    // whole history too. Same class of "the parameter never reaches the code
7314    // that would honour it" as #250's offset.
7315    #[test]
7316    fn query_window_applies_time_filters_on_the_full_scan_path() {
7317        let store = EventStore::new();
7318        let base = Utc::now() - chrono::Duration::hours(24);
7319        let mut ids = Vec::new();
7320        for i in 0..5i64 {
7321            let mut event = create_test_event(&format!("e-{i}"), "user.created");
7322            event.timestamp = base + chrono::Duration::hours(i);
7323            event.version = i + 1;
7324            ids.push(event.id);
7325            store.ingest(&event).unwrap();
7326        }
7327        let at = |h: i64| base + chrono::Duration::hours(h);
7328
7329        // Tenant-only: no entity_id, no event_type, no event_type_prefix, so
7330        // nothing narrows the scan.
7331        let scoped = |mutate: &dyn Fn(&mut QueryEventsRequest)| {
7332            let mut req = QueryEventsRequest {
7333                as_of_valid: None,
7334                since_valid: None,
7335                until_valid: None,
7336                tenant_id: Some("default".to_string()),
7337                ..QueryEventsRequest::default()
7338            };
7339            mutate(&mut req);
7340            req
7341        };
7342
7343        for (label, req, expected) in [
7344            (
7345                "since=T+2 keeps only events at or after T+2",
7346                scoped(&|r| r.since = Some(at(2))),
7347                vec![ids[2], ids[3], ids[4]],
7348            ),
7349            (
7350                "until=T+1 keeps only events at or before T+1",
7351                scoped(&|r| r.until = Some(at(1))),
7352                vec![ids[0], ids[1]],
7353            ),
7354            (
7355                "as_of=T+1 is time travel: nothing newer than T+1",
7356                scoped(&|r| r.as_of = Some(at(1))),
7357                vec![ids[0], ids[1]],
7358            ),
7359            (
7360                "since+until compose into a closed window",
7361                scoped(&|r| {
7362                    r.since = Some(at(1));
7363                    r.until = Some(at(3));
7364                }),
7365                vec![ids[1], ids[2], ids[3]],
7366            ),
7367        ] {
7368            let (events, total) = store.query_window(&req, 0, false).unwrap();
7369            let got: Vec<_> = events.iter().map(|e| e.id).collect();
7370            assert_eq!(got, expected, "{label}");
7371            assert_eq!(
7372                total,
7373                expected.len(),
7374                "{label}: total counts the events INSIDE the window — \
7375                 has_more is derived from it, so a full-history total makes a \
7376                 paginator walk events the caller filtered out"
7377            );
7378        }
7379
7380        // The indexed branches must keep agreeing with the full scan — the same
7381        // window asked for with an entity filter is the same window.
7382        let (indexed, total) = store
7383            .query_window(
7384                &scoped(&|r| {
7385                    r.entity_id = Some("e-3".to_string());
7386                    r.since = Some(at(2));
7387                }),
7388                0,
7389                false,
7390            )
7391            .unwrap();
7392        assert_eq!(
7393            indexed.iter().map(|e| e.id).collect::<Vec<_>>(),
7394            vec![ids[3]]
7395        );
7396        assert_eq!(total, 1);
7397
7398        // And the window composes with the #251 selection: a bounded page taken
7399        // out of a time window is a page of that window, not of the history.
7400        let (page, total) = store
7401            .query_window(&scoped(&|r| r.since = Some(at(2))), 1, true)
7402            .unwrap();
7403        assert_eq!(
7404            page.iter().map(|e| e.id).collect::<Vec<_>>(),
7405            vec![ids[3], ids[2]],
7406            "order=desc + offset=1 inside a since window"
7407        );
7408        assert_eq!(total, 3);
7409    }
7410
7411    #[test]
7412    fn valid_time_axes_agree_across_index_and_full_scan_paths() {
7413        let store = EventStore::new();
7414        let base = Utc::now() - chrono::Duration::hours(24);
7415        let at = |minutes: i64| base + chrono::Duration::minutes(minutes);
7416        // (recorded, valid_from, valid_to) in minutes from `base`. The last
7417        // fact is a backdated correction: filed at 300, true from 90.
7418        let facts = [
7419            (0, None, None),
7420            (60, Some(60), None),
7421            (120, Some(0), Some(120)),
7422            (240, Some(180), None),
7423            (300, Some(90), None),
7424        ];
7425        let mut ids = Vec::new();
7426        for (i, (recorded, valid_from, valid_to)) in facts.into_iter().enumerate() {
7427            let mut event = create_test_event("e-1", "user.created");
7428            event.timestamp = at(recorded);
7429            event.version = i as i64 + 1;
7430            let event = event
7431                .with_valid_time(valid_from.map(&at), valid_to.map(&at))
7432                .unwrap();
7433            ids.push(event.id);
7434            store.ingest(&event).unwrap();
7435        }
7436
7437        // Each query runs through the entity, type, type-prefix and tenant-only
7438        // (full scan) branches; all four must return the same set.
7439        let paths: [fn(&mut QueryEventsRequest); 4] = [
7440            |r| r.entity_id = Some("e-1".to_string()),
7441            |r| r.event_type = Some("user.created".to_string()),
7442            |r| r.event_type_prefix = Some("user.".to_string()),
7443            |_| {},
7444        ];
7445        let check =
7446            |label: &str, mutate: &dyn Fn(&mut QueryEventsRequest), expected: Vec<uuid::Uuid>| {
7447                let mut want = expected;
7448                want.sort();
7449                for path in paths {
7450                    let mut req = QueryEventsRequest {
7451                        as_of_valid: None,
7452                        since_valid: None,
7453                        until_valid: None,
7454                        tenant_id: Some("default".to_string()),
7455                        ..QueryEventsRequest::default()
7456                    };
7457                    path(&mut req);
7458                    mutate(&mut req);
7459                    let (events, _) = store.query_window(&req, 0, false).unwrap();
7460                    let mut got: Vec<uuid::Uuid> = events.iter().map(|e| e.id).collect();
7461                    got.sort();
7462                    assert_eq!(got, want, "{label} via {req:?}");
7463                }
7464            };
7465
7466        check(
7467            "as_of_valid inside an open fact and a closed one",
7468            &|r| r.as_of_valid = Some(at(72)),
7469            vec![ids[0], ids[1], ids[2]],
7470        );
7471        check(
7472            "as_of_valid excludes a fact whose valid_to equals the instant",
7473            &|r| r.as_of_valid = Some(at(120)),
7474            vec![ids[0], ids[1], ids[4]],
7475        );
7476        check(
7477            "backdated correction is invisible to a record bound before it was filed",
7478            &|r| {
7479                r.as_of = Some(at(270));
7480                r.as_of_valid = Some(at(210));
7481            },
7482            vec![ids[0], ids[1], ids[3]],
7483        );
7484        check(
7485            "since_valid is inclusive on valid_from",
7486            &|r| r.since_valid = Some(at(90)),
7487            vec![ids[3], ids[4]],
7488        );
7489        check(
7490            "until_valid is inclusive on valid_from",
7491            &|r| r.until_valid = Some(at(60)),
7492            vec![ids[0], ids[1], ids[2]],
7493        );
7494        check(
7495            "since_valid and until_valid compose",
7496            &|r| {
7497                r.since_valid = Some(at(60));
7498                r.until_valid = Some(at(90));
7499            },
7500            vec![ids[1], ids[4]],
7501        );
7502        check(
7503            "as_of_valid at the base instant",
7504            &|r| r.as_of_valid = Some(at(0)),
7505            vec![ids[0], ids[2]],
7506        );
7507        check(
7508            "record axis is unchanged: as_of bounds recorded time",
7509            &|r| r.as_of = Some(at(240)),
7510            vec![ids[0], ids[1], ids[2], ids[3]],
7511        );
7512        check(
7513            "record axis is unchanged: since bounds recorded time",
7514            &|r| r.since = Some(at(240)),
7515            vec![ids[3], ids[4]],
7516        );
7517    }
7518
7519    #[test]
7520    fn query_window_bounded_selection_matches_a_full_sort() {
7521        // Bounded selection (partial select + sort of the window only) must be
7522        // observationally identical to sort-everything-then-window, including
7523        // ties and the descending path — otherwise the perf win silently
7524        // changes pagination.
7525        let store = EventStore::new();
7526        for i in 0..50 {
7527            store
7528                .ingest(&create_test_event(&format!("e-{i:02}"), "user.created"))
7529                .unwrap();
7530        }
7531        let all = |descending: bool| {
7532            let (events, _) = store
7533                .query_window(&QueryEventsRequest::default(), 0, descending)
7534                .unwrap();
7535            events
7536        };
7537
7538        for descending in [false, true] {
7539            let reference = all(descending);
7540            for offset in [0, 1, 7, 49, 50, 100] {
7541                for limit in [1, 3, 10, 50, 100] {
7542                    let (page, total) = store
7543                        .query_window(
7544                            &QueryEventsRequest {
7545                                as_of_valid: None,
7546                                since_valid: None,
7547                                until_valid: None,
7548                                limit: Some(limit),
7549                                ..QueryEventsRequest::default()
7550                            },
7551                            offset,
7552                            descending,
7553                        )
7554                        .unwrap();
7555                    let expected: Vec<_> = reference
7556                        .iter()
7557                        .skip(offset)
7558                        .take(limit)
7559                        .map(|e| e.id)
7560                        .collect();
7561                    let got: Vec<_> = page.iter().map(|e| e.id).collect();
7562                    assert_eq!(
7563                        got, expected,
7564                        "desc={descending} offset={offset} limit={limit}: windowed \
7565                         selection must match a full sort"
7566                    );
7567                    assert_eq!(total, 50, "total is always the full match count");
7568                }
7569            }
7570        }
7571    }
7572}