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