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