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