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