Skip to main content

reddb_server/runtime/
impl_lifecycle.rs

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