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