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