Skip to main content

reddb_server/
runtime.rs

1//! Embedded runtime with connection pooling, scans and health.
2
3use std::cmp::Ordering;
4use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
5use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
6use std::sync::{Arc, Mutex};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use crate::api::{RedDBError, RedDBOptions, RedDBResult};
10use crate::catalog::{
11    CatalogAnalyticsJobStatus, CatalogAttentionSummary, CatalogGraphProjectionStatus,
12    CatalogIndexStatus, CatalogModelSnapshot, CollectionDescriptor,
13};
14use crate::health::{HealthProvider, HealthReport};
15use crate::index::IndexCatalog;
16use crate::physical::{
17    ExportDescriptor, ManifestEvent, PhysicalAnalyticsJob, PhysicalGraphProjection, PhysicalLayout,
18    SnapshotDescriptor,
19};
20use crate::serde_json::Value as JsonValue;
21use crate::storage::engine::pathfinding::{AStar, BellmanFord, Dijkstra, BFS, DFS};
22use crate::storage::engine::{
23    BetweennessCentrality, ClosenessCentrality, ClusteringCoefficient, ConnectedComponents,
24    CycleDetector, DegreeCentrality, EigenvectorCentrality, GraphStore, IvfConfig, IvfIndex,
25    IvfStats, LabelPropagation, Louvain, MetadataEntry, MetadataFilter as VectorMetadataFilter,
26    MetadataValue as VectorMetadataValue, PageRank, PersonalizedPageRank, PhysicalFileHeader,
27    StoredNode, StronglyConnectedComponents, WeaklyConnectedComponents, HITS,
28};
29use crate::storage::query::is_universal_entity_source as is_universal_query_source;
30use crate::storage::query::planner::{
31    CanonicalLogicalPlan, CanonicalPlanner, CostEstimator, QueryPlanner,
32};
33use crate::storage::query::unified::{UnifiedRecord, UnifiedResult};
34use crate::storage::unified::dsl::{
35    apply_filters, cosine_similarity, Filter as DslFilter, FilterOp as DslFilterOp,
36    FilterValue as DslFilterValue, GraphPatternDsl, HybridQueryBuilder, MatchComponents,
37    QueryResult as DslQueryResult, ScoredMatch, TextSearchBuilder,
38};
39use crate::storage::unified::store::{
40    NativeCatalogSummary, NativeManifestSummary, NativePhysicalState, NativeRecoverySummary,
41    NativeRegistrySummary,
42};
43use crate::storage::unified::{
44    Metadata, MetadataValue as UnifiedMetadataValue, RefTarget, UnifiedMetadataFilter,
45};
46use crate::storage::{
47    EntityData, EntityId, EntityKind, RedDB, RefType, SimilarResult, StoreStats, UnifiedEntity,
48    UnifiedStore,
49};
50use reddb_rql::ast::{
51    AlterOperation, AlterQueueQuery, AlterTableQuery, CompareOp, CreateCollectionQuery,
52    CreateIndexQuery, CreateQueueQuery, CreateTableQuery, CreateTimeSeriesQuery, CreateTreeQuery,
53    CreateVectorQuery, DeleteQuery, DropCollectionQuery, DropDocumentQuery, DropForkQuery,
54    DropGraphQuery, DropIndexQuery, DropKvQuery, DropQueueQuery, DropTableQuery,
55    DropTimeSeriesQuery, DropTreeQuery, DropVectorQuery, EventsBackfillQuery, ExplainAlterQuery,
56    ExplainFormat, FieldRef, Filter, ForkStoreQuery, FusionStrategy, GraphCommand, HybridQuery,
57    IndexMethod, InsertEntityType, InsertQuery, JoinQuery, JoinType, OrderByClause,
58    ProbabilisticCommand, Projection, PromoteForkQuery, QueryExpr, QueueCommand, QueueSelectQuery,
59    QueueSide, SearchCommand, TableQuery, TreeCommand, TruncateQuery, UpdateQuery, VectorQuery,
60    VectorSource,
61};
62use reddb_rql::modes::{detect_mode, parse_multi, QueryMode};
63use reddb_types::Value;
64
65static TIMESERIES_TAG_INDEX_OBSERVED_POINTS: AtomicU64 = AtomicU64::new(0);
66
67pub fn reset_timeseries_tag_index_observability() {
68    TIMESERIES_TAG_INDEX_OBSERVED_POINTS.store(0, AtomicOrdering::Relaxed);
69}
70
71pub fn timeseries_tag_index_observed_points() -> u64 {
72    TIMESERIES_TAG_INDEX_OBSERVED_POINTS.load(AtomicOrdering::Relaxed)
73}
74
75pub(crate) fn observe_timeseries_tag_index_point() {
76    TIMESERIES_TAG_INDEX_OBSERVED_POINTS.fetch_add(1, AtomicOrdering::Relaxed);
77}
78
79#[derive(Debug, Clone)]
80pub struct ConnectionPoolConfig {
81    pub max_connections: usize,
82    pub max_idle: usize,
83}
84
85impl Default for ConnectionPoolConfig {
86    fn default() -> Self {
87        Self {
88            max_connections: 64,
89            max_idle: 16,
90        }
91    }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq)]
95pub struct ScanCursor {
96    pub offset: usize,
97}
98
99#[derive(Debug, Clone)]
100pub struct ScanPage {
101    pub collection: String,
102    pub items: Vec<UnifiedEntity>,
103    pub next: Option<ScanCursor>,
104    pub total: usize,
105}
106
107#[derive(Debug, Clone)]
108pub struct SystemInfo {
109    pub pid: u32,
110    pub cpu_cores: usize,
111    pub total_memory_bytes: u64,
112    pub available_memory_bytes: u64,
113    pub os: String,
114    pub arch: String,
115    pub hostname: String,
116}
117
118impl SystemInfo {
119    /// Whether the system has enough cores to benefit from parallelism.
120    /// Returns false on single-core machines where thread overhead > gains.
121    pub fn should_parallelize() -> bool {
122        reddb_engine::execution::should_parallelize()
123    }
124
125    pub fn collect() -> Self {
126        Self {
127            pid: std::process::id(),
128            cpu_cores: std::thread::available_parallelism()
129                .map(|p| p.get())
130                .unwrap_or(1),
131            total_memory_bytes: Self::read_total_memory(),
132            available_memory_bytes: Self::read_available_memory(),
133            os: std::env::consts::OS.to_string(),
134            arch: std::env::consts::ARCH.to_string(),
135            hostname: std::env::var("HOSTNAME")
136                .or_else(|_| std::env::var("COMPUTERNAME"))
137                .unwrap_or_else(|_| "unknown".to_string()),
138        }
139    }
140
141    #[cfg(target_os = "linux")]
142    fn read_total_memory() -> u64 {
143        std::fs::read_to_string("/proc/meminfo")
144            .ok()
145            .and_then(|s| {
146                s.lines()
147                    .find(|l| l.starts_with("MemTotal:"))
148                    .and_then(|l| {
149                        l.split_whitespace()
150                            .nth(1)
151                            .and_then(|v| v.parse::<u64>().ok())
152                    })
153                    .map(|kb| kb * 1024)
154            })
155            .unwrap_or(0)
156    }
157
158    #[cfg(target_os = "linux")]
159    fn read_available_memory() -> u64 {
160        std::fs::read_to_string("/proc/meminfo")
161            .ok()
162            .and_then(|s| {
163                s.lines()
164                    .find(|l| l.starts_with("MemAvailable:"))
165                    .and_then(|l| {
166                        l.split_whitespace()
167                            .nth(1)
168                            .and_then(|v| v.parse::<u64>().ok())
169                    })
170                    .map(|kb| kb * 1024)
171            })
172            .unwrap_or(0)
173    }
174
175    #[cfg(not(target_os = "linux"))]
176    fn read_total_memory() -> u64 {
177        0
178    }
179
180    #[cfg(not(target_os = "linux"))]
181    fn read_available_memory() -> u64 {
182        0
183    }
184}
185
186#[derive(Debug, Clone)]
187pub struct RuntimeStats {
188    pub active_connections: usize,
189    pub idle_connections: usize,
190    pub total_checkouts: u64,
191    pub paged_mode: bool,
192    pub started_at_unix_ms: u128,
193    pub store: StoreStats,
194    pub system: SystemInfo,
195    pub result_blob_cache: crate::storage::cache::BlobCacheStats,
196    pub kv: KvStats,
197    pub metrics_ingest: MetricsIngestStats,
198}
199
200#[derive(Debug, Clone, PartialEq, Eq)]
201pub struct MetricsTenantActivityStats {
202    pub tenant: String,
203    pub namespace: String,
204    pub operation: String,
205    pub count: u64,
206}
207
208#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
209pub struct MetricsIngestStats {
210    pub samples_accepted: u64,
211    pub series_accepted: u64,
212    pub samples_rejected: u64,
213    pub series_rejected: u64,
214    pub series_rejected_cardinality_budget: u64,
215}
216
217#[derive(Debug, Default)]
218pub(crate) struct MetricsIngestCounters {
219    samples_accepted: AtomicU64,
220    series_accepted: AtomicU64,
221    samples_rejected: AtomicU64,
222    series_rejected: AtomicU64,
223    series_rejected_cardinality_budget: AtomicU64,
224}
225
226impl MetricsIngestCounters {
227    pub(crate) fn record(
228        &self,
229        accepted_samples: u64,
230        accepted_series: u64,
231        rejected_samples: u64,
232        rejected_series: u64,
233    ) {
234        self.samples_accepted
235            .fetch_add(accepted_samples, AtomicOrdering::Relaxed);
236        self.series_accepted
237            .fetch_add(accepted_series, AtomicOrdering::Relaxed);
238        self.samples_rejected
239            .fetch_add(rejected_samples, AtomicOrdering::Relaxed);
240        self.series_rejected
241            .fetch_add(rejected_series, AtomicOrdering::Relaxed);
242    }
243
244    pub(crate) fn record_cardinality_budget_rejections(&self, rejected_series: u64) {
245        self.series_rejected_cardinality_budget
246            .fetch_add(rejected_series, AtomicOrdering::Relaxed);
247    }
248
249    pub(crate) fn snapshot(&self) -> MetricsIngestStats {
250        MetricsIngestStats {
251            samples_accepted: self.samples_accepted.load(AtomicOrdering::Relaxed),
252            series_accepted: self.series_accepted.load(AtomicOrdering::Relaxed),
253            samples_rejected: self.samples_rejected.load(AtomicOrdering::Relaxed),
254            series_rejected: self.series_rejected.load(AtomicOrdering::Relaxed),
255            series_rejected_cardinality_budget: self
256                .series_rejected_cardinality_budget
257                .load(AtomicOrdering::Relaxed),
258        }
259    }
260}
261
262#[derive(Debug, Default)]
263pub(crate) struct MetricsTenantActivityCounters {
264    inner: Mutex<BTreeMap<(String, String, String), u64>>,
265}
266
267impl MetricsTenantActivityCounters {
268    pub(crate) fn record(&self, tenant: &str, namespace: &str, operation: &str) {
269        let mut inner = self
270            .inner
271            .lock()
272            .unwrap_or_else(|poison| poison.into_inner());
273        let key = (
274            tenant.to_string(),
275            namespace.to_string(),
276            operation.to_string(),
277        );
278        *inner.entry(key).or_insert(0) += 1;
279    }
280
281    pub(crate) fn snapshot(&self) -> Vec<MetricsTenantActivityStats> {
282        let inner = self
283            .inner
284            .lock()
285            .unwrap_or_else(|poison| poison.into_inner());
286        inner
287            .iter()
288            .map(
289                |((tenant, namespace, operation), count)| MetricsTenantActivityStats {
290                    tenant: tenant.clone(),
291                    namespace: namespace.clone(),
292                    operation: operation.clone(),
293                    count: *count,
294                },
295            )
296            .collect()
297    }
298}
299
300#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
301pub struct KvStats {
302    pub puts: u64,
303    pub gets: u64,
304    pub deletes: u64,
305    pub incrs: u64,
306    pub cas_success: u64,
307    pub cas_conflict: u64,
308    pub watch_streams_active: u64,
309    pub watch_events_emitted: u64,
310    pub watch_drops: u64,
311}
312
313#[derive(Debug, Default)]
314pub(crate) struct KvStatsCounters {
315    puts: AtomicU64,
316    gets: AtomicU64,
317    deletes: AtomicU64,
318    incrs: AtomicU64,
319    cas_success: AtomicU64,
320    cas_conflict: AtomicU64,
321    watch_streams_active: AtomicU64,
322    watch_events_emitted: AtomicU64,
323    watch_drops: AtomicU64,
324}
325
326#[derive(Debug, Default)]
327pub(crate) struct KvTagIndex {
328    tag_to_entries: parking_lot::RwLock<HashMap<(String, String), HashMap<String, EntityId>>>,
329    key_to_tags: parking_lot::RwLock<HashMap<(String, String), BTreeSet<String>>>,
330}
331
332impl KvTagIndex {
333    pub(crate) fn replace(&self, collection: &str, key: &str, id: EntityId, tags: &[String]) {
334        let entry_key = (collection.to_string(), key.to_string());
335        let new_tags: BTreeSet<String> = tags
336            .iter()
337            .map(|tag| tag.trim())
338            .filter(|tag| !tag.is_empty())
339            .map(ToOwned::to_owned)
340            .collect();
341
342        let old_tags = {
343            let mut key_to_tags = self.key_to_tags.write();
344            if new_tags.is_empty() {
345                key_to_tags.remove(&entry_key)
346            } else {
347                key_to_tags.insert(entry_key.clone(), new_tags.clone())
348            }
349        };
350
351        let mut tag_to_entries = self.tag_to_entries.write();
352        if let Some(old_tags) = old_tags {
353            for tag in old_tags {
354                let scoped = (collection.to_string(), tag);
355                let remove_scoped = if let Some(entries) = tag_to_entries.get_mut(&scoped) {
356                    entries.remove(key);
357                    entries.is_empty()
358                } else {
359                    false
360                };
361                if remove_scoped {
362                    tag_to_entries.remove(&scoped);
363                }
364            }
365        }
366
367        for tag in new_tags {
368            tag_to_entries
369                .entry((collection.to_string(), tag))
370                .or_default()
371                .insert(key.to_string(), id);
372        }
373    }
374
375    pub(crate) fn remove(&self, collection: &str, key: &str) {
376        let entry_key = (collection.to_string(), key.to_string());
377        let old_tags = self.key_to_tags.write().remove(&entry_key);
378        let Some(old_tags) = old_tags else {
379            return;
380        };
381
382        let mut tag_to_entries = self.tag_to_entries.write();
383        for tag in old_tags {
384            let scoped = (collection.to_string(), tag);
385            let remove_scoped = if let Some(entries) = tag_to_entries.get_mut(&scoped) {
386                entries.remove(key);
387                entries.is_empty()
388            } else {
389                false
390            };
391            if remove_scoped {
392                tag_to_entries.remove(&scoped);
393            }
394        }
395    }
396
397    pub(crate) fn entries_for_tags(
398        &self,
399        collection: &str,
400        tags: &[String],
401    ) -> Vec<(String, EntityId)> {
402        if tags.is_empty() {
403            return Vec::new();
404        }
405
406        let tag_to_entries = self.tag_to_entries.read();
407        let mut out: HashMap<String, EntityId> = HashMap::new();
408        for tag in tags {
409            let scoped = (collection.to_string(), tag.trim().to_string());
410            if let Some(entries) = tag_to_entries.get(&scoped) {
411                for (key, id) in entries {
412                    out.entry(key.clone()).or_insert(*id);
413                }
414            }
415        }
416        out.into_iter().collect()
417    }
418
419    pub(crate) fn tags_for_key(&self, collection: &str, key: &str) -> Vec<String> {
420        self.key_to_tags
421            .read()
422            .get(&(collection.to_string(), key.to_string()))
423            .map(|tags| tags.iter().cloned().collect())
424            .unwrap_or_default()
425    }
426}
427
428impl KvStatsCounters {
429    pub(crate) fn snapshot(&self) -> KvStats {
430        KvStats {
431            puts: self.puts.load(AtomicOrdering::Relaxed),
432            gets: self.gets.load(AtomicOrdering::Relaxed),
433            deletes: self.deletes.load(AtomicOrdering::Relaxed),
434            incrs: self.incrs.load(AtomicOrdering::Relaxed),
435            cas_success: self.cas_success.load(AtomicOrdering::Relaxed),
436            cas_conflict: self.cas_conflict.load(AtomicOrdering::Relaxed),
437            watch_streams_active: self.watch_streams_active.load(AtomicOrdering::Relaxed),
438            watch_events_emitted: self.watch_events_emitted.load(AtomicOrdering::Relaxed),
439            watch_drops: self.watch_drops.load(AtomicOrdering::Relaxed),
440        }
441    }
442
443    pub(crate) fn incr_puts(&self) {
444        self.puts.fetch_add(1, AtomicOrdering::Relaxed);
445    }
446
447    pub(crate) fn incr_gets(&self) {
448        self.gets.fetch_add(1, AtomicOrdering::Relaxed);
449    }
450
451    pub(crate) fn incr_deletes(&self) {
452        self.deletes.fetch_add(1, AtomicOrdering::Relaxed);
453    }
454
455    pub(crate) fn incr_incrs(&self) {
456        self.incrs.fetch_add(1, AtomicOrdering::Relaxed);
457    }
458
459    pub(crate) fn incr_cas_success(&self) {
460        self.cas_success.fetch_add(1, AtomicOrdering::Relaxed);
461    }
462
463    pub(crate) fn incr_cas_conflict(&self) {
464        self.cas_conflict.fetch_add(1, AtomicOrdering::Relaxed);
465    }
466
467    pub(crate) fn incr_watch_streams_active(&self) {
468        self.watch_streams_active
469            .fetch_add(1, AtomicOrdering::Relaxed);
470    }
471
472    pub(crate) fn decr_watch_streams_active(&self) {
473        self.watch_streams_active
474            .fetch_sub(1, AtomicOrdering::Relaxed);
475    }
476
477    pub(crate) fn incr_watch_events_emitted(&self) {
478        self.watch_events_emitted
479            .fetch_add(1, AtomicOrdering::Relaxed);
480    }
481
482    pub(crate) fn add_watch_drops(&self, count: u64) {
483        self.watch_drops.fetch_add(count, AtomicOrdering::Relaxed);
484    }
485}
486
487#[derive(Debug, Clone)]
488pub struct RuntimeQueryResult {
489    pub query: String,
490    pub mode: QueryMode,
491    pub statement: &'static str,
492    pub engine: &'static str,
493    pub result: UnifiedResult,
494    pub affected_rows: u64,
495    /// High-level statement type: "select", "insert", "update", "delete", "create", "drop", "alter"
496    pub statement_type: &'static str,
497    pub bookmark: Option<String>,
498    pub notice: Option<String>,
499}
500
501impl RuntimeQueryResult {
502    /// Construct a result representing a DML operation (insert/update/delete).
503    pub fn dml_result(
504        query: String,
505        affected: u64,
506        statement_type: &'static str,
507        engine: &'static str,
508    ) -> Self {
509        Self {
510            query,
511            mode: QueryMode::Sql,
512            statement: statement_type,
513            engine,
514            result: UnifiedResult::empty(),
515            affected_rows: affected,
516            statement_type,
517            bookmark: None,
518            notice: None,
519        }
520    }
521
522    /// Construct a result representing a DDL message (create/drop/alter).
523    pub fn ok_message(query: String, message: &str, statement_type: &'static str) -> Self {
524        let mut result = UnifiedResult::empty();
525        let mut record = UnifiedRecord::new();
526        record.set("message", Value::text(message.to_string()));
527        result.push(record);
528        result.columns = vec!["message".to_string()];
529
530        Self {
531            query,
532            mode: QueryMode::Sql,
533            statement: statement_type,
534            engine: "runtime-ddl",
535            result,
536            affected_rows: 0,
537            statement_type,
538            bookmark: None,
539            notice: None,
540        }
541    }
542
543    /// Construct a multi-column record result for read-only meta commands
544    /// (EXPLAIN ALTER, schema introspection, etc.). Each row is a Vec of
545    /// (column_name, value) pairs in column order.
546    pub fn ok_records(
547        query: String,
548        columns: Vec<String>,
549        rows: Vec<Vec<(String, Value)>>,
550        statement_type: &'static str,
551    ) -> Self {
552        let mut result = UnifiedResult::empty();
553        for row in rows {
554            let mut record = UnifiedRecord::new();
555            for (k, v) in row {
556                record.set(&k, v);
557            }
558            result.push(record);
559        }
560        result.columns = columns;
561
562        Self {
563            query,
564            mode: QueryMode::Sql,
565            statement: statement_type,
566            engine: "runtime-meta",
567            result,
568            affected_rows: 0,
569            statement_type,
570            bookmark: None,
571            notice: None,
572        }
573    }
574
575    pub fn bookmark_token(&self) -> Option<&str> {
576        self.bookmark.as_deref()
577    }
578}
579
580#[derive(Debug, Clone)]
581pub struct RuntimeQueryExplain {
582    pub query: String,
583    pub mode: QueryMode,
584    pub statement: &'static str,
585    pub is_universal: bool,
586    pub plan_cost: crate::storage::query::planner::PlanCost,
587    pub estimated_rows: f64,
588    pub estimated_selectivity: f64,
589    pub estimated_confidence: f64,
590    pub passes_applied: Vec<String>,
591    pub logical_plan: CanonicalLogicalPlan,
592    /// Names of any CTEs declared by a leading `WITH` clause. Empty
593    /// for non-CTE queries. The plan tree is built against the
594    /// post-inlining body, so each CTE's body is reachable inside
595    /// `logical_plan` as a regular `Subquery` (or, for bare refs, the
596    /// inlined Table node verbatim). This list lets renderers prepend
597    /// `CteScan` markers so operators see which CTEs were resolved.
598    pub cte_materializations: Vec<String>,
599}
600
601#[derive(Debug, Clone)]
602pub struct RuntimeIvfMatch {
603    pub entity_id: u64,
604    pub distance: f32,
605    pub entity: Option<UnifiedEntity>,
606}
607
608#[derive(Debug, Clone)]
609pub struct RuntimeIvfSearchResult {
610    pub collection: String,
611    pub k: usize,
612    pub n_lists: usize,
613    pub n_probes: usize,
614    pub stats: IvfStats,
615    pub matches: Vec<RuntimeIvfMatch>,
616}
617
618#[derive(Debug, Clone, Copy, PartialEq, Eq)]
619pub enum RuntimeGraphDirection {
620    Outgoing,
621    Incoming,
622    Both,
623}
624
625#[derive(Debug, Clone, Copy, PartialEq, Eq)]
626pub enum RuntimeGraphTraversalStrategy {
627    Bfs,
628    Dfs,
629}
630
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
632pub enum RuntimeGraphPathAlgorithm {
633    Bfs,
634    Dijkstra,
635    AStar,
636    BellmanFord,
637}
638
639#[derive(Debug, Clone)]
640pub struct RuntimeGraphNode {
641    pub id: String,
642    pub label: String,
643    pub node_type: String,
644    pub out_edge_count: u32,
645    pub in_edge_count: u32,
646}
647
648#[derive(Debug, Clone)]
649pub struct RuntimeGraphEdge {
650    pub source: String,
651    pub target: String,
652    pub edge_type: String,
653    pub weight: f32,
654}
655
656#[derive(Debug, Clone)]
657pub struct RuntimeGraphVisit {
658    pub depth: usize,
659    pub node: RuntimeGraphNode,
660}
661
662#[derive(Debug, Clone)]
663pub struct RuntimeGraphNeighborhoodResult {
664    pub source: String,
665    pub direction: RuntimeGraphDirection,
666    pub max_depth: usize,
667    pub nodes: Vec<RuntimeGraphVisit>,
668    pub edges: Vec<RuntimeGraphEdge>,
669}
670
671#[derive(Debug, Clone)]
672pub struct RuntimeGraphTraversalResult {
673    pub source: String,
674    pub direction: RuntimeGraphDirection,
675    pub strategy: RuntimeGraphTraversalStrategy,
676    pub max_depth: usize,
677    pub visits: Vec<RuntimeGraphVisit>,
678    pub edges: Vec<RuntimeGraphEdge>,
679}
680
681#[derive(Debug, Clone)]
682pub struct RuntimeGraphPath {
683    pub hop_count: usize,
684    pub total_weight: f64,
685    pub nodes: Vec<RuntimeGraphNode>,
686    pub edges: Vec<RuntimeGraphEdge>,
687}
688
689#[derive(Debug, Clone)]
690pub struct RuntimeGraphPathResult {
691    pub source: String,
692    pub target: String,
693    pub direction: RuntimeGraphDirection,
694    pub algorithm: RuntimeGraphPathAlgorithm,
695    pub nodes_visited: usize,
696    pub negative_cycle_detected: Option<bool>,
697    pub path: Option<RuntimeGraphPath>,
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701pub enum RuntimeGraphComponentsMode {
702    Connected,
703    Weak,
704    Strong,
705}
706
707#[derive(Debug, Clone, Copy, PartialEq, Eq)]
708pub enum RuntimeGraphCentralityAlgorithm {
709    Degree,
710    Closeness,
711    Betweenness,
712    Eigenvector,
713    PageRank,
714}
715
716#[derive(Debug, Clone, Copy, PartialEq, Eq)]
717pub enum RuntimeGraphCommunityAlgorithm {
718    LabelPropagation,
719    Louvain,
720}
721
722#[derive(Debug, Clone)]
723pub struct RuntimeGraphComponent {
724    pub id: String,
725    pub size: usize,
726    pub nodes: Vec<String>,
727}
728
729#[derive(Debug, Clone)]
730pub struct RuntimeGraphComponentsResult {
731    pub mode: RuntimeGraphComponentsMode,
732    pub count: usize,
733    pub components: Vec<RuntimeGraphComponent>,
734}
735
736#[derive(Debug, Clone)]
737pub struct RuntimeGraphCentralityScore {
738    pub node: RuntimeGraphNode,
739    pub score: f64,
740}
741
742#[derive(Debug, Clone)]
743pub struct RuntimeGraphDegreeScore {
744    pub node: RuntimeGraphNode,
745    pub in_degree: usize,
746    pub out_degree: usize,
747    pub total_degree: usize,
748}
749
750#[derive(Debug, Clone)]
751pub struct RuntimeGraphCentralityResult {
752    pub algorithm: RuntimeGraphCentralityAlgorithm,
753    pub normalized: Option<bool>,
754    pub iterations: Option<usize>,
755    pub converged: Option<bool>,
756    pub scores: Vec<RuntimeGraphCentralityScore>,
757    pub degree_scores: Vec<RuntimeGraphDegreeScore>,
758}
759
760#[derive(Debug, Clone)]
761pub struct RuntimeGraphCommunity {
762    pub id: String,
763    pub size: usize,
764    pub nodes: Vec<String>,
765}
766
767#[derive(Debug, Clone)]
768pub struct RuntimeGraphCommunityResult {
769    pub algorithm: RuntimeGraphCommunityAlgorithm,
770    pub count: usize,
771    pub iterations: Option<usize>,
772    pub converged: Option<bool>,
773    pub modularity: Option<f64>,
774    pub passes: Option<usize>,
775    pub communities: Vec<RuntimeGraphCommunity>,
776}
777
778#[derive(Debug, Clone)]
779pub struct RuntimeGraphClusteringResult {
780    pub global: f64,
781    pub local: Vec<RuntimeGraphCentralityScore>,
782    pub triangle_count: Option<usize>,
783}
784
785#[derive(Debug, Clone)]
786pub struct RuntimeGraphHitsResult {
787    pub iterations: usize,
788    pub converged: bool,
789    pub hubs: Vec<RuntimeGraphCentralityScore>,
790    pub authorities: Vec<RuntimeGraphCentralityScore>,
791}
792
793#[derive(Debug, Clone)]
794pub struct RuntimeGraphCyclesResult {
795    pub limit_reached: bool,
796    pub cycles: Vec<RuntimeGraphPath>,
797}
798
799#[derive(Debug, Clone)]
800pub struct RuntimeGraphTopologicalSortResult {
801    pub acyclic: bool,
802    pub ordered_nodes: Vec<RuntimeGraphNode>,
803}
804
805#[derive(Debug, Clone)]
806pub struct RuntimeGraphPropertiesResult {
807    pub node_count: usize,
808    pub edge_count: usize,
809    pub self_loop_count: usize,
810    pub negative_edge_count: usize,
811    pub connected_component_count: usize,
812    pub weak_component_count: usize,
813    pub strong_component_count: usize,
814    pub is_empty: bool,
815    pub is_connected: bool,
816    pub is_weakly_connected: bool,
817    pub is_strongly_connected: bool,
818    pub is_complete: bool,
819    pub is_complete_directed: bool,
820    pub is_cyclic: bool,
821    pub is_circular: bool,
822    pub is_acyclic: bool,
823    pub is_tree: bool,
824    pub density: f64,
825    pub density_directed: f64,
826}
827
828// ============================================================================
829// Context Search types
830// ============================================================================
831
832#[derive(Debug, Clone)]
833pub struct ContextSearchResult {
834    pub query: String,
835    pub tables: Vec<ContextEntity>,
836    pub graph: ContextGraphResult,
837    pub vectors: Vec<ContextEntity>,
838    pub documents: Vec<ContextEntity>,
839    pub key_values: Vec<ContextEntity>,
840    pub connections: Vec<ContextConnection>,
841    pub summary: ContextSummary,
842}
843
844#[derive(Debug, Clone)]
845pub struct ContextEntity {
846    pub entity: UnifiedEntity,
847    pub score: f32,
848    pub discovery: DiscoveryMethod,
849    pub collection: String,
850}
851
852#[derive(Debug, Clone)]
853pub enum DiscoveryMethod {
854    Indexed {
855        field: String,
856    },
857    GlobalScan,
858    CrossReference {
859        source_id: u64,
860        ref_type: String,
861    },
862    GraphTraversal {
863        source_id: u64,
864        edge_type: String,
865        depth: usize,
866    },
867    VectorQuery {
868        similarity: f32,
869    },
870}
871
872#[derive(Debug, Clone)]
873pub struct ContextGraphResult {
874    pub nodes: Vec<ContextEntity>,
875    pub edges: Vec<ContextEntity>,
876}
877
878#[derive(Debug, Clone)]
879pub struct ContextConnection {
880    pub from_id: u64,
881    pub to_id: u64,
882    pub connection_type: ContextConnectionType,
883    pub weight: f32,
884}
885
886#[derive(Debug, Clone)]
887pub enum ContextConnectionType {
888    CrossRef(String),
889    GraphEdge(String),
890    VectorSimilarity(f32),
891}
892
893#[derive(Debug, Clone)]
894pub struct ContextSummary {
895    pub total_entities: usize,
896    pub direct_matches: usize,
897    pub expanded_via_graph: usize,
898    pub expanded_via_cross_refs: usize,
899    pub expanded_via_vector_query: usize,
900    pub collections_searched: usize,
901    pub execution_time_us: u64,
902    pub tiers_used: Vec<String>,
903    pub entities_reindexed: usize,
904}
905
906struct PoolState {
907    next_id: u64,
908    active: usize,
909    pooled_active: usize,
910    idle: Vec<u64>,
911    total_checkouts: u64,
912}
913
914impl Default for PoolState {
915    fn default() -> Self {
916        Self {
917            next_id: 1,
918            active: 0,
919            pooled_active: 0,
920            idle: Vec::new(),
921            total_checkouts: 0,
922        }
923    }
924}
925
926#[derive(Debug, Clone)]
927struct RuntimeResultCacheEntry {
928    result: RuntimeQueryResult,
929    cached_at: std::time::Instant,
930    scopes: HashSet<String>,
931}
932
933pub const METRIC_CACHE_SHADOW_DIVERGENCE_TOTAL: &str = "cache_shadow_divergence_total";
934/// Stable metric names for the query/graph-analytics result cache
935/// (issue #802). Exposed under the `red.metrics` surface as
936/// `reddb_result_cache_{hit,miss,evict}_total` and readable in-process
937/// via `RedDBRuntime::result_cache_metrics`.
938pub const METRIC_RESULT_CACHE_HIT_TOTAL: &str = "result_cache_hit_total";
939pub const METRIC_RESULT_CACHE_MISS_TOTAL: &str = "result_cache_miss_total";
940pub const METRIC_RESULT_CACHE_EVICT_TOTAL: &str = "result_cache_evict_total";
941pub(crate) const ASK_ANSWER_CACHE_NAMESPACE: &str = "runtime.ask_answer_cache";
942const RMW_LOCK_SHARDS: usize = 64;
943
944struct RmwLockTable {
945    shards: Vec<parking_lot::Mutex<HashMap<String, Arc<parking_lot::Mutex<()>>>>>,
946}
947
948impl RmwLockTable {
949    fn new() -> Self {
950        let shards = (0..RMW_LOCK_SHARDS)
951            .map(|_| parking_lot::Mutex::new(HashMap::new()))
952            .collect();
953        Self { shards }
954    }
955
956    fn lock_for(&self, collection: &str, key: &str) -> Arc<parking_lot::Mutex<()>> {
957        use std::hash::{Hash, Hasher};
958
959        let mut hasher = std::collections::hash_map::DefaultHasher::new();
960        collection.hash(&mut hasher);
961        key.hash(&mut hasher);
962        let shard_idx = (hasher.finish() as usize) % self.shards.len();
963        let map_key = format!("{collection}\u{1f}{key}");
964        let mut shard = self.shards[shard_idx].lock();
965        shard
966            .entry(map_key)
967            .or_insert_with(|| Arc::new(parking_lot::Mutex::new(())))
968            .clone()
969    }
970}
971
972#[derive(Debug, Default)]
973pub(crate) struct CheckpointProjectionStats {
974    last_materialized_lsn: std::sync::atomic::AtomicU64,
975    checkpoints_completed: std::sync::atomic::AtomicU64,
976    last_checkpoint_duration_ms: std::sync::atomic::AtomicU64,
977}
978
979impl CheckpointProjectionStats {
980    pub(crate) fn record_checkpoint(&self, lsn: u64, duration_ms: u64) {
981        use std::sync::atomic::Ordering;
982
983        self.last_materialized_lsn.store(lsn, Ordering::Relaxed);
984        self.last_checkpoint_duration_ms
985            .store(duration_ms, Ordering::Relaxed);
986        self.checkpoints_completed.fetch_add(1, Ordering::Relaxed);
987    }
988
989    pub(crate) fn snapshot(&self, current_lsn: u64) -> CheckpointProjectionStatsSnapshot {
990        use std::sync::atomic::Ordering;
991
992        let last_materialized_lsn = self.last_materialized_lsn.load(Ordering::Relaxed);
993        CheckpointProjectionStatsSnapshot {
994            current_lsn,
995            last_materialized_lsn,
996            projection_lag: current_lsn.saturating_sub(last_materialized_lsn),
997            checkpoints_completed: self.checkpoints_completed.load(Ordering::Relaxed),
998            last_checkpoint_duration_ms: self.last_checkpoint_duration_ms.load(Ordering::Relaxed),
999        }
1000    }
1001}
1002
1003#[derive(Debug, Clone, Copy)]
1004pub(crate) struct CheckpointProjectionStatsSnapshot {
1005    pub(crate) current_lsn: u64,
1006    pub(crate) last_materialized_lsn: u64,
1007    pub(crate) projection_lag: u64,
1008    pub(crate) checkpoints_completed: u64,
1009    pub(crate) last_checkpoint_duration_ms: u64,
1010}
1011
1012#[derive(Debug, Clone)]
1013pub(crate) struct ScrubStatsSnapshot {
1014    pub(crate) last_run_unix_ms: u64,
1015    pub(crate) last_findings_count: u64,
1016    pub(crate) background_status: String,
1017    pub(crate) background_verified_objects: u64,
1018    pub(crate) background_total_objects: u64,
1019    pub(crate) verified: reddb_file::StorageScrubVerifiedCounters,
1020}
1021
1022#[derive(Debug, Clone)]
1023pub(crate) struct ScrubRuntimeState {
1024    pub(crate) last_run_unix_ms: u64,
1025    pub(crate) last_findings_count: u64,
1026    pub(crate) background_cursor: usize,
1027    pub(crate) background_status: String,
1028    pub(crate) background_verified_objects: u64,
1029    pub(crate) background_total_objects: u64,
1030    pub(crate) verified: reddb_file::StorageScrubVerifiedCounters,
1031}
1032
1033impl Default for ScrubRuntimeState {
1034    fn default() -> Self {
1035        Self {
1036            last_run_unix_ms: 0,
1037            last_findings_count: 0,
1038            background_cursor: 0,
1039            background_status: "idle".to_string(),
1040            background_verified_objects: 0,
1041            background_total_objects: 0,
1042            verified: reddb_file::StorageScrubVerifiedCounters::default(),
1043        }
1044    }
1045}
1046
1047impl ScrubRuntimeState {
1048    pub(crate) fn snapshot(&self) -> ScrubStatsSnapshot {
1049        ScrubStatsSnapshot {
1050            last_run_unix_ms: self.last_run_unix_ms,
1051            last_findings_count: self.last_findings_count,
1052            background_status: self.background_status.clone(),
1053            background_verified_objects: self.background_verified_objects,
1054            background_total_objects: self.background_total_objects,
1055            verified: self.verified.clone(),
1056        }
1057    }
1058}
1059
1060struct RuntimeInner {
1061    functions: parking_lot::RwLock<function_catalog::FunctionCatalog>,
1062    db: Arc<RedDB>,
1063    layout: PhysicalLayout,
1064    embedded_single_file: bool,
1065    /// The one memory budget this process runs under (ADR 0073 §1),
1066    /// resolved once at boot and immutable for the process lifetime.
1067    pub(crate) memory_budget: crate::storage::memory_budget::MemoryBudget,
1068    /// The one shared accounting pool (ADR 0073 §2): each big consumer's share
1069    /// of the budget above, and the live usage they report into it.
1070    pub(crate) memory_accounting: Arc<crate::storage::memory_pools::MemoryAccounting>,
1071    memory_reservations: parking_lot::Mutex<memory_admission::MemoryReservations>,
1072    indices: IndexCatalog,
1073    pool_config: ConnectionPoolConfig,
1074    pool: Mutex<PoolState>,
1075    started_at_unix_ms: u128,
1076    probabilistic: probabilistic_store::ProbabilisticStore,
1077    index_store: index_store::IndexStore,
1078    cdc: crate::replication::cdc::CdcBuffer,
1079    pub(crate) checkpoint_projection_stats: CheckpointProjectionStats,
1080    pub(crate) scrub_state: parking_lot::Mutex<ScrubRuntimeState>,
1081    pub(crate) checkpoint_columnar_emission_budget_chunks: usize,
1082    pub(crate) columnar_projection_size_floor_rows: usize,
1083    backup_scheduler: crate::replication::scheduler::BackupScheduler,
1084    query_cache: parking_lot::RwLock<crate::storage::query::planner::cache::PlanCache>,
1085    result_cache: parking_lot::RwLock<(
1086        HashMap<String, RuntimeResultCacheEntry>,
1087        std::collections::VecDeque<String>,
1088    )>,
1089    result_blob_cache: crate::storage::cache::BlobCache,
1090    result_blob_entries: parking_lot::RwLock<(
1091        HashMap<String, RuntimeResultCacheEntry>,
1092        std::collections::VecDeque<String>,
1093    )>,
1094    ask_answer_cache_entries:
1095        parking_lot::RwLock<(HashSet<String>, std::collections::VecDeque<String>)>,
1096    result_cache_shadow_divergences: std::sync::atomic::AtomicU64,
1097    /// Result-cache observability counters (issue #802). Process-cumulative
1098    /// hit/miss/eviction tallies surfaced under `red.metrics`.
1099    result_cache_hits: std::sync::atomic::AtomicU64,
1100    result_cache_misses: std::sync::atomic::AtomicU64,
1101    result_cache_evictions: std::sync::atomic::AtomicU64,
1102    ask_daily_spend:
1103        parking_lot::RwLock<HashMap<String, crate::runtime::ai::cost_guard::DailyState>>,
1104    /// Process-local queue message locks used to emulate `SKIP LOCKED`-style
1105    /// claim semantics for concurrent queue consumers inside this runtime.
1106    queue_message_locks: parking_lot::RwLock<HashMap<String, Arc<parking_lot::Mutex<()>>>>,
1107    /// Process-local read-modify-write locks. The table is sharded by
1108    /// `(collection, key)` and each entry has its own mutex, so unrelated keys
1109    /// in the same collection do not serialize behind one global lock.
1110    rmw_locks: RmwLockTable,
1111    planner_dirty_tables: parking_lot::RwLock<HashSet<String>>,
1112    ec_registry: Arc<crate::ec::config::EcRegistry>,
1113    config_registry: Arc<crate::auth::registry::ConfigRegistry>,
1114    ec_worker: crate::ec::worker::EcWorker,
1115    /// Optional AuthStore — injected by server boot when auth is
1116    /// enabled. Required for `Value::Secret` auto-encrypt/decrypt
1117    /// because the AES key lives in the vault KV under the
1118    /// `red.secret.aes_key` entry.
1119    auth_store: parking_lot::RwLock<Option<Arc<crate::auth::store::AuthStore>>>,
1120    /// Optional OAuth/OIDC JWT validator. Wired by server boot when
1121    /// the operator configures issuer + JWKS via env / CLI. HTTP and
1122    /// wire transports read this on every bearer-token request and,
1123    /// when the token decodes as a JWT, validate it against the
1124    /// configured issuer + audience + signature before falling back to
1125    /// the local AuthStore lookup.
1126    oauth_validator: parking_lot::RwLock<Option<Arc<crate::auth::oauth::OAuthValidator>>>,
1127    /// Browser credential layer — the hybrid-token authority (issue
1128    /// #936, PRD #930). When wired (an operator opts the browser
1129    /// endpoint in), the RedWire WS handshake accepts the short-lived
1130    /// access JWT it mints, and the `/auth/browser/*` HTTP endpoints
1131    /// issue/rotate the access+refresh pair. `None` leaves the browser
1132    /// flow inert — default-deny, matching the WS endpoint itself.
1133    browser_token_authority:
1134        parking_lot::RwLock<Option<Arc<crate::auth::browser_token::BrowserTokenAuthority>>>,
1135    /// View registry (Phase 2.1 PG parity).
1136    ///
1137    /// Holds the parsed `SELECT` body for every view created via
1138    /// `CREATE [MATERIALIZED] VIEW`. Queries that reference a view name
1139    /// substitute the stored `QueryExpr` at execution time. Materialized
1140    /// views additionally back onto the shared `MaterializedViewCache`
1141    /// (see `RuntimeInner::materialized_views`).
1142    ///
1143    /// This is in-memory only in Phase 2.1 — view definitions do not
1144    /// survive a restart. Persistence is a Phase 3 follow-up.
1145    views: parking_lot::RwLock<HashMap<String, Arc<reddb_rql::ast::CreateViewQuery>>>,
1146    materialized_views: parking_lot::RwLock<crate::storage::cache::result::MaterializedViewCache>,
1147    /// Per-collection retention sweeper state (issue #584 slice 12).
1148    /// Tracks `last_sweep_at_ms`, row/segment retirement totals, and
1149    /// the latest pending-rows estimate that feeds `red.retention`.
1150    /// In-memory only; resets across restart.
1151    pub(crate) retention_sweeper:
1152        parking_lot::RwLock<crate::runtime::retention_sweeper::RetentionSweeperState>,
1153    /// Per-connection transaction contexts, local tenant overrides, and the
1154    /// shared MVCC snapshot manager behind the Transaction State interface.
1155    transaction_state: crate::runtime::transaction_state::TransactionState,
1156    /// Intent-lock hierarchy (IS/IX/S/X) used to break the implicit
1157    /// global-write serialisation in write paths. Populated at boot
1158    /// with `concurrency.locking.deadlock_timeout_ms` from the matrix
1159    /// and wired through DML/DDL dispatch in later P1 tasks.
1160    /// Dormant until P1.T3 flips the read path to `(Global,IS) →
1161    /// (Collection,IS)` and P1.T4/T5 pick up writes/DDL.
1162    lock_manager: Arc<crate::runtime::lock_manager::LockManager>,
1163    /// Perf-parity env-var overrides (`REDDB_<UP_DOTTED_KEY>`).
1164    /// Populated once at boot, read by every config getter; takes
1165    /// precedence over the persisted red_config value so operators
1166    /// can hot-fix a bad config by restarting with a different env
1167    /// var set. Keys are restricted to those declared in the matrix.
1168    env_config_overrides: HashMap<String, String>,
1169    /// Row-level security policies (Phase 2.5 PG parity).
1170    ///
1171    /// Keyed by `(table_name, policy_name)`; the set of tables with RLS
1172    /// enforcement toggled on lives in `rls_enabled_tables`. Filter
1173    /// enforcement hooks into the read path via `collect_rls_filters()`
1174    /// — see `runtime::impl_core`.
1175    rls_policies:
1176        parking_lot::RwLock<HashMap<(String, String), Arc<reddb_rql::ast::CreatePolicyQuery>>>,
1177    rls_enabled_tables: parking_lot::RwLock<HashSet<String>>,
1178    /// Foreign Data Wrapper registry (Phase 3.2 PG parity).
1179    ///
1180    /// Maps server names → wrapper instances and foreign-table names →
1181    /// definitions. Queries referencing a registered foreign table are
1182    /// re-routed to `ForeignTableRegistry::scan` by the read-path
1183    /// rewriter; reads against unknown names fall through to the native
1184    /// collection lookup.
1185    foreign_tables: Arc<crate::storage::fdw::ForeignTableRegistry>,
1186    /// Per-connection list of tuples marked for deletion by the current
1187    /// transaction (Phase 2.3.2b MVCC tombstones + 2.3.2e savepoints).
1188    /// Each entry is `(collection, entity_id, stamper_xid, previous_xmax)`
1189    /// — the xid that stamped xmax on the tuple plus the value it
1190    /// replaced. For a plain transaction the
1191    /// stamper equals `ctx.xid`; with savepoints the stamper equals
1192    /// the innermost open sub-xid so ROLLBACK TO SAVEPOINT can revive
1193    /// only the matching subset. COMMIT drains the whole conn list
1194    /// and keeps the committed tombstones; ROLLBACK (whole-tx) revives them all;
1195    /// ROLLBACK TO SAVEPOINT revives those with `stamper_xid >=
1196    /// savepoint_xid`. Autocommit DELETE bypasses this map.
1197    pending_tombstones: parking_lot::RwLock<
1198        HashMap<
1199            u64,
1200            Vec<(
1201                String,
1202                crate::storage::unified::entity::EntityId,
1203                crate::storage::transaction::snapshot::Xid,
1204                crate::storage::transaction::snapshot::Xid,
1205            )>,
1206        >,
1207    >,
1208    /// Per-connection table-row UPDATE versions created by an open
1209    /// transaction. Each entry is `(collection, old_entity_id,
1210    /// new_entity_id, stamper_xid, previous_xmax)`. COMMIT keeps both physical
1211    /// versions and drops the pending marker; ROLLBACK revives the old
1212    /// version and removes the new uncommitted version.
1213    pending_versioned_updates: parking_lot::RwLock<
1214        HashMap<
1215            u64,
1216            Vec<(
1217                String,
1218                crate::storage::unified::entity::EntityId,
1219                crate::storage::unified::entity::EntityId,
1220                crate::storage::transaction::snapshot::Xid,
1221                crate::storage::transaction::snapshot::Xid,
1222            )>,
1223        >,
1224    >,
1225    /// Per-connection push idempotency keys written by an open transaction.
1226    /// Each entry is `(queue, dedup_key, metadata_entity_id)`. COMMIT checks
1227    /// the queue/key subject for first-committer-wins conflicts; ROLLBACK
1228    /// removes the uncommitted metadata row so later producer retries enqueue
1229    /// normally.
1230    pending_queue_dedup: parking_lot::RwLock<HashMap<u64, Vec<(String, String, EntityId)>>>,
1231    pending_kv_watch_events:
1232        parking_lot::RwLock<HashMap<u64, Vec<(u64, crate::replication::cdc::KvWatchEvent)>>>,
1233    pending_vault_writes: parking_lot::RwLock<HashMap<u64, Vec<impl_kv::PendingVaultWrite>>>,
1234    pending_store_wal_actions:
1235        parking_lot::RwLock<HashMap<u64, crate::storage::unified::DeferredStoreWalActions>>,
1236    /// Transaction-scoped table UPDATE CLAIM ownership.
1237    ///
1238    /// Keyed by `(collection, logical_row_id)` and valued by connection id.
1239    /// Only claim selection consults this map: ordinary DML still follows
1240    /// MVCC first-committer-wins instead of waiting on claim locks.
1241    pending_claim_locks: parking_lot::RwLock<HashMap<(String, EntityId), u64>>,
1242    /// Table-scoped tenancy registry (Phase 2.5.4).
1243    ///
1244    /// Maps `table_name → tenant_column`. DML auto-fill looks here to
1245    /// inject `CURRENT_TENANT()` on INSERTs that omit the column, and
1246    /// DDL keeps the in-memory registry in sync with the
1247    /// `tenant_tables.*` keys in red_config. Read-side enforcement
1248    /// piggy-backs on the existing RLS infrastructure: every entry
1249    /// installs an implicit `col = CURRENT_TENANT()` policy.
1250    tenant_tables: parking_lot::RwLock<HashMap<String, String>>,
1251    /// Monotonic epoch bumped on every DDL / schema-mutating operation
1252    /// that calls `invalidate_plan_cache`. Prepared statements capture
1253    /// this at PREPARE and re-check at EXECUTE — a mismatch means the
1254    /// cached shape may reference dropped or renamed columns and the
1255    /// client must re-PREPARE.
1256    ddl_epoch: std::sync::atomic::AtomicU64,
1257    /// Public-mutation gate (PLAN.md W1).
1258    ///
1259    /// Built once at construction from the immutable subset of
1260    /// `RedDBOptions` (read_only flag + replication role). Every public
1261    /// mutation surface — SQL DML/DDL, gRPC mutating RPCs, HTTP/native
1262    /// wire mutations, admin maintenance endpoints, serverless
1263    /// lifecycle — consults `write_gate.check(WriteKind::*)` before
1264    /// dispatching to storage. The replica internal apply path
1265    /// (`LogicalChangeApplier`) reaches into the store directly and
1266    /// bypasses the gate by construction.
1267    write_gate: Arc<crate::runtime::write_gate::WriteGate>,
1268    /// Process lifecycle state machine (PLAN.md Phase 1 — Lifecycle
1269    /// Contract). Drives `/health/live`, `/health/ready`,
1270    /// `/health/startup`, and `POST /admin/shutdown` so any
1271    /// orchestrator (K8s preStop, Fly autostop, ECS task drain,
1272    /// systemd) can coordinate without losing data.
1273    lifecycle: crate::runtime::lifecycle::Lifecycle,
1274    /// Operator-imposed resource limits (PLAN.md Phase 4.1).
1275    /// Read once at boot from `RED_MAX_*` env vars; consulted by
1276    /// observability and (in follow-up commits) the per-write
1277    /// enforcement points.
1278    resource_limits: crate::runtime::resource_limits::ResourceLimits,
1279    query_budget_slots: AtomicU64,
1280    /// Append-only audit log for admin mutations (PLAN.md Phase
1281    /// 6.5). Lives next to the primary `.rdb` file so backup +
1282    /// restore flows ship it alongside the data.
1283    audit_log: Arc<crate::runtime::audit_log::AuditLogger>,
1284    /// Durable control-plane evidence ledger. Producer slices emit
1285    /// through this sink and decide fail-open/fail-closed using
1286    /// `control_event_config`.
1287    control_event_ledger:
1288        parking_lot::RwLock<Arc<dyn crate::runtime::control_events::ControlEventLedger>>,
1289    control_event_config: crate::runtime::control_events::ControlEventConfig,
1290    /// Data-plane query audit stream. Kept separate from the Control
1291    /// Event Ledger so scoped query metadata cannot be confused with
1292    /// governance evidence.
1293    query_audit: Arc<crate::runtime::query_audit::QueryAuditStream>,
1294    /// Serverless writer-lease state machine. `None` when the operator
1295    /// did not opt into lease fencing (`RED_LEASE_REQUIRED` unset/false).
1296    /// When set, owns the {acquire/refresh/release/lost} transitions and
1297    /// is the single place that mutates `write_gate.set_lease_state` and
1298    /// records lease/* audit entries — keeping those two side-effects
1299    /// from drifting.
1300    lease_lifecycle: std::sync::OnceLock<Arc<crate::runtime::lease_lifecycle::LeaseLifecycle>>,
1301    /// PLAN.md Phase 11.5 — counters bumped by the replica apply
1302    /// loop on `Gap` / `Divergence` / `Apply` errors so /metrics
1303    /// surfaces them as `reddb_replica_apply_errors_total{kind}`.
1304    replica_apply_metrics: Arc<crate::replication::logical::ReplicaApplyMetrics>,
1305    /// Issue #1243 (PRD #1237 Phase B) — primary↔replica reconnect counter
1306    /// bumped by the replica loop's health-persist chokepoint when the link
1307    /// drops and restores. Surfaced as `reddb_replication_reconnects_total`
1308    /// and in the red-ui replica status read model.
1309    replica_link_metrics: Arc<crate::replication::reconnect::ReplicaLinkMetrics>,
1310    /// PLAN.md Phase 4.4 — per-caller QPS quotas. Disabled (no-op)
1311    /// when `RED_MAX_QPS_PER_CALLER` is unset.
1312    quota_bucket: crate::runtime::quota_bucket::QuotaBucket,
1313    /// Issue #120 — token → schema entity reverse index, kept current
1314    /// incrementally on DDL events. Consumed by AskPipeline (issue
1315    /// #121) Stage 2 to narrow vector-search candidates before any
1316    /// embedding compute. Mutated only from DDL execution paths.
1317    schema_vocabulary: parking_lot::RwLock<crate::runtime::schema_vocabulary::SchemaVocabulary>,
1318    /// Issue #205 — dedicated slow-query sink (`red-slow.log`).
1319    /// Built once at runtime startup; below-threshold calls pay only a
1320    /// single relaxed atomic load. Threshold + sample-pct come from
1321    /// `runtime.slow_query.threshold_ms` / `.sample_pct` (config matrix)
1322    /// at construction; live tuning via the config tree is a follow-up.
1323    slow_query_logger: Arc<crate::telemetry::slow_query_logger::SlowQueryLogger>,
1324    /// Issue #1238 — operational telemetry substrate for slow-query events
1325    /// (ADR 0060, §2). Bounded ring buffer that the slow-query logger dual-
1326    /// writes into alongside `red-slow.log`. Exposed to read-model consumers
1327    /// via `slow_query_store()`.
1328    slow_query_store: Arc<crate::telemetry::slow_query_store::SlowQueryStore>,
1329    /// Process-local normal-KV operation counters. These are intentionally
1330    /// runtime-local; persistent accounting belongs in catalog stats.
1331    kv_stats: KvStatsCounters,
1332    metrics_ingest_stats: MetricsIngestCounters,
1333    metrics_tenant_activity_stats: MetricsTenantActivityCounters,
1334    /// Issue #1457 — Concurrent claim counters rendered onto `/metrics`.
1335    /// Process-local; counters reset on restart by design.
1336    claim_telemetry: std::sync::Arc<claim_telemetry::ClaimTelemetryCounters>,
1337    /// Slice 10 of issue #527 — Prometheus counters for the queue
1338    /// lifecycle (delivered/acked/nacked) rendered onto `/metrics`.
1339    /// Process-local; counters reset on restart by design.
1340    queue_telemetry: std::sync::Arc<queue_telemetry::QueueTelemetryCounters>,
1341    /// Issue #1241 — query latency histogram substrate (per-`kind`
1342    /// `reddb_query_duration_seconds`). Process-local measurement + read
1343    /// model that `/metrics`, `/cluster/status`, and the red-ui percentile
1344    /// panels all consume; counters reset on restart by design.
1345    query_latency_telemetry: std::sync::Arc<query_latency_telemetry::QueryLatencyTelemetry>,
1346    /// Issue #1244 — node CPU/RAM occupancy sampler (ADR 0060 §2 "node
1347    /// samples"). Process-local measurement + current-snapshot read model
1348    /// `/cluster/status` consumes; sampled on-demand from the status
1349    /// handler. See `occupancy_sampler` for the overhead/interval contract.
1350    occupancy_sampler: std::sync::Arc<occupancy_sampler::OccupancySampler>,
1351    /// Issue #1245 — per-node load telemetry (active query gauge +
1352    /// connect/disconnect churn counters). Three atomics; no per-client
1353    /// labels; feeds `/metrics`, `/cluster/status`, and the red-ui load
1354    /// panels (ADR 0060 §2 "node samples" data class).
1355    node_load_telemetry: std::sync::Arc<node_load_telemetry::NodeLoadTelemetry>,
1356    /// Issue #742 — consumer presence (heartbeat / lease / lifecycle
1357    /// state per (queue, group, consumer)). Process-local in this
1358    /// slice; durability across restart lands in the follow-up that
1359    /// mirrors the registry into `red_queue_meta` rows. Independent
1360    /// of pending-delivery state by design — see
1361    /// `storage::queue::presence` for the contract.
1362    queue_presence: std::sync::Arc<crate::storage::queue::presence::ConsumerPresenceRegistry>,
1363    /// Issue #743 — vector + TurboQuant introspection registry. Red UI
1364    /// vector toolbars (and `red.*` vector virtual tables) read
1365    /// per-collection metadata + artifact state from here so they
1366    /// never have to reach into `engine::vector_store` or
1367    /// `engine::turboquant::*` internals. Engine publish points (build
1368    /// start / finish, fallback toggle, drop) call into this in
1369    /// follow-up slices of PRD #735; the public Rust surface lives on
1370    /// the runtime and does not change when those land.
1371    vector_introspection:
1372        std::sync::Arc<crate::storage::vector::introspection::VectorIntrospectionRegistry>,
1373    /// Slice C of PRD #718 — local wait registry for `QUEUE READ … WAIT`.
1374    /// Producer commits notify; readers park here until wake-or-timeout
1375    /// or until `cancel_all` is invoked at shutdown.
1376    queue_wait_registry: std::sync::Arc<queue_wait_registry::QueueWaitRegistry>,
1377    /// Per-connection list of `(scope, queue)` pairs that should be
1378    /// notified through `queue_wait_registry` on COMMIT (slice C of
1379    /// PRD #718). Push paths buffer here while inside a txn; the
1380    /// COMMIT path drains and notifies. ROLLBACK discards — by design
1381    /// rolled-back enqueues do not deliver and do not wake waiters.
1382    pending_queue_wakes: parking_lot::RwLock<HashMap<u64, Vec<(String, String)>>>,
1383    /// Process-local normal-KV tag index used by `INVALIDATE TAGS`.
1384    kv_tag_index: KvTagIndex,
1385    /// Issue #524 — in-memory chain-tip cache per collection. Populated lazily
1386    /// by the first INSERT or `GET /chain-tip` call after restart and updated
1387    /// atomically with each chain INSERT. Backed by a single mutex so a chain
1388    /// INSERT serialises against concurrent submitters — the loser observes
1389    /// the advanced tip and surfaces `BlockchainConflict` to its caller.
1390    chain_tip_cache:
1391        parking_lot::Mutex<HashMap<String, crate::runtime::blockchain_kind::ChainTipFull>>,
1392    /// Issue #525 — in-memory mirror of the persisted `integrity` flag per
1393    /// chain collection.  `true` means INSERTs must be rejected with
1394    /// `ChainIntegrityBroken`.  Loaded lazily from `red_config` on first
1395    /// access so the flag survives restart.
1396    chain_integrity_broken: parking_lot::Mutex<HashMap<String, bool>>,
1397    /// Issue #765 / S6 — in-memory cache of input-stream integrity tombstone
1398    /// RID ranges. Loaded lazily from `red_config` on first read so the set
1399    /// survives restart (the durable list lives under
1400    /// `stream.integrity.tombstones`). `integrity_tombstones_state` is the
1401    /// hot-path gate: `0` = unloaded, `1` = loaded-empty (reads skip
1402    /// filtering after a single relaxed load), `2` = loaded-with-tombstones.
1403    integrity_tombstones:
1404        parking_lot::Mutex<Vec<crate::runtime::integrity_tombstone::TombstoneRange>>,
1405    integrity_tombstones_state: std::sync::atomic::AtomicU8,
1406}
1407
1408#[derive(Clone)]
1409pub struct RedDBRuntime {
1410    // Field order matters: drain workers before dropping the foreground inner.
1411    // Temporary handles used by workers do not own their own shutdown guard.
1412    background_tasks: Option<Arc<background_tasks::RuntimeBackgroundTasks>>,
1413    inner: Arc<RuntimeInner>,
1414}
1415
1416pub struct RuntimeConnection {
1417    id: u64,
1418    uses_pool_slot: bool,
1419    background_tasks: Option<Arc<background_tasks::RuntimeBackgroundTasks>>,
1420    inner: Arc<RuntimeInner>,
1421}
1422
1423pub struct CausalSession {
1424    runtime: RedDBRuntime,
1425    bookmark: Option<crate::replication::CausalBookmark>,
1426    wait_timeout: std::time::Duration,
1427}
1428
1429impl CausalSession {
1430    pub fn bookmark_token(&self) -> Option<String> {
1431        self.bookmark.map(|bookmark| bookmark.encode())
1432    }
1433
1434    pub fn inject_bookmark(&mut self, token: &str) -> RedDBResult<()> {
1435        let bookmark = crate::replication::CausalBookmark::decode(token)
1436            .map_err(|err| RedDBError::InvalidOperation(err.to_string()))?;
1437        self.bookmark = Some(bookmark);
1438        Ok(())
1439    }
1440
1441    pub fn execute_query(&mut self, query: &str) -> RedDBResult<RuntimeQueryResult> {
1442        if is_select_query_text(query) {
1443            if let Some(bookmark) = self.bookmark {
1444                self.runtime
1445                    .wait_for_bookmark(&bookmark, self.wait_timeout)?;
1446            }
1447        }
1448        let result = self.runtime.execute_query(query)?;
1449        if let Some(token) = result.bookmark.as_deref() {
1450            self.inject_bookmark(token)?;
1451        }
1452        Ok(result)
1453    }
1454}
1455
1456fn is_select_query_text(query: &str) -> bool {
1457    query
1458        .trim_start()
1459        .get(..6)
1460        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("select"))
1461}
1462
1463pub mod ai;
1464mod allocator_pressure;
1465pub mod analytics_schema_registry;
1466pub(crate) mod analytics_source_catalog;
1467pub mod ask_pipeline;
1468pub mod audit_log;
1469pub mod audit_query;
1470pub mod authorized_search;
1471pub(crate) mod authz;
1472mod background_tasks;
1473pub mod batch_insert;
1474pub mod blockchain_kind;
1475mod collection_contract;
1476pub mod config_matrix;
1477pub mod config_overlay;
1478pub mod config_watcher;
1479pub mod continuous_materialized_view;
1480pub mod control_events;
1481pub(crate) mod ddl;
1482pub mod disk_space_monitor;
1483mod dml_target_scan;
1484pub mod evidence_export;
1485pub(crate) mod execution_context;
1486mod expr_eval;
1487mod graph_dsl;
1488mod graph_tvf;
1489mod health_connection;
1490mod impl_audit_control;
1491mod impl_backup;
1492mod impl_catalog_accessors;
1493mod impl_cdc;
1494mod impl_config;
1495mod impl_config_secret;
1496pub(crate) mod impl_core;
1497mod impl_core_outer_scope;
1498mod impl_core_result_cache_scopes;
1499mod impl_ddl;
1500mod impl_dml;
1501mod impl_dml_batch;
1502mod impl_dml_chain;
1503mod impl_dml_claim;
1504mod impl_dml_crypto;
1505mod impl_dml_returning;
1506mod impl_dml_support;
1507mod impl_dml_tenant;
1508mod impl_dml_ttl;
1509mod impl_dml_update_analysis;
1510mod impl_dml_update_target;
1511mod impl_ec;
1512pub mod impl_ephemeral;
1513mod impl_events;
1514mod impl_fast_path;
1515mod impl_graph;
1516mod impl_graph_commands;
1517pub mod impl_kv;
1518mod impl_lifecycle;
1519mod impl_materialized_view;
1520mod impl_migrations;
1521mod impl_native;
1522mod impl_physical;
1523mod impl_primary_replica_file;
1524mod impl_probabilistic;
1525pub mod impl_queue;
1526mod impl_ranking;
1527mod impl_replica_loop;
1528mod impl_replication_commit;
1529mod impl_runtime_index_registry;
1530mod impl_telemetry_accessors;
1531mod impl_tenant_registry;
1532pub(crate) use impl_queue::RedwireWaitOutcome;
1533pub(crate) mod claim_telemetry;
1534#[cfg(test)]
1535mod evaluator_differential;
1536mod function_budget;
1537pub(crate) mod function_catalog;
1538mod function_execution;
1539mod function_validation;
1540mod impl_scrub;
1541mod impl_search;
1542mod impl_serverless;
1543mod impl_timeseries;
1544mod impl_tree;
1545mod impl_vcs;
1546mod index_store;
1547#[cfg(test)]
1548pub(crate) use index_store::MutationTestPhase;
1549pub mod integrity_tombstone;
1550mod join_filter;
1551mod keyed_spine;
1552pub(crate) mod kv_read;
1553pub mod kv_watch;
1554pub(crate) mod kv_write;
1555pub mod lease_lifecycle;
1556pub mod lease_loop;
1557pub mod lease_timer_wheel;
1558pub mod lifecycle;
1559pub mod lock_manager;
1560pub mod locking;
1561pub(crate) mod materialization_limit;
1562/// Samples every governed pool's live usage into the shared accounting
1563/// (ADR 0073 §2).
1564pub mod memory_accounting;
1565pub(crate) mod memory_admission;
1566pub(crate) mod metric_descriptor_catalog;
1567pub(crate) mod mutation;
1568#[cfg(test)]
1569mod mutation_index_topology_tests;
1570#[cfg(test)]
1571mod mutation_memory_tests;
1572pub(crate) mod mvcc_lifecycle;
1573pub(crate) mod mvcc_maintenance;
1574pub(crate) mod node_load_telemetry;
1575pub(crate) mod occupancy_sampler;
1576pub(crate) mod primary_queue_store;
1577mod probabilistic_store;
1578pub mod query_audit;
1579pub(crate) mod query_budget;
1580pub(crate) mod query_exec;
1581pub(crate) mod query_latency_telemetry;
1582pub mod query_request;
1583pub(crate) mod queue_lifecycle;
1584pub(crate) mod queue_telemetry;
1585pub(crate) mod queue_wait_registry;
1586pub mod quota_bucket;
1587pub(crate) mod ranking_descriptor_catalog;
1588mod record_search;
1589mod red_schema;
1590pub(crate) mod replica_queue_store;
1591pub mod resource_limits;
1592mod result_cache_runtime;
1593pub(crate) mod retention_filter;
1594pub(crate) mod retention_sweeper;
1595mod rls_injection;
1596pub mod schema_diff;
1597pub mod schema_vocabulary;
1598pub(crate) mod score_sketch;
1599mod search_graph;
1600pub(crate) mod sessionize;
1601pub mod signed_chain;
1602pub mod signed_writes_kind;
1603pub(crate) mod slo_descriptor_catalog;
1604pub mod snapshot_reuse;
1605mod statement_frame;
1606mod table_row_mvcc_resolver;
1607pub(crate) mod transaction_state;
1608pub mod turbo_crash_inject;
1609mod unique_index_admission;
1610mod vcs_command;
1611mod vector_index;
1612pub mod vector_turbo_kind;
1613pub(crate) mod window_phase;
1614pub mod within_clause;
1615pub mod write_gate;
1616
1617pub use self::claim_telemetry::ClaimTelemetrySnapshot;
1618pub use self::graph_dsl::*;
1619use self::join_filter::*;
1620use self::query_exec::*;
1621use self::record_search::*;
1622pub use self::statement_frame::EffectiveScope;
1623
1624/// Re-exports for transports + tests that need per-connection
1625/// isolation, tenant / auth thread-locals, and MVCC snapshot
1626/// utilities. Mirrors what PG-wire / gRPC / HTTP middleware already
1627/// call, and is enough to emulate independent connections in
1628/// integration tests.
1629pub mod mvcc {
1630    pub use super::impl_core::{
1631        capture_current_snapshot, clear_current_auth_identity, clear_current_connection_id,
1632        clear_current_snapshot, clear_current_tenant, current_connection_id, current_tenant,
1633        entity_visible_under_current_snapshot, entity_visible_with_context,
1634        set_current_auth_identity, set_current_connection_id, set_current_snapshot,
1635        set_current_tenant, snapshot_bundle, with_snapshot_bundle, SnapshotBundle, SnapshotContext,
1636    };
1637}
1638
1639/// Public helpers re-exported for use by the presentation layer.
1640pub mod record_search_helpers {
1641    use crate::storage::query::UnifiedRecord;
1642    use crate::storage::UnifiedEntity;
1643    use std::collections::BTreeSet;
1644
1645    pub fn entity_type_and_capabilities(
1646        entity: &UnifiedEntity,
1647    ) -> (&'static str, BTreeSet<String>) {
1648        super::record_search::runtime_entity_type_and_capabilities(entity)
1649    }
1650
1651    /// Materialise any entity kind (TableRow, Node, Edge, Vector,
1652    /// TimeSeriesPoint, QueueMessage) into a `UnifiedRecord` whose
1653    /// `values` carry the native fields. Used by the RLS evaluator
1654    /// when a non-table collection matches a `CompareExpr` policy.
1655    pub fn any_record_from_entity(entity: UnifiedEntity) -> Option<UnifiedRecord> {
1656        super::record_search::runtime_any_record_from_entity(entity)
1657    }
1658}