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