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