Skip to main content

reddb_server/runtime/
impl_lifecycle.rs

1//! Runtime bootstrap / constructor / handle accessors.
2//!
3//! Extracted verbatim from `impl_core.rs` (impl_core slice 8/10, issue #1629).
4//! Houses the in-memory / options constructors, the ~800-line `with_pool`
5//! constructor (moved verbatim — restructuring it is future work), snapshot
6//! rehydration and materialized-view backing lifecycle, system keyed-collection
7//! bootstrap, and the db / index-store / schema-vocabulary / auth-store /
8//! oauth / browser-token / registry handle accessors.
9//!
10//! - **Free helpers** — `view_records_to_entities`,
11//!   `system_keyed_collection_contract`, `table_row_index_fields`.
12use super::impl_config_secret::seed_storage_deploy_config;
13use super::*;
14
15/// Convert the rows produced by a materialized-view body into
16/// `UnifiedEntity` table rows targeting the backing collection.
17/// Issue #595 slice 9c — feeds `UnifiedStore::refresh_collection`.
18///
19/// Graph fragments and vector hits are ignored: a materialized view
20/// is a relational result set (SELECT-shaped); slices 11+ may extend
21/// this once we have a richer view body shape. Each row materialises
22/// the union of its schema-bound columns + overflow.
23pub(crate) fn view_records_to_entities(
24    table: &str,
25    records: &[crate::storage::query::unified::UnifiedRecord],
26) -> Vec<crate::storage::UnifiedEntity> {
27    use std::collections::HashMap;
28    let table_arc: std::sync::Arc<str> = std::sync::Arc::from(table);
29    let mut out = Vec::with_capacity(records.len());
30    for record in records {
31        let mut named: HashMap<String, reddb_types::Value> = HashMap::new();
32        for (name, value) in record.iter_fields() {
33            named.insert(name.to_string(), value.clone());
34        }
35        let entity = crate::storage::UnifiedEntity::new(
36            crate::storage::EntityId::new(0),
37            crate::storage::EntityKind::TableRow {
38                table: std::sync::Arc::clone(&table_arc),
39                row_id: 0,
40            },
41            crate::storage::EntityData::Row(crate::storage::RowData {
42                columns: Vec::new(),
43                named: Some(named),
44                schema: None,
45            }),
46        );
47        out.push(entity);
48    }
49    out
50}
51
52fn system_keyed_collection_contract(
53    name: &str,
54    model: crate::catalog::CollectionModel,
55) -> crate::physical::CollectionContract {
56    let now = crate::utils::now_unix_millis() as u128;
57    crate::physical::CollectionContract {
58        name: name.to_string(),
59        declared_model: model,
60        schema_mode: crate::catalog::SchemaMode::Dynamic,
61        origin: crate::physical::ContractOrigin::Implicit,
62        version: 1,
63        created_at_unix_ms: now,
64        updated_at_unix_ms: now,
65        default_ttl_ms: None,
66        vector_dimension: None,
67        vector_metric: None,
68        context_index_fields: Vec::new(),
69        declared_columns: Vec::new(),
70        table_def: None,
71        timestamps_enabled: false,
72        context_index_enabled: false,
73        metrics_raw_retention_ms: None,
74        metrics_rollup_policies: Vec::new(),
75        metrics_tenant_identity: None,
76        metrics_namespace: None,
77        append_only: false,
78        subscriptions: Vec::new(),
79        analytics_config: Vec::new(),
80        session_key: None,
81        session_gap_ms: None,
82        retention_duration_ms: None,
83        analytical_storage: None,
84
85        ai_policy: None,
86    }
87}
88
89pub(crate) fn table_row_index_fields(
90    entity: &crate::storage::unified::entity::UnifiedEntity,
91) -> Vec<(String, reddb_types::Value)> {
92    let crate::storage::EntityData::Row(row) = &entity.data else {
93        return Vec::new();
94    };
95    if let Some(named) = &row.named {
96        return named
97            .iter()
98            .map(|(name, value)| (name.clone(), value.clone()))
99            .collect();
100    }
101    if let Some(schema) = &row.schema {
102        return schema
103            .iter()
104            .zip(row.columns.iter())
105            .map(|(name, value)| (name.clone(), value.clone()))
106            .collect();
107    }
108    Vec::new()
109}
110
111impl RedDBRuntime {
112    pub fn in_memory() -> RedDBResult<Self> {
113        Self::with_options(RedDBOptions::in_memory())
114    }
115
116    pub fn flush(&self) -> RedDBResult<()> {
117        let store = self.inner.db.store();
118        let publication = store.vault_publication_lock.lock();
119        self.inner
120            .db
121            .flush_local_only()
122            .map_err(|err| RedDBError::Internal(err.to_string()))?;
123        self.index_store_ref().clear_paged_btree_overlays();
124        drop(publication);
125        self.inner
126            .db
127            .upload_to_remote_backend()
128            .map_err(|err| RedDBError::Internal(err.to_string()))
129    }
130
131    /// Handle to the intent-lock manager for tests + introspection.
132    /// Production code acquires via `LockerGuard::new(rt.lock_manager())`
133    /// rather than touching the manager directly.
134    pub fn lock_manager(&self) -> std::sync::Arc<crate::runtime::lock_manager::LockManager> {
135        self.inner.lock_manager.clone()
136    }
137
138    /// Process-local governance registry for managed policy/config guardrails.
139    pub fn config_registry(&self) -> std::sync::Arc<crate::auth::registry::ConfigRegistry> {
140        self.inner.config_registry.clone()
141    }
142
143    pub fn query_audit(&self) -> std::sync::Arc<crate::runtime::query_audit::QueryAuditStream> {
144        self.inner.query_audit.clone()
145    }
146
147    pub fn control_events_require_persistence(&self) -> bool {
148        self.inner.control_event_config.require_persistence()
149    }
150
151    pub fn control_event_config(&self) -> crate::runtime::control_events::ControlEventConfig {
152        self.inner.control_event_config
153    }
154
155    pub fn control_event_ledger(
156        &self,
157    ) -> Arc<dyn crate::runtime::control_events::ControlEventLedger> {
158        self.inner.control_event_ledger.read().clone()
159    }
160
161    #[doc(hidden)]
162    pub fn replace_control_event_ledger_for_tests(
163        &self,
164        ledger: Arc<dyn crate::runtime::control_events::ControlEventLedger>,
165    ) {
166        *self.inner.control_event_ledger.write() = ledger;
167    }
168
169    #[inline(never)]
170    pub fn with_options(options: RedDBOptions) -> RedDBResult<Self> {
171        Self::with_pool(options, ConnectionPoolConfig::default())
172    }
173
174    /// The memory budget resolved at boot (ADR 0073 §1). Immutable for the
175    /// process lifetime; echoed by the boot log and the `red.stats` budget
176    /// section.
177    pub fn memory_budget(&self) -> crate::storage::memory_budget::MemoryBudget {
178        self.inner.memory_budget
179    }
180
181    /// The one shared accounting pool (ADR 0073 §2). Per-pool shares are fixed
182    /// at boot; live usage is refreshed by
183    /// [`RedDBRuntime::refresh_memory_accounting`].
184    pub fn memory_accounting(&self) -> &crate::storage::memory_pools::MemoryAccounting {
185        &self.inner.memory_accounting
186    }
187
188    pub fn with_pool(
189        options: RedDBOptions,
190        pool_config: ConnectionPoolConfig,
191    ) -> RedDBResult<Self> {
192        Self::with_pool_and_limits(
193            options,
194            pool_config,
195            super::resource_limits::ResourceLimits::from_env(),
196        )
197    }
198
199    pub(super) fn with_pool_and_limits(
200        options: RedDBOptions,
201        pool_config: ConnectionPoolConfig,
202        resource_limits: super::resource_limits::ResourceLimits,
203    ) -> RedDBResult<Self> {
204        options
205            .replication
206            .validate_failover_profile()
207            .map_err(RedDBError::InvalidConfig)?;
208        // PLAN.md Phase 9.1 — capture wall-clock before storage
209        // open so the cold-start phase markers can be backfilled
210        // once Lifecycle is constructed below. Storage open
211        // encapsulates auto-restore + WAL replay; we treat the
212        // whole window as one combined "restore" + "wal_replay"
213        // phase split at the same boundary because the storage
214        // layer doesn't yet emit a finer signal.
215        let boot_open_start_ms = std::time::SystemTime::now()
216            .duration_since(std::time::UNIX_EPOCH)
217            .map(|d| d.as_millis() as u64)
218            .unwrap_or(0);
219        // ADR 0073 §1 — resolve the one memory budget before anything is
220        // opened, so a nonsensical operator value fails the boot before the
221        // process touches disk. The log line fires once per process.
222        let memory_budget = crate::storage::memory_budget::resolve_for_boot(
223            options.storage_profile.deploy_profile,
224            options.memory_budget_bytes,
225        )
226        .map_err(|err| RedDBError::InvalidConfig(err.to_string()))?;
227        crate::storage::memory_budget::log_resolved_once(&memory_budget);
228        // ADR 0073 §2 — divide the budget among the pools before any of them
229        // is constructed. `BudgetShares::resolve` asserts Σ(shares) ≤ budget;
230        // one boot log line per pool names its share.
231        let memory_shares = crate::storage::memory_pools::BudgetShares::resolve(
232            memory_budget,
233            options.storage_profile.deploy_profile,
234        );
235        memory_shares.log_once();
236        let embedded_single_file = options.storage_profile.deploy_profile
237            == crate::storage::DeployProfile::Embedded
238            && options.storage_profile.packaging == crate::storage::StoragePackaging::SingleFile;
239        let db = Arc::new(RedDB::open_with_options(&options).map_err(|err| {
240            match err.downcast::<crate::storage::StoreError>() {
241                Ok(store_err) => RedDBError::from(*store_err),
242                Err(err) => RedDBError::Internal(err.to_string()),
243            }
244        })?);
245        // Query results are disposable. Do not create a second persistent
246        // database outside the .rdb and its WAL for the cache.
247        let result_blob_cache_config = crate::storage::cache::BlobCacheConfig::default()
248            .with_l1_bytes_max(memory_shares.blob_cache_l1_bytes());
249        let result_blob_cache =
250            crate::storage::cache::BlobCache::open_with_l2(result_blob_cache_config).map_err(
251                |err| RedDBError::Internal(format!("open result Blob Cache L2 failed: {err:?}")),
252            )?;
253        let storage_ready_ms = std::time::SystemTime::now()
254            .duration_since(std::time::UNIX_EPOCH)
255            .map(|d| d.as_millis() as u64)
256            .unwrap_or(0);
257
258        let no_auth_boot = crate::service_cli::no_auth_active(&options);
259        let runtime = Self {
260            background_tasks: Some(Arc::new(background_tasks::RuntimeBackgroundTasks::default())),
261            inner: Arc::new(RuntimeInner {
262                functions: parking_lot::RwLock::new(
263                    super::function_catalog::FunctionCatalog::load(&db)?,
264                ),
265                db: db.clone(),
266                layout: PhysicalLayout::from_options(&options),
267                embedded_single_file,
268                memory_budget,
269                memory_accounting: Arc::new(
270                    crate::storage::memory_pools::MemoryAccounting::from_shares(
271                        memory_budget,
272                        memory_shares,
273                    ),
274                ),
275                memory_reservations: parking_lot::Mutex::new(
276                    super::memory_admission::MemoryReservations::default(),
277                ),
278                mvcc_maintenance: parking_lot::Mutex::new(Default::default()),
279                indices: IndexCatalog::register_default_vector_graph(
280                    options.has_capability(crate::api::Capability::Table),
281                    options.has_capability(crate::api::Capability::Graph),
282                ),
283                pool_config,
284                pool: Mutex::new(PoolState::default()),
285                execution_admission: parking_lot::RwLock::new(
286                    crate::transport::execution_admission::ExecutionAdmission::for_host(),
287                ),
288                execution_queue_timeout_ms: AtomicU64::new(30_000),
289                started_at_unix_ms: SystemTime::now()
290                    .duration_since(UNIX_EPOCH)
291                    .unwrap_or_default()
292                    .as_millis(),
293                probabilistic: super::probabilistic_store::ProbabilisticStore::new(),
294                index_store: super::index_store::IndexStore::new(),
295                cdc: crate::replication::cdc::CdcBuffer::new(100_000),
296                checkpoint_projection_stats: super::CheckpointProjectionStats::default(),
297                scrub_state: parking_lot::Mutex::new(super::ScrubRuntimeState::default()),
298                checkpoint_columnar_emission_budget_chunks: options
299                    .checkpoint_columnar_emission_budget_chunks,
300                columnar_projection_size_floor_rows: options.columnar_projection_size_floor_rows,
301                backup_scheduler: crate::replication::scheduler::BackupScheduler::new(3600),
302                query_cache: parking_lot::RwLock::new(
303                    crate::storage::query::planner::cache::PlanCache::new(1000),
304                ),
305                result_cache: parking_lot::RwLock::new((
306                    HashMap::new(),
307                    std::collections::VecDeque::new(),
308                )),
309                result_blob_cache,
310                result_blob_entries: parking_lot::RwLock::new((
311                    HashMap::new(),
312                    std::collections::VecDeque::new(),
313                )),
314                ask_answer_cache_entries: parking_lot::RwLock::new((
315                    HashSet::new(),
316                    std::collections::VecDeque::new(),
317                )),
318                result_cache_shadow_divergences: std::sync::atomic::AtomicU64::new(0),
319                result_cache_hits: std::sync::atomic::AtomicU64::new(0),
320                result_cache_misses: std::sync::atomic::AtomicU64::new(0),
321                result_cache_evictions: std::sync::atomic::AtomicU64::new(0),
322                ask_daily_spend: parking_lot::RwLock::new(HashMap::new()),
323                queue_message_locks: parking_lot::RwLock::new(HashMap::new()),
324                rmw_locks: RmwLockTable::new(),
325                planner_dirty_tables: parking_lot::RwLock::new(HashSet::new()),
326                ec_registry: Arc::new(crate::ec::config::EcRegistry::new()),
327                config_registry: Arc::new(crate::auth::registry::ConfigRegistry::new()),
328                ec_worker: crate::ec::worker::EcWorker::new(),
329                auth_store: parking_lot::RwLock::new(None),
330                oauth_validator: parking_lot::RwLock::new(None),
331                browser_token_authority: parking_lot::RwLock::new(None),
332                views: parking_lot::RwLock::new(HashMap::new()),
333                materialized_views: parking_lot::RwLock::new(
334                    crate::storage::cache::result::MaterializedViewCache::new(),
335                ),
336                retention_sweeper: parking_lot::RwLock::new(
337                    crate::runtime::retention_sweeper::RetentionSweeperState::new(),
338                ),
339                transaction_state: crate::runtime::transaction_state::TransactionState::new(),
340                env_config_overrides: crate::runtime::config_overlay::collect_env_overrides(),
341                lock_manager: Arc::new({
342                    // Sourced from the matrix: Tier B key
343                    // `concurrency.locking.deadlock_timeout_ms`
344                    // (default 5000). Env var wins at boot so
345                    // operators can tune without touching red_config.
346                    let env = crate::runtime::config_overlay::collect_env_overrides();
347                    let timeout_ms = env
348                        .get("concurrency.locking.deadlock_timeout_ms")
349                        .and_then(|raw| raw.parse::<u64>().ok())
350                        .unwrap_or_else(|| {
351                            match crate::runtime::config_matrix::default_for(
352                                "concurrency.locking.deadlock_timeout_ms",
353                            ) {
354                                Some(crate::serde_json::Value::Number(n)) => n as u64,
355                                _ => 5000,
356                            }
357                        });
358                    let cfg = crate::runtime::lock_manager::LockConfig {
359                        default_timeout: std::time::Duration::from_millis(timeout_ms),
360                        ..Default::default()
361                    };
362                    crate::runtime::lock_manager::LockManager::new(cfg)
363                }),
364                rls_policies: parking_lot::RwLock::new(HashMap::new()),
365                rls_enabled_tables: parking_lot::RwLock::new(HashSet::new()),
366                foreign_tables: Arc::new(crate::storage::fdw::ForeignTableRegistry::with_builtins()),
367                pending_tombstones: parking_lot::RwLock::new(HashMap::new()),
368                pending_versioned_updates: parking_lot::RwLock::new(HashMap::new()),
369                pending_queue_dedup: parking_lot::RwLock::new(HashMap::new()),
370                pending_kv_watch_events: parking_lot::RwLock::new(HashMap::new()),
371                pending_vault_writes: parking_lot::RwLock::new(HashMap::new()),
372                pending_store_wal_actions: parking_lot::RwLock::new(HashMap::new()),
373                pending_claim_locks: parking_lot::RwLock::new(HashMap::new()),
374                queue_wait_registry: std::sync::Arc::new(
375                    crate::runtime::queue_wait_registry::QueueWaitRegistry::new(),
376                ),
377                pending_queue_wakes: parking_lot::RwLock::new(HashMap::new()),
378                tenant_tables: parking_lot::RwLock::new(HashMap::new()),
379                ddl_epoch: std::sync::atomic::AtomicU64::new(0),
380                write_gate: Arc::new(crate::runtime::write_gate::WriteGate::from_options(
381                    &options,
382                )),
383                lifecycle: crate::runtime::lifecycle::Lifecycle::new(),
384                resource_limits,
385                query_budget_slots: AtomicU64::new(0),
386                audit_log: {
387                    // Default audit-log path for the in-memory case
388                    // sits in the system temp dir; persistent runs
389                    // place it next to the resolved data file.
390                    //
391                    // gh-471 iter 2: route through the resolved
392                    // `LogDestination`. Performance/Max tiers emit a
393                    // file-backed log destination under the file-owned
394                    // support-directory logs tier;
395                    // lower tiers / ephemeral runs report `Stderr`
396                    // and we keep the legacy file-next-to-data sink.
397                    // #1375 — single-file embedded mode keeps the data
398                    // directory to exactly the `.rdb` artifact, so the audit
399                    // log must NOT land as a sibling. Route it to a
400                    // process-unique temp location even when a data path is
401                    // set; only the non-embedded case uses the data dir.
402                    let data_path = if embedded_single_file || options.read_only {
403                        std::env::temp_dir()
404                            .join("reddb-embedded-runtime")
405                            .join(format!("audit-{}", std::process::id()))
406                    } else {
407                        options
408                            .data_path
409                            .clone()
410                            .unwrap_or_else(|| std::env::temp_dir().join("reddb"))
411                    };
412                    let (audit_dest, _) = crate::api::tier_wiring::current_log_destinations();
413                    let audit_dest = if options.read_only {
414                        crate::storage::layout::LogDestination::Stderr
415                    } else {
416                        audit_dest
417                    };
418                    if !matches!(audit_dest, crate::storage::layout::LogDestination::File(_))
419                        && (embedded_single_file
420                            || options.read_only
421                            || options
422                                .metadata
423                                .contains_key(crate::api::EPHEMERAL_RUNTIME_METADATA_KEY))
424                    {
425                        // The Stderr/Syslog lower-tier sink resolves to a
426                        // `for_data_path` sibling that collides across concurrent
427                        // temp-dir runtimes — nextest's process-per-test model
428                        // truncates one shared file, flaking audit assertions.
429                        // Pin a unique sibling for these short-lived ephemeral /
430                        // single-file embedded runtimes. The file-owned support-
431                        // dir tier (`File`) is already per-data unique, so leave
432                        // it to `for_destination` (#1375: the embedded audit then
433                        // still never lands a sibling next to the `.rdb`).
434                        let audit_path = reddb_file::layout::sibling_path(
435                            &data_path,
436                            &reddb_file::layout::sidecar_file_name(&data_path, "audit.log"),
437                        );
438                        Arc::new(crate::runtime::audit_log::AuditLogger::with_path(
439                            audit_path,
440                        ))
441                    } else {
442                        Arc::new(crate::runtime::audit_log::AuditLogger::for_destination(
443                            &audit_dest,
444                            &data_path,
445                        ))
446                    }
447                },
448                control_event_ledger: parking_lot::RwLock::new(Arc::new(
449                    crate::runtime::control_events::RuntimeLedger::new(db.store()),
450                )),
451                control_event_config: options.control_events,
452                query_audit: Arc::new(crate::runtime::query_audit::QueryAuditStream::new(
453                    db.store(),
454                    options.query_audit.clone(),
455                )),
456                lease_lifecycle: std::sync::OnceLock::new(),
457                replica_apply_metrics: std::sync::Arc::new(
458                    crate::replication::logical::ReplicaApplyMetrics::default(),
459                ),
460                replica_link_metrics: std::sync::Arc::new(
461                    crate::replication::reconnect::ReplicaLinkMetrics::default(),
462                ),
463                quota_bucket: crate::runtime::quota_bucket::QuotaBucket::from_env(),
464                schema_vocabulary: parking_lot::RwLock::new(
465                    crate::runtime::schema_vocabulary::SchemaVocabulary::new(),
466                ),
467                slow_query_logger: {
468                    // Issue #205 — slow-query sink lives in the same
469                    // directory the audit log uses, so backup/restore
470                    // ships them together. Threshold + sample-pct
471                    // default conservatively (1 s, 100% sampling) so
472                    // emitted lines are rare and complete. Operators
473                    // tune via env / config matrix in a follow-up.
474                    //
475                    // gh-471 iter 2: same routing as the audit log —
476                    // `LogDestination::File(...)` for Performance/Max
477                    // lands under the file-owned support-directory logs tier;
478                    // lower tiers fall back to `red-slow.log` in the
479                    // data directory.
480                    // #1375 — see the audit-log note above: single-file mode
481                    // never writes the slow-query log as a sibling of the
482                    // `.rdb`. Route to a process-unique temp dir when embedded,
483                    // regardless of the data path.
484                    let fallback_dir = if embedded_single_file || options.read_only {
485                        std::env::temp_dir()
486                            .join("reddb-embedded-runtime")
487                            .join(format!("slow-{}", std::process::id()))
488                    } else {
489                        options
490                            .data_path
491                            .as_ref()
492                            .and_then(|p| p.parent().map(std::path::PathBuf::from))
493                            .unwrap_or_else(|| std::env::temp_dir().join("reddb"))
494                    };
495                    let threshold_ms = std::env::var("RED_SLOW_QUERY_THRESHOLD_MS")
496                        .ok()
497                        .and_then(|s| s.parse::<u64>().ok())
498                        .unwrap_or(1000);
499                    let sample_pct = std::env::var("RED_SLOW_QUERY_SAMPLE_PCT")
500                        .ok()
501                        .and_then(|s| s.parse::<u8>().ok())
502                        .unwrap_or(100);
503                    let (_, slow_dest) = crate::api::tier_wiring::current_log_destinations();
504                    let slow_dest = if options.read_only {
505                        crate::storage::layout::LogDestination::Stderr
506                    } else {
507                        slow_dest
508                    };
509                    crate::telemetry::slow_query_logger::SlowQueryLogger::for_destination(
510                        &slow_dest,
511                        &fallback_dir,
512                        threshold_ms,
513                        sample_pct,
514                    )
515                },
516                slow_query_store: crate::telemetry::slow_query_store::SlowQueryStore::new(
517                    crate::telemetry::slow_query_store::DEFAULT_CAP,
518                ),
519                kv_stats: crate::runtime::KvStatsCounters::default(),
520                metrics_ingest_stats: crate::runtime::MetricsIngestCounters::default(),
521                metrics_tenant_activity_stats:
522                    crate::runtime::MetricsTenantActivityCounters::default(),
523                claim_telemetry: Arc::new(
524                    crate::runtime::claim_telemetry::ClaimTelemetryCounters::default(),
525                ),
526                queue_telemetry: Arc::new(
527                    crate::runtime::queue_telemetry::QueueTelemetryCounters::default(),
528                ),
529                query_latency_telemetry: Arc::new(
530                    crate::runtime::query_latency_telemetry::QueryLatencyTelemetry::default(),
531                ),
532                occupancy_sampler: Arc::new(
533                    crate::runtime::occupancy_sampler::OccupancySampler::new(),
534                ),
535                node_load_telemetry: Arc::new(
536                    crate::runtime::node_load_telemetry::NodeLoadTelemetry::default(),
537                ),
538                queue_presence: Arc::new(
539                    crate::storage::queue::presence::ConsumerPresenceRegistry::new(),
540                ),
541                vector_introspection: Arc::new(
542                    crate::storage::vector::introspection::VectorIntrospectionRegistry::new(),
543                ),
544                kv_tag_index: crate::runtime::KvTagIndex::default(),
545                chain_tip_cache: parking_lot::Mutex::new(HashMap::new()),
546                chain_integrity_broken: parking_lot::Mutex::new(HashMap::new()),
547                integrity_tombstones: parking_lot::Mutex::new(Vec::new()),
548                integrity_tombstones_state: std::sync::atomic::AtomicU8::new(0),
549            }),
550        };
551
552        runtime.install_hash_candidate_admission();
553
554        // Issue #205 — install the process-wide OperatorEvent sink so
555        // emit sites buried in storage / replication / signal handlers
556        // can record without threading an `&AuditLogger` through every
557        // call stack. First registration wins; subsequent in-memory
558        // runtimes (test harnesses) fall through to tracing+eprintln.
559        crate::telemetry::operator_event::install_global_audit_sink(Arc::clone(
560            &runtime.inner.audit_log,
561        ));
562
563        // Issue #1238 — wire the slow-query telemetry substrate (ADR 0060).
564        // The logger dual-writes: file sink (existing) + ring store (new).
565        runtime
566            .inner
567            .slow_query_logger
568            .attach_store(Arc::clone(&runtime.inner.slow_query_store));
569
570        // PLAN.md Phase 9.1 — backfill cold-start phase markers
571        // from the wall-clock captured before storage open. The
572        // entire `RedDB::open_with_options` call covers both
573        // auto-restore (when configured) and WAL replay. We
574        // record both phases against the same boundary today;
575        // a follow-up will split them once the storage layer
576        // surfaces a finer-grained event.
577        runtime
578            .inner
579            .lifecycle
580            .set_restore_started_at_ms(boot_open_start_ms);
581        runtime
582            .inner
583            .lifecycle
584            .set_restore_ready_at_ms(storage_ready_ms);
585        runtime
586            .inner
587            .lifecycle
588            .set_wal_replay_started_at_ms(boot_open_start_ms);
589        runtime
590            .inner
591            .lifecycle
592            .set_wal_replay_ready_at_ms(storage_ready_ms);
593
594        let restored_cdc_lsn = runtime
595            .inner
596            .db
597            .replication
598            .as_ref()
599            .map(|repl| {
600                repl.logical_wal_spool
601                    .as_ref()
602                    .map(|spool| spool.current_lsn())
603                    .unwrap_or(0)
604            })
605            .unwrap_or(0)
606            .max(runtime.config_u64("red.config.timeline.last_archived_lsn", 0));
607        runtime.inner.cdc.set_current_lsn(restored_cdc_lsn);
608        runtime.rehydrate_snapshot_xid_floor()?;
609        assert!(runtime
610            .inner
611            .db
612            .runtime
613            .set(super::WeakRuntime(Arc::downgrade(&runtime.inner)))
614            .is_ok());
615        assert!(
616            runtime
617                .inner
618                .db
619                .store()
620                .snapshot_manager
621                .set(runtime.snapshot_manager())
622                .is_ok(),
623            "a new runtime owns the store transaction outcomes"
624        );
625        runtime
626            .bootstrap_system_keyed_collections()
627            .map_err(|err| RedDBError::Internal(format!("bootstrap system collections: {err}")))?;
628        runtime.rehydrate_declared_column_schemas();
629        // Registry restoration can checkpoint missing required projections.
630        // Register their projectors before that epoch.
631        super::control_event_index::prepare(&runtime)?;
632        super::queue_storage_index::prepare(&runtime)?;
633        runtime.rehydrate_runtime_index_registry()?;
634        if runtime
635            .db()
636            .store()
637            .config()
638            .resident_memory_bytes_max
639            .is_some()
640        {
641            runtime
642                .db()
643                .store()
644                .checkpoint_missing_secondary_indices()?;
645        }
646        runtime.rehydrate_kv_tags()?;
647        runtime
648            .load_probabilistic_state()
649            .map_err(|err| RedDBError::Internal(format!("load probabilistic state: {err}")))?;
650
651        // Phase 2.5.4: replay `tenant_tables.{table}.column` markers so
652        // tables declared via `TENANT BY (col)` survive restart. Each
653        // entry re-registers the auto-policy and flips RLS on again.
654        runtime.rehydrate_tenant_tables();
655        // Issue #593 slice 9a — replay persisted materialized-view
656        // descriptors so `CREATE MATERIALIZED VIEW v AS …` survives a
657        // restart. Runs after the system-keyed collections bootstrap
658        // and before the API opens.
659        runtime.rehydrate_materialized_view_descriptors()?;
660        runtime.recover_store_forks()?;
661        if let Some(repl) = &runtime.inner.db.replication {
662            repl.wal_buffer.set_current_lsn(restored_cdc_lsn);
663        }
664
665        // Save system info to red_config on boot
666        {
667            let sys = SystemInfo::collect();
668            runtime.inner.db.store().set_config_tree(
669                "red.system",
670                &crate::serde_json::json!({
671                    "pid": sys.pid,
672                    "cpu_cores": sys.cpu_cores,
673                    "total_memory_bytes": sys.total_memory_bytes,
674                    "available_memory_bytes": sys.available_memory_bytes,
675                    "os": sys.os,
676                    "arch": sys.arch,
677                    "hostname": sys.hostname,
678                    "started_at": SystemTime::now()
679                        .duration_since(UNIX_EPOCH)
680                        .unwrap_or_default()
681                        .as_millis() as u64
682                }),
683            );
684
685            // Seed defaults on first boot (only if red_config is empty or missing defaults)
686            let store = runtime.inner.db.store();
687            if store
688                .get_collection("red_config")
689                .map(|m| m.query_all(|_| true).len())
690                .unwrap_or(0)
691                <= 10
692            {
693                store.set_config_tree("red.ai", &crate::json!({
694                    "default": crate::json!({
695                        "provider": "openai",
696                        "model": crate::ai::DEFAULT_OPENAI_PROMPT_MODEL
697                    }),
698                    "max_embedding_inputs": 256,
699                    "max_prompt_batch": 256,
700                    "timeout": crate::json!({ "connect_secs": 10, "read_secs": 90, "write_secs": 30 })
701                }));
702                store.set_config_tree(
703                    "red.server",
704                    &crate::json!({
705                        "max_scan_limit": 1000,
706                        "max_body_size": 1048576,
707                        "read_timeout_ms": 5000,
708                        "write_timeout_ms": 5000
709                    }),
710                );
711                store.set_config_tree(
712                    "red.storage",
713                    &crate::json!({
714                        "page_size": 4096,
715                        "page_cache_capacity": 100000,
716                        "auto_checkpoint_pages": 1000,
717                        "snapshot_retention": 16,
718                        "verify_checksums": true,
719                        "segment": crate::json!({
720                            "max_entities": 100000,
721                            "max_bytes": 268435456_u64,
722                            "compression_level": 6
723                        }),
724                        "hnsw": crate::json!({ "m": 16, "ef_construction": 100, "ef_search": 50 }),
725                        "ivf": crate::json!({ "n_lists": 100, "n_probes": 10 }),
726                        "bm25": crate::json!({ "k1": 1.2, "b": 0.75 })
727                    }),
728                );
729                store.set_config_tree(
730                    "red.search",
731                    &crate::json!({
732                        "rag": crate::json!({
733                            "max_chunks_per_source": 10,
734                            "max_total_chunks": 25,
735                            "similarity_threshold": 0.8,
736                            "graph_depth": 2,
737                            "min_relevance": 0.3
738                        }),
739                        "fusion": crate::json!({
740                            "vector_weight": 0.5,
741                            "graph_weight": 0.3,
742                            "table_weight": 0.2,
743                            "dedup_threshold": 0.85
744                        })
745                    }),
746                );
747                store.set_config_tree(
748                    "red.auth",
749                    &crate::json!({
750                        "enabled": false,
751                        "session_ttl_secs": 3600,
752                        "require_auth": false
753                    }),
754                );
755                store.set_config_tree(
756                    "red.query",
757                    &crate::json!({
758                        "connection_pool": crate::json!({ "max_connections": 64, "max_idle": 16 }),
759                        "max_recursion_depth": 1000
760                    }),
761                );
762                store.set_config_tree(
763                    "red.indexes",
764                    &crate::json!({
765                        "auto_select": true,
766                        "bloom_filter": crate::json!({
767                            "enabled": true,
768                            "false_positive_rate": 0.01,
769                            "prune_on_scan": true
770                        }),
771                        "hash": crate::json!({ "enabled": true }),
772                        "bitmap": crate::json!({ "enabled": true, "max_cardinality": 1000 }),
773                        "spatial": crate::json!({ "enabled": true })
774                    }),
775                );
776                store.set_config_tree(
777                    "red.probabilistic",
778                    &crate::json!({
779                        "hll_registers": 16384,
780                        "sketch_default_width": 1000,
781                        "sketch_default_depth": 5,
782                        "filter_default_capacity": 100000
783                    }),
784                );
785                store.set_config_tree(
786                    "red.timeseries",
787                    &crate::json!({
788                        "default_chunk_size": 1024,
789                        "compression": crate::json!({
790                            "timestamps": "delta_of_delta",
791                            "values": "gorilla_xor"
792                        }),
793                        "default_retention_days": 0
794                    }),
795                );
796                store.set_config_tree(
797                    "red.queue",
798                    &crate::json!({
799                        "default_max_size": 0,
800                        "default_max_attempts": 3,
801                        "visibility_timeout_ms": 30000,
802                        "consumer_idle_timeout_ms": 60000
803                    }),
804                );
805                store.set_config_tree(
806                    "red.backup",
807                    &crate::json!({
808                        "enabled": false,
809                        "interval_secs": 3600,
810                        "retention_count": 24,
811                        "upload": false,
812                        "backend": "local"
813                    }),
814                );
815                store.set_config_tree(
816                    "red.wal",
817                    &crate::json!({
818                        "archive": crate::json!({
819                            "enabled": false,
820                            "retention_hours": 168,
821                            "prefix": reddb_file::backup_wal_prefix("")
822                        })
823                    }),
824                );
825                store.set_config_tree(
826                    "red.cdc",
827                    &crate::json!({
828                        "enabled": true,
829                        "buffer_size": 100000
830                    }),
831                );
832                store.set_config_tree(
833                    "red.config.secret",
834                    &crate::json!({
835                        "auto_encrypt": true,
836                        "auto_decrypt": true
837                    }),
838                );
839            }
840
841            // Perf-parity config matrix: heal the Tier A (critical)
842            // keys unconditionally on every boot. Idempotent — only
843            // writes the default when the key is missing. Keeps
844            // `SHOW CONFIG` showing every guarantee the operator has
845            // (durability.mode, concurrency.locking.enabled, …) even
846            // on long-running datadirs that predate the matrix.
847            crate::runtime::config_matrix::heal_critical_keys(store.as_ref());
848            seed_storage_deploy_config(store.as_ref(), options.storage_profile);
849
850            // Phase 5 — Lehman-Yao runtime flag. Read the Tier A
851            // `storage.btree.lehman_yao` value from the matrix (env
852            // > file > red_config > default) and publish it to the
853            // storage layer's atomic so the B-tree read / split
854            // paths can branch without re-reading the config on
855            // every hot-path call.
856            let lehman_yao = runtime.config_bool("storage.btree.lehman_yao", true);
857            crate::storage::engine::btree::lehman_yao::set_enabled(lehman_yao);
858            if lehman_yao {
859                tracing::info!(
860                    "storage.btree.lehman_yao=true — lock-free concurrent descent enabled"
861                );
862            }
863
864            // Config file overlay — mounted `/etc/reddb/config.json`
865            // (override path via REDDB_CONFIG_FILE). Writes keys with
866            // write-if-absent semantics so a later user `SET CONFIG`
867            // always wins. Missing file = silent no-op.
868            let overlay_path = crate::runtime::config_overlay::config_file_path();
869            let _ =
870                crate::runtime::config_overlay::apply_config_file(store.as_ref(), &overlay_path);
871        }
872
873        // VCS ("Git for Data") — create the `red_*` metadata
874        // collections on first boot. Idempotent: `get_or_create_collection`
875        // is a no-op if the collection already exists.
876        {
877            let store = runtime.inner.db.store();
878            for name in crate::application::vcs_collections::ALL {
879                let _ = store.get_or_create_collection(*name);
880            }
881            // Seed VCS config namespace with sensible defaults on first
882            // boot, matching the pattern used by red.ai / red.storage.
883            store.set_config_tree(
884                crate::application::vcs_collections::CONFIG_NAMESPACE,
885                &crate::json!({
886                    "default_branch": "main",
887                    "author": crate::json!({
888                        "name": "reddb",
889                        "email": "reddb@localhost"
890                    }),
891                    "protected_branches": crate::json!(["main"]),
892                    "closure": crate::json!({
893                        "enabled": true,
894                        "lazy": true
895                    }),
896                    "merge": crate::json!({
897                        "default_strategy": "auto",
898                        "fast_forward": true
899                    })
900                }),
901            );
902        }
903
904        // Migrations — create the `red_migrations` / `red_migration_deps`
905        // system collections on first boot. Idempotent.
906        {
907            let store = runtime.inner.db.store();
908            for name in crate::application::migration_collections::ALL {
909                let _ = store.get_or_create_collection(*name);
910            }
911        }
912
913        // Topology graph (#803) — ensure the built-in `red.topology.cluster`
914        // graph collection (declared WITH ANALYTICS) and its metadata sidecar
915        // exist. Idempotent and survives restarts via the WAL-backed contract.
916        let _ = crate::application::topology_collections::ensure(&runtime);
917
918        // Bootstrapping topology can publish a metadata checkpoint. Register
919        // the optional COUNT projection only after that publication, so old
920        // data is not backfilled before readiness. Queries scan until the next
921        // checkpoint publishes the projection.
922        runtime.prepare_paged_counts()?;
923
924        // #1369 — reserve a fixed internal-id floor so the first user-inserted
925        // entity always receives a stable, documented `rid` (FIRST_USER_ENTITY_ID),
926        // independent of how many internal collection-descriptor / config-default
927        // entities the boot sequence seeded above. `register_entity_id` only ever
928        // raises the allocator, so a database that already holds user data
929        // (counter past the floor) is untouched; a freshly-seeded database jumps
930        // straight to the floor.
931        runtime
932            .inner
933            .db
934            .store()
935            .register_entity_id(crate::storage::EntityId::new(
936                crate::storage::FIRST_USER_ENTITY_ID - 1,
937            ));
938
939        // Start background maintenance thread (context index refresh +
940        // session purge). Held by a WEAK reference to `RuntimeInner`
941        // to avoid an ownership cycle. The last foreground owner unparks
942        // and joins the worker before releasing its inner reference, so
943        // an active weak upgrade cannot retain the pager lock after close.
944        // The 60-second work cadence is tracked via `last_work`.
945        //
946        // The previous version captured `rt = runtime.clone()` by
947        // strong reference and ran an unterminated `loop`, which held
948        // Arc<RuntimeInner> forever — reopening a persistent database
949        // in the same process failed with "Database is locked" because
950        // the pager could never drop. See the regression test
951        // `finding_1_select_after_bulk_insert_persistent_reopen`.
952        {
953            let weak = Arc::downgrade(&runtime.inner);
954            runtime
955                .background_tasks
956                .as_ref()
957                .expect("foreground runtime")
958                .spawn(
959                    std::thread::Builder::new().name("reddb-maintenance".into()),
960                    move |stopped| {
961                        let tick = std::time::Duration::from_millis(200);
962                        let work_interval = std::time::Duration::from_secs(60);
963                        let mut last_work = std::time::Instant::now();
964                        let mut allocator_pressure =
965                            super::allocator_pressure::AllocatorPressure::default();
966                        loop {
967                            std::thread::park_timeout(tick);
968                            if stopped.load(AtomicOrdering::Acquire) {
969                                break;
970                            }
971                            let Some(inner) = weak.upgrade() else {
972                                // All strong references dropped — the
973                                // runtime is gone, exit cleanly.
974                                break;
975                            };
976                            if last_work.elapsed() >= work_interval {
977                                let _stats = inner.db.store().context_index().stats();
978                                last_work = std::time::Instant::now();
979                            }
980                            let rt = RedDBRuntime {
981                                background_tasks: None,
982                                inner,
983                            };
984                            rt.try_reclaim_history_tick();
985                            allocator_pressure.tick();
986                        }
987                    },
988                );
989        }
990
991        // Start backup scheduler if enabled via red_config
992        {
993            let store = runtime.inner.db.store();
994            let mut backup_enabled = false;
995            let mut backup_interval = 3600u64;
996
997            if let Some(manager) = store.get_collection("red_config") {
998                manager.for_each_entity(|entity| {
999                    if let Some(row) = entity.data.as_row() {
1000                        let key = row.get_field("key").and_then(|v| match v {
1001                            reddb_types::Value::Text(s) => Some(s.as_ref()),
1002                            _ => None,
1003                        });
1004                        let val = row.get_field("value");
1005                        if key == Some("red.config.backup.enabled") {
1006                            backup_enabled = match val {
1007                                Some(reddb_types::Value::Boolean(true)) => true,
1008                                Some(reddb_types::Value::Text(s)) => &**s == "true",
1009                                _ => false,
1010                            };
1011                        } else if key == Some("red.config.backup.interval_secs") {
1012                            if let Some(reddb_types::Value::Integer(n)) = val {
1013                                backup_interval = *n as u64;
1014                            }
1015                        }
1016                    }
1017                    true
1018                });
1019            }
1020
1021            if backup_enabled {
1022                runtime.inner.backup_scheduler.set_interval(backup_interval);
1023                let rt = runtime.clone();
1024                runtime
1025                    .inner
1026                    .backup_scheduler
1027                    .start(move || rt.trigger_backup().map_err(|e| format!("{}", e)));
1028            }
1029        }
1030
1031        // Load EC registry from red_config and start worker
1032        {
1033            runtime
1034                .inner
1035                .ec_registry
1036                .load_from_config_store(runtime.inner.db.store().as_ref());
1037            if !runtime.inner.db.options().read_only
1038                && !runtime.inner.ec_registry.async_configs().is_empty()
1039            {
1040                runtime.inner.ec_worker.start(
1041                    Arc::clone(&runtime.inner.ec_registry),
1042                    Arc::clone(&runtime.inner.db.store()),
1043                );
1044            }
1045        }
1046
1047        if let (true, crate::replication::ReplicationRole::Replica { primary_addr }) = (
1048            runtime.inner.db.options().replica_loop_enabled
1049                && !runtime.inner.db.options().read_only,
1050            runtime.inner.db.options().replication.role.clone(),
1051        ) {
1052            let rt = runtime.clone();
1053            std::thread::Builder::new()
1054                .name("reddb-replica".into())
1055                .spawn(move || rt.run_replica_loop(primary_addr))
1056                .ok();
1057        }
1058
1059        // PLAN.md Phase 1 — Lifecycle Contract. Mark Ready once every
1060        // boot stage above has completed (WAL replay, restore-from-
1061        // remote, replica-loop spawn). Health probes flip from 503 to
1062        // 200 here; shutdown begins from this state.
1063        runtime.inner.lifecycle.mark_ready();
1064
1065        #[cfg(not(test))]
1066        if runtime
1067            .db()
1068            .store()
1069            .config()
1070            .resident_memory_bytes_max
1071            .is_some()
1072            && !runtime.db().options().read_only
1073        {
1074            runtime.start_count_projection_worker();
1075        }
1076
1077        // Issue #583 slice 10 — ContinuousMaterializedView scheduler.
1078        // Low-priority background ticker that drains the cache's
1079        // `claim_due_at` set every ~50ms. Holds only a Weak<RuntimeInner>
1080        // to avoid an ownership cycle; foreground close unparks and drains
1081        // an active refresh before releasing storage. Materialized views without
1082        // a `REFRESH EVERY` clause stay on the manual-refresh path
1083        // and are skipped by `claim_due_at`, so the loop is a no-op
1084        // when no scheduled views exist.
1085        {
1086            let weak_inner = Arc::downgrade(&runtime.inner);
1087            runtime
1088                .background_tasks
1089                .as_ref()
1090                .expect("foreground runtime")
1091                .spawn(
1092                    std::thread::Builder::new()
1093                        .name("reddb-mv-scheduler".into())
1094                        // Rust's default for spawned threads is 2 MiB, which is too
1095                        // small for the query-execution path that refresh_due_materialized_views
1096                        // runs (StatementExecutionFrame + guards per view). Match the
1097                        // 8 MiB that the OS gives the main thread.
1098                        .stack_size(8 * 1024 * 1024),
1099                    move |stopped| loop {
1100                        std::thread::park_timeout(std::time::Duration::from_millis(50));
1101                        if stopped.load(AtomicOrdering::Acquire) {
1102                            break;
1103                        }
1104                        let Some(inner) = weak_inner.upgrade() else {
1105                            break;
1106                        };
1107                        let rt = RedDBRuntime {
1108                            background_tasks: None,
1109                            inner,
1110                        };
1111                        rt.refresh_due_materialized_views();
1112                    },
1113                );
1114        }
1115
1116        // Issue #584 slice 12 — DeclarativeRetention background sweeper.
1117        // Low-priority ticker that physically reclaims rows whose
1118        // timestamp has fallen beyond the retention window. Holds a
1119        // `Weak<RuntimeInner>`; foreground close drains an active tick
1120        // before releasing storage (shutdown leaves storage consistent
1121        // because each tick goes through the standard DELETE path —
1122        // there is no half-finished mutation state to clean up). The
1123        // tick interval is intentionally longer than the MV scheduler
1124        // (500ms) because retention is order-of-seconds at minimum.
1125        if !runtime.write_gate().is_read_only() {
1126            let weak_inner = Arc::downgrade(&runtime.inner);
1127            runtime
1128                .background_tasks
1129                .as_ref()
1130                .expect("foreground runtime")
1131                .spawn(
1132                    std::thread::Builder::new().name("reddb-retention-sweeper".into()),
1133                    move |stopped| loop {
1134                        std::thread::park_timeout(std::time::Duration::from_millis(500));
1135                        if stopped.load(AtomicOrdering::Acquire) {
1136                            break;
1137                        }
1138                        let Some(inner) = weak_inner.upgrade() else {
1139                            break;
1140                        };
1141                        let rt = RedDBRuntime {
1142                            background_tasks: None,
1143                            inner,
1144                        };
1145                        rt.sweep_retention_tick(
1146                            crate::runtime::retention_sweeper::DEFAULT_SWEEPER_BATCH,
1147                        );
1148                        rt.sweep_individual_ttl_tick(
1149                            crate::runtime::retention_sweeper::DEFAULT_SWEEPER_BATCH,
1150                        );
1151                    },
1152                );
1153        }
1154
1155        // Anonymous access is the most consequential posture an operator can
1156        // choose. It was only ever announced on stderr; leave it in the
1157        // chained ledger too, so an audit of the store itself shows it.
1158        if no_auth_boot {
1159            use crate::runtime::control_events::{
1160                ActorRef, ControlEvent, ControlEventCtx, EventKind, Outcome,
1161            };
1162            let ledger = std::sync::Arc::clone(&runtime.inner.control_event_ledger.read());
1163            let ctx = ControlEventCtx {
1164                actor: ActorRef::System("boot"),
1165                scope: None,
1166                request_id: None,
1167                trace_id: None,
1168            };
1169            let event = ControlEvent {
1170                kind: EventKind::AuthDisabled,
1171                outcome: Outcome::Allowed,
1172                action: std::borrow::Cow::Borrowed("auth.disabled"),
1173                resource: Some("server".to_string()),
1174                reason: Some("--no-auth / --dev".to_string()),
1175                matched_policy_id: None,
1176                fields: std::collections::HashMap::new(),
1177            };
1178            if let Err(err) = ledger.emit(&ctx, event) {
1179                tracing::warn!(
1180                    target: "reddb::security",
1181                    error = %err,
1182                    "could not record the auth-disabled boot in the control-event ledger"
1183                );
1184            }
1185        }
1186
1187        Ok(runtime)
1188    }
1189
1190    fn rehydrate_snapshot_xid_floor(&self) -> RedDBResult<()> {
1191        let store = self.inner.db.store();
1192        let snapshot_manager = self.inner.transaction_state.snapshot_manager();
1193        let base_high_water_mark = store.startup_xid_high_water_mark();
1194        if let Some(high_water_mark) = base_high_water_mark {
1195            snapshot_manager.observe_committed_xid(high_water_mark);
1196        }
1197        for collection in store.list_collections() {
1198            let Some(manager) = store.get_collection(&collection) else {
1199                continue;
1200            };
1201            let observe = |entity: &crate::storage::UnifiedEntity| {
1202                snapshot_manager.observe_committed_xid(entity.xmin);
1203                snapshot_manager.observe_committed_xid(entity.xmax);
1204                true
1205            };
1206            if base_high_water_mark.is_some() {
1207                // The catalog covers the exact immutable roots. Committed WAL
1208                // replay remains resident and must still advance the floor.
1209                manager.for_each_entity(observe);
1210            } else {
1211                // Older or unproven generations require complete physical
1212                // validation, one bounded record at a time, before filtering.
1213                manager.try_for_each_entity(usize::MAX, observe)?;
1214            }
1215        }
1216        if base_high_water_mark.is_none() {
1217            store.remember_startup_xid_high_water_mark(
1218                snapshot_manager.peek_next_xid().saturating_sub(1),
1219            );
1220        }
1221        Ok(())
1222    }
1223
1224    /// Provision an empty Table-shaped collection that backs a
1225    /// `CREATE MATERIALIZED VIEW v` (issue #594 slice 9b of #575).
1226    /// `SELECT FROM v` reads this collection directly; the rewriter is
1227    /// configured to skip materialized views so the body is no longer
1228    /// substituted. REFRESH still writes to the cache slot — wiring it
1229    /// into this backing collection is the job of slice 9c.
1230    ///
1231    /// Idempotent: re-running for the same name leaves the existing
1232    /// collection in place (mirrors `CREATE TABLE IF NOT EXISTS`
1233    /// semantics). This keeps `CREATE OR REPLACE MATERIALIZED VIEW v`
1234    /// cheap — the body change does not invalidate already-buffered
1235    /// rows. Until 9c lands the backing is always empty anyway.
1236    pub(crate) fn ensure_materialized_view_backing(&self, name: &str) -> RedDBResult<()> {
1237        let store = self.inner.db.store();
1238        let mut changed = false;
1239        if store.get_collection(name).is_none() {
1240            store.get_or_create_collection(name);
1241            changed = true;
1242        }
1243        if self.inner.db.collection_contract(name).is_none() {
1244            self.inner
1245                .db
1246                .save_collection_contract(system_keyed_collection_contract(
1247                    name,
1248                    crate::catalog::CollectionModel::Table,
1249                ))
1250                .map_err(|err| RedDBError::Internal(err.to_string()))?;
1251            changed = true;
1252        }
1253        if changed {
1254            self.inner
1255                .db
1256                .persist_metadata()
1257                .map_err(|err| RedDBError::Internal(err.to_string()))?;
1258        }
1259        Ok(())
1260    }
1261
1262    /// Inverse of [`ensure_materialized_view_backing`] — drops the
1263    /// backing collection on `DROP MATERIALIZED VIEW v`. No-op when
1264    /// the collection was never created (e.g. a `DROP MATERIALIZED
1265    /// VIEW IF EXISTS v` against an unknown name).
1266    pub(crate) fn drop_materialized_view_backing(&self, name: &str) -> RedDBResult<()> {
1267        let store = self.inner.db.store();
1268        if store.get_collection(name).is_none() {
1269            return Ok(());
1270        }
1271        store
1272            .drop_collection(name)
1273            .map_err(|err| RedDBError::Internal(err.to_string()))?;
1274        // The contract may have been dropped already (DROP TABLE path)
1275        // — ignore "not found" errors by checking presence first.
1276        if self.inner.db.collection_contract(name).is_some() {
1277            self.inner
1278                .db
1279                .remove_collection_contract(name)
1280                .map_err(|err| RedDBError::Internal(err.to_string()))?;
1281        }
1282        self.invalidate_result_cache();
1283        self.inner
1284            .db
1285            .persist_metadata()
1286            .map_err(|err| RedDBError::Internal(err.to_string()))?;
1287        Ok(())
1288    }
1289
1290    fn bootstrap_system_keyed_collections(&self) -> RedDBResult<()> {
1291        let mut changed = false;
1292        for (name, model) in [
1293            ("red.config", crate::catalog::CollectionModel::Config),
1294            ("red.vault", crate::catalog::CollectionModel::Vault),
1295            // Issue #593 — materialized-view catalog. One row per
1296            // `CREATE MATERIALIZED VIEW`; rehydrated at boot before
1297            // the API opens.
1298            (
1299                crate::runtime::continuous_materialized_view::CATALOG_COLLECTION,
1300                crate::catalog::CollectionModel::Config,
1301            ),
1302        ] {
1303            if self.inner.db.store().get_collection(name).is_none() {
1304                self.inner.db.store().get_or_create_collection(name);
1305                changed = true;
1306            }
1307            if self.inner.db.collection_contract(name).is_none() {
1308                let contract = system_keyed_collection_contract(name, model);
1309                if self.inner.db.options().read_only {
1310                    self.inner.db.cache_read_only_bootstrap_contract(contract);
1311                } else {
1312                    self.inner
1313                        .db
1314                        .save_collection_contract(contract)
1315                        .map_err(|err| RedDBError::Internal(err.to_string()))?;
1316                }
1317                changed = true;
1318            }
1319        }
1320        if changed {
1321            self.inner
1322                .db
1323                .persist_metadata()
1324                .map_err(|err| RedDBError::Internal(err.to_string()))?;
1325        }
1326        Ok(())
1327    }
1328
1329    pub fn db(&self) -> Arc<RedDB> {
1330        Arc::clone(&self.inner.db)
1331    }
1332
1333    /// Direct access to the runtime's secondary-index store.
1334    /// Used by bulk-insert entry points (gRPC binary bulk, HTTP bulk,
1335    /// wire bulk) that need to push new rows through the per-index
1336    /// maintenance hook after `store.bulk_insert` returns.
1337    pub fn index_store_ref(&self) -> &super::index_store::IndexStore {
1338        &self.inner.index_store
1339    }
1340
1341    /// Apply a DDL event to the schema-vocabulary reverse index
1342    /// (issue #120). Called by DDL execution paths after the catalog
1343    /// mutation has succeeded so the index never holds entries for
1344    /// half-applied DDL.
1345    pub(crate) fn schema_vocabulary_apply(
1346        &self,
1347        event: crate::runtime::schema_vocabulary::DdlEvent,
1348    ) {
1349        self.inner.schema_vocabulary.write().on_ddl(event);
1350    }
1351
1352    /// Lookup `token` in the schema-vocabulary reverse index. Returns
1353    /// an owned `Vec<VocabHit>` because the underlying read lock
1354    /// cannot be borrowed across the call boundary; the slice from
1355    /// `SchemaVocabulary::lookup` is cloned per hit.
1356    pub fn schema_vocabulary_lookup(
1357        &self,
1358        token: &str,
1359    ) -> Vec<crate::runtime::schema_vocabulary::VocabHit> {
1360        self.inner.schema_vocabulary.read().lookup(token).to_vec()
1361    }
1362
1363    /// Inject an AuthStore into the runtime. Called by server boot
1364    /// after the vault has been bootstrapped, so that `Value::Secret`
1365    /// auto-encrypt/decrypt can reach the vault AES key.
1366    pub fn set_auth_store(&self, store: Arc<crate::auth::store::AuthStore>) {
1367        *self.inner.auth_store.write() = Some(store);
1368    }
1369
1370    /// Snapshot the current AuthStore (if any). Used by the wire listener
1371    /// to validate bearer tokens issued via HTTP `/auth/login`.
1372    pub fn auth_store(&self) -> Option<Arc<crate::auth::store::AuthStore>> {
1373        self.inner.auth_store.read().clone()
1374    }
1375
1376    /// Inject an `OAuthValidator` into the runtime. When set, HTTP and
1377    /// wire transports try OAuth JWT validation before falling back to
1378    /// the local AuthStore lookup. Pass `None` to disable.
1379    pub fn set_oauth_validator(&self, validator: Option<Arc<crate::auth::oauth::OAuthValidator>>) {
1380        *self.inner.oauth_validator.write() = validator;
1381    }
1382
1383    /// Returns a clone of the configured `OAuthValidator` Arc, if any.
1384    /// Hot path: called per HTTP request when an Authorization header
1385    /// is present, so we hand back a cheap Arc clone.
1386    pub fn oauth_validator(&self) -> Option<Arc<crate::auth::oauth::OAuthValidator>> {
1387        self.inner.oauth_validator.read().clone()
1388    }
1389
1390    /// Inject the browser-token authority (issue #936). When set, the
1391    /// RedWire WS handshake accepts the short-lived access JWT it mints
1392    /// (alongside, and tried before, the federated OAuth validator), and
1393    /// the `/auth/browser/*` HTTP endpoints can issue/rotate the pair.
1394    /// `None` leaves the browser credential flow inert.
1395    pub fn set_browser_token_authority(
1396        &self,
1397        authority: Option<Arc<crate::auth::browser_token::BrowserTokenAuthority>>,
1398    ) {
1399        *self.inner.browser_token_authority.write() = authority;
1400    }
1401
1402    /// Snapshot the browser-token authority, if wired. Read on the WS
1403    /// handshake path and by the `/auth/browser/*` handlers; a cheap Arc
1404    /// clone keeps the lock hold short.
1405    pub fn browser_token_authority(
1406        &self,
1407    ) -> Option<Arc<crate::auth::browser_token::BrowserTokenAuthority>> {
1408        self.inner.browser_token_authority.read().clone()
1409    }
1410}
1411
1412#[cfg(test)]
1413mod xid_resume_tests {
1414    use super::*;
1415    use reddb_engine::storage::collection_read::{CollectionCursor, CollectionRead, EncodedRecord};
1416
1417    struct Unreadable;
1418
1419    fn unavailable() -> crate::storage::StoreError {
1420        crate::storage::StoreError::Io(std::io::Error::other("XID bootstrap read a base payload"))
1421    }
1422
1423    impl CollectionRead for Unreadable {
1424        fn get_record(
1425            &self,
1426            id: crate::storage::EntityId,
1427            _: usize,
1428        ) -> Result<Option<EncodedRecord>, crate::storage::StoreError> {
1429            if id.raw() == 999 {
1430                Ok(None)
1431            } else {
1432                Err(unavailable())
1433            }
1434        }
1435        fn cursor(&self) -> Result<Box<dyn CollectionCursor + '_>, crate::storage::StoreError> {
1436            Err(unavailable())
1437        }
1438        fn owned_cursor(&self) -> Result<Box<dyn CollectionCursor>, crate::storage::StoreError> {
1439            Err(unavailable())
1440        }
1441    }
1442
1443    #[test]
1444    fn xid_resume_survives_pending_checkpoint_process_exit() {
1445        const FIXTURE: &str = "REDDB_XID_RESUME_CRASH_FIXTURE";
1446        let open = |path: std::path::PathBuf| {
1447            let options = RedDBOptions::persistent(path)
1448                .with_memory_budget(64 * 1024 * 1024)
1449                .with_storage_profile(
1450                    crate::storage::profile::StorageDeployPreset::PrimaryReplicaDev.selection(),
1451                )
1452                .expect("profile");
1453            crate::storage::RedDB::with_disk_residency_for_qualification(|| {
1454                RedDBRuntime::with_options(options)
1455            })
1456            .expect("crash recovery runtime")
1457        };
1458        if let Some(root) = std::env::var_os(FIXTURE) {
1459            let root = std::path::PathBuf::from(root);
1460            assert_eq!(
1461                std::fs::read_to_string(root.join("owned-fixture")).expect("owned fixture"),
1462                "xid-resume-crash-v1"
1463            );
1464            let runtime = open(root.join("crash.rdb"));
1465            for sql in [
1466                "CREATE TABLE crash_rows (id INTEGER, payload TEXT)",
1467                "INSERT INTO crash_rows (id, payload) VALUES (1, 'committed')",
1468                "BEGIN",
1469                "UPDATE crash_rows SET payload = 'pending' WHERE id = 1",
1470                "INSERT INTO crash_rows (id, payload) VALUES (2, 'pending')",
1471            ] {
1472                runtime.execute_query(sql).expect("crash fixture statement");
1473            }
1474            runtime
1475                .flush()
1476                .expect("checkpoint with pending transaction");
1477            std::fs::write(
1478                root.join("checkpoint-complete"),
1479                "pending transaction remains open",
1480            )
1481            .expect("acknowledged fixture checkpoint");
1482            // Deliberately skip all runtime destructors and rollback. The
1483            // parent must recover the committed preimage from the native file.
1484            std::process::exit(0);
1485        }
1486        let directory = tempfile::tempdir().expect("owned crash fixture");
1487        std::fs::write(
1488            directory.path().join("owned-fixture"),
1489            "xid-resume-crash-v1",
1490        )
1491        .expect("ownership marker");
1492        let child = std::process::Command::new(std::env::current_exe().expect("test executable"))
1493            .args([
1494                "--exact",
1495                "runtime::impl_lifecycle::xid_resume_tests::xid_resume_survives_pending_checkpoint_process_exit",
1496                "--test-threads=1",
1497            ])
1498            .env(FIXTURE, directory.path())
1499            .output()
1500            .expect("crashing owned child");
1501        assert!(
1502            child.status.success(),
1503            "{}",
1504            String::from_utf8_lossy(&child.stderr)
1505        );
1506        assert!(directory.path().join("checkpoint-complete").is_file());
1507        let path = directory.path().join("crash.rdb");
1508        assert!(path.is_file());
1509        let runtime = open(path.clone());
1510        let result = runtime
1511            .execute_query("SELECT id, payload FROM crash_rows ORDER BY id")
1512            .expect("committed preimage");
1513        assert_eq!(
1514            result.result.records.len(),
1515            1,
1516            "pending insert must stay invisible"
1517        );
1518        assert_eq!(result.result.records[0].get("id"), Some(&Value::Integer(1)));
1519        assert_eq!(
1520            result.result.records[0].get("payload"),
1521            Some(&Value::text("committed"))
1522        );
1523        runtime
1524            .execute_query("INSERT INTO crash_rows (id, payload) VALUES (3, 'after')")
1525            .expect("new writer after recovery");
1526        runtime.flush().expect("recovered checkpoint");
1527        drop(runtime);
1528        let reopened = open(path);
1529        let result = reopened
1530            .execute_query("SELECT id FROM crash_rows ORDER BY id")
1531            .expect("second recovery");
1532        assert_eq!(result.result.records.len(), 2);
1533        assert_eq!(result.result.records[0].get("id"), Some(&Value::Integer(1)));
1534        assert_eq!(result.result.records[1].get("id"), Some(&Value::Integer(3)));
1535    }
1536
1537    #[test]
1538    fn xid_resume_skips_known_base_payloads_but_rejects_an_unproven_root() {
1539        let directory = tempfile::tempdir().expect("resume fixture");
1540        let options = RedDBOptions::persistent(directory.path().join("resume.rdb"))
1541            .with_memory_budget(64 * 1024 * 1024)
1542            .with_storage_profile(
1543                crate::storage::profile::StorageDeployPreset::PrimaryReplicaDev.selection(),
1544            )
1545            .expect("profile");
1546        let runtime = crate::storage::RedDB::with_disk_residency_for_qualification(|| {
1547            RedDBRuntime::with_options(options)
1548        })
1549        .expect("runtime");
1550        runtime
1551            .execute_query("CREATE TABLE resume_rows (id INTEGER)")
1552            .expect("table");
1553        runtime
1554            .execute_query("INSERT INTO resume_rows (id) VALUES (1)")
1555            .expect("row");
1556        runtime.flush().expect("publish complete XID summary");
1557        let store = runtime.db().store();
1558        assert!(store.startup_xid_high_water_mark().is_some());
1559        let root = store
1560            .collection_root_page("resume_rows")
1561            .expect("published root");
1562        let manager = store.get_collection("resume_rows").expect("manager");
1563        for (candidate, proven) in [(root, true), (root + 1, false)] {
1564            manager.install_backing(
1565                Arc::new(Unreadable),
1566                candidate,
1567                store.format_version(),
1568                4096,
1569                1,
1570            );
1571            let mut overlay = crate::storage::UnifiedEntity::table_row(
1572                crate::storage::EntityId::new(999),
1573                "resume_rows",
1574                999,
1575                vec![Value::Integer(2)],
1576            );
1577            overlay.xmin = 500_000;
1578            overlay.xmax = 600_000;
1579            manager.insert(overlay).expect("resident WAL overlay");
1580            let result = runtime.rehydrate_snapshot_xid_floor();
1581            assert_eq!(result.is_ok(), proven, "root={candidate}: {result:?}");
1582            if proven {
1583                assert!(runtime.snapshot_manager().peek_next_xid() > 600_000);
1584            }
1585        }
1586    }
1587}