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