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