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_threads: Default::default(),
412                ask_answer_cache_entries: parking_lot::RwLock::new((
413                    HashSet::new(),
414                    std::collections::VecDeque::new(),
415                )),
416                result_cache_hits: std::sync::atomic::AtomicU64::new(0),
417                result_cache_misses: std::sync::atomic::AtomicU64::new(0),
418                result_cache_evictions: std::sync::atomic::AtomicU64::new(0),
419                ask_daily_spend: parking_lot::RwLock::new(HashMap::new()),
420                queue_message_locks: parking_lot::RwLock::new(HashMap::new()),
421                rmw_locks: RmwLockTable::new(),
422                planner_dirty_tables: parking_lot::RwLock::new(HashSet::new()),
423                ec_registry: Arc::new(crate::ec::config::EcRegistry::new()),
424                config_registry: Arc::new(crate::auth::registry::ConfigRegistry::new()),
425                ec_worker: crate::ec::worker::EcWorker::new(),
426                auth_store: parking_lot::RwLock::new(None),
427                oauth_validator: parking_lot::RwLock::new(None),
428                browser_token_authority: parking_lot::RwLock::new(None),
429                views: parking_lot::RwLock::new(HashMap::new()),
430                materialized_views: parking_lot::RwLock::new(
431                    crate::storage::cache::result::MaterializedViewCache::new(),
432                ),
433                retention_sweeper: parking_lot::RwLock::new(
434                    crate::runtime::retention_sweeper::RetentionSweeperState::new(),
435                ),
436                transaction_state: crate::runtime::transaction_state::TransactionState::new(),
437                env_config_overrides,
438                lock_manager: Arc::new({
439                    // Sourced from the matrix: Tier B key
440                    // `concurrency.locking.deadlock_timeout_ms`
441                    // (default 5000). Env var wins at boot so
442                    // operators can tune without touching red.config.
443                    let env = crate::runtime::config_overlay::collect_env_overrides();
444                    let timeout_ms = env
445                        .get("concurrency.locking.deadlock_timeout_ms")
446                        .and_then(|raw| raw.parse::<u64>().ok())
447                        .unwrap_or_else(|| {
448                            match crate::runtime::config_matrix::default_for(
449                                "concurrency.locking.deadlock_timeout_ms",
450                            ) {
451                                Some(crate::serde_json::Value::Number(n)) => n as u64,
452                                _ => 5000,
453                            }
454                        });
455                    let cfg = crate::runtime::lock_manager::LockConfig {
456                        default_timeout: std::time::Duration::from_millis(timeout_ms),
457                        ..Default::default()
458                    };
459                    crate::runtime::lock_manager::LockManager::new(cfg)
460                }),
461                rls_policies: parking_lot::RwLock::new(HashMap::new()),
462                rls_enabled_tables: parking_lot::RwLock::new(HashSet::new()),
463                foreign_tables: Arc::new(crate::storage::fdw::ForeignTableRegistry::with_builtins()),
464                pending_tombstones: parking_lot::RwLock::new(HashMap::new()),
465                pending_versioned_updates: parking_lot::RwLock::new(HashMap::new()),
466                pending_queue_dedup: parking_lot::RwLock::new(HashMap::new()),
467                pending_kv_watch_events: parking_lot::RwLock::new(HashMap::new()),
468                pending_vault_writes: parking_lot::RwLock::new(HashMap::new()),
469                pending_store_wal_actions: parking_lot::RwLock::new(HashMap::new()),
470                pending_logical_records: parking_lot::Mutex::new(HashMap::new()),
471                pending_commit_policies: parking_lot::Mutex::new(HashMap::new()),
472                logical_publication: parking_lot::ReentrantMutex::new(()),
473                logical_allocated_lsn: std::sync::atomic::AtomicU64::new(0),
474                pending_claim_locks: parking_lot::RwLock::new(HashMap::new()),
475                queue_wait_registry: std::sync::Arc::new(
476                    crate::runtime::queue_wait_registry::QueueWaitRegistry::new(),
477                ),
478                pending_queue_wakes: parking_lot::RwLock::new(HashMap::new()),
479                tenant_tables: parking_lot::RwLock::new(HashMap::new()),
480                ddl_epoch: std::sync::atomic::AtomicU64::new(0),
481                write_gate: Arc::new(crate::runtime::write_gate::WriteGate::from_options(
482                    &options,
483                )),
484                lifecycle: crate::runtime::lifecycle::Lifecycle::new(),
485                resource_limits,
486                query_budget_slots: AtomicU64::new(0),
487                audit_log: if !options.mode.is_persistent() {
488                    Arc::new(crate::runtime::audit_log::AuditLogger::stderr())
489                } else {
490                    // Default audit-log path for the temporary case
491                    // sits in the system temp dir; persistent runs
492                    // place it next to the resolved data file.
493                    //
494                    // gh-471 iter 2: route through the resolved
495                    // `LogDestination`. Performance/Max tiers emit a
496                    // file-backed log destination under the file-owned
497                    // support-directory logs tier;
498                    // lower tiers / ephemeral runs report `Stderr`
499                    // and we keep the legacy file-next-to-data sink.
500                    // #1375 — single-file embedded mode keeps the data
501                    // directory to exactly the `.rdb` artifact, so the audit
502                    // log must NOT land as a sibling. Route it to a
503                    // process-unique temp location even when a data path is
504                    // set; only the non-embedded case uses the data dir.
505                    let data_path = if embedded_single_file || options.read_only {
506                        std::env::temp_dir()
507                            .join("reddb-embedded-runtime")
508                            .join(format!("audit-{}", std::process::id()))
509                    } else {
510                        options
511                            .data_path
512                            .clone()
513                            .unwrap_or_else(|| std::env::temp_dir().join("reddb"))
514                    };
515                    let (audit_dest, _) = crate::api::tier_wiring::current_log_destinations();
516                    let audit_dest = if options.read_only {
517                        crate::storage::layout::LogDestination::Stderr
518                    } else {
519                        audit_dest
520                    };
521                    if !matches!(audit_dest, crate::storage::layout::LogDestination::File(_))
522                        && (embedded_single_file
523                            || options.read_only
524                            || options
525                                .metadata
526                                .contains_key(crate::api::EPHEMERAL_RUNTIME_METADATA_KEY))
527                    {
528                        // The Stderr/Syslog lower-tier sink resolves to a
529                        // `for_data_path` sibling that collides across concurrent
530                        // temp-dir runtimes — nextest's process-per-test model
531                        // truncates one shared file, flaking audit assertions.
532                        // Pin a unique sibling for these short-lived ephemeral /
533                        // single-file embedded runtimes. The file-owned support-
534                        // dir tier (`File`) is already per-data unique, so leave
535                        // it to `for_destination` (#1375: the embedded audit then
536                        // still never lands a sibling next to the `.rdb`).
537                        let audit_path = reddb_file::layout::sibling_path(
538                            &data_path,
539                            &reddb_file::layout::sidecar_file_name(&data_path, "audit.log"),
540                        );
541                        Arc::new(crate::runtime::audit_log::AuditLogger::with_path(
542                            audit_path,
543                        ))
544                    } else {
545                        Arc::new(crate::runtime::audit_log::AuditLogger::for_destination(
546                            &audit_dest,
547                            &data_path,
548                        ))
549                    }
550                },
551                control_event_ledger: parking_lot::RwLock::new(Arc::new(
552                    crate::runtime::control_events::RuntimeLedger::new(db.store()),
553                )),
554                control_event_config: options.control_events,
555                query_audit: Arc::new(crate::runtime::query_audit::QueryAuditStream::new(
556                    db.store(),
557                    options.query_audit.clone(),
558                )),
559                lease_lifecycle: std::sync::OnceLock::new(),
560                serverless_wal_archive: std::sync::OnceLock::new(),
561                routing_primary_endpoints: parking_lot::RwLock::new(Default::default()),
562                replica_apply_metrics: std::sync::Arc::new(
563                    crate::replication::logical::ReplicaApplyMetrics::default(),
564                ),
565                replica_link_metrics: std::sync::Arc::new(
566                    crate::replication::reconnect::ReplicaLinkMetrics::default(),
567                ),
568                quota_bucket: crate::runtime::quota_bucket::QuotaBucket::from_env(),
569                schema_vocabulary: parking_lot::RwLock::new(
570                    crate::runtime::schema_vocabulary::SchemaVocabulary::new(),
571                ),
572                description_enrichment: parking_lot::Mutex::new(Default::default()),
573                slow_query_logger: {
574                    // Issue #205 — slow-query sink lives in the same
575                    // directory the audit log uses, so backup/restore
576                    // ships them together. Threshold + sample-pct
577                    // default conservatively (1 s, 100% sampling) so
578                    // emitted lines are rare and complete. Operators
579                    // tune via env / config matrix in a follow-up.
580                    //
581                    // gh-471 iter 2: same routing as the audit log —
582                    // `LogDestination::File(...)` for Performance/Max
583                    // lands under the file-owned support-directory logs tier;
584                    // lower tiers fall back to `red-slow.log` in the
585                    // data directory.
586                    // #1375 — see the audit-log note above: single-file mode
587                    // never writes the slow-query log as a sibling of the
588                    // `.rdb`. Route to a process-unique temp dir when embedded,
589                    // regardless of the data path.
590                    let fallback_dir = if embedded_single_file || options.read_only {
591                        std::env::temp_dir()
592                            .join("reddb-embedded-runtime")
593                            .join(format!("slow-{}", std::process::id()))
594                    } else {
595                        options
596                            .data_path
597                            .as_ref()
598                            .and_then(|p| p.parent().map(std::path::PathBuf::from))
599                            .unwrap_or_else(|| std::env::temp_dir().join("reddb"))
600                    };
601                    let threshold_ms = std::env::var("RED_SLOW_QUERY_THRESHOLD_MS")
602                        .ok()
603                        .and_then(|s| s.parse::<u64>().ok())
604                        .unwrap_or(1000);
605                    let sample_pct = std::env::var("RED_SLOW_QUERY_SAMPLE_PCT")
606                        .ok()
607                        .and_then(|s| s.parse::<u8>().ok())
608                        .unwrap_or(100);
609                    let (_, slow_dest) = crate::api::tier_wiring::current_log_destinations();
610                    let slow_dest = if options.read_only || !options.mode.is_persistent() {
611                        crate::storage::layout::LogDestination::Stderr
612                    } else {
613                        slow_dest
614                    };
615                    crate::telemetry::slow_query_logger::SlowQueryLogger::for_destination(
616                        &slow_dest,
617                        &fallback_dir,
618                        threshold_ms,
619                        sample_pct,
620                    )
621                },
622                slow_query_store: crate::telemetry::slow_query_store::SlowQueryStore::new(
623                    crate::telemetry::slow_query_store::DEFAULT_CAP,
624                ),
625                kv_stats: crate::runtime::KvStatsCounters::default(),
626                metrics_ingest_stats: crate::runtime::MetricsIngestCounters::default(),
627                metrics_tenant_activity_stats:
628                    crate::runtime::MetricsTenantActivityCounters::default(),
629                claim_telemetry: Arc::new(
630                    crate::runtime::claim_telemetry::ClaimTelemetryCounters::default(),
631                ),
632                queue_telemetry: Arc::new(
633                    crate::runtime::queue_telemetry::QueueTelemetryCounters::default(),
634                ),
635                query_latency_telemetry: Arc::new(
636                    crate::runtime::query_latency_telemetry::QueryLatencyTelemetry::default(),
637                ),
638                occupancy_sampler: Arc::new(
639                    crate::runtime::occupancy_sampler::OccupancySampler::new(),
640                ),
641                node_load_telemetry: Arc::new(
642                    crate::runtime::node_load_telemetry::NodeLoadTelemetry::default(),
643                ),
644                queue_presence: Arc::new(
645                    crate::storage::queue::presence::ConsumerPresenceRegistry::new(),
646                ),
647                vector_introspection: Arc::new(
648                    crate::storage::vector::introspection::VectorIntrospectionRegistry::new(),
649                ),
650                kv_tag_index: crate::runtime::KvTagIndex::default(),
651                chain_tip_cache: parking_lot::Mutex::new(HashMap::new()),
652                chain_integrity_broken: parking_lot::Mutex::new(HashMap::new()),
653                integrity_tombstones: parking_lot::Mutex::new(Vec::new()),
654                integrity_tombstones_state: std::sync::atomic::AtomicU8::new(0),
655            }),
656        };
657
658        runtime.install_hash_candidate_admission();
659
660        // Issue #205 — install the process-wide OperatorEvent sink so
661        // emit sites buried in storage / replication / signal handlers
662        // can record without threading an `&AuditLogger` through every
663        // call stack. First registration wins; subsequent in-memory
664        // runtimes (test harnesses) fall through to tracing+eprintln.
665        crate::telemetry::operator_event::install_global_audit_sink(Arc::clone(
666            &runtime.inner.audit_log,
667        ));
668
669        // Issue #1238 — wire the slow-query telemetry substrate (ADR 0060).
670        // The logger dual-writes: file sink (existing) + ring store (new).
671        runtime
672            .inner
673            .slow_query_logger
674            .attach_store(Arc::clone(&runtime.inner.slow_query_store));
675
676        // PLAN.md Phase 9.1 — backfill cold-start phase markers
677        // from the wall-clock captured before storage open. The
678        // entire `RedDB::open_with_options` call covers both
679        // auto-restore (when configured) and WAL replay. We
680        // record both phases against the same boundary today;
681        // a follow-up will split them once the storage layer
682        // surfaces a finer-grained event.
683        runtime
684            .inner
685            .lifecycle
686            .set_restore_started_at_ms(boot_open_start_ms);
687        runtime
688            .inner
689            .lifecycle
690            .set_restore_ready_at_ms(storage_ready_ms);
691        runtime
692            .inner
693            .lifecycle
694            .set_wal_replay_started_at_ms(boot_open_start_ms);
695        runtime
696            .inner
697            .lifecycle
698            .set_wal_replay_ready_at_ms(storage_ready_ms);
699
700        let inherited_replication_lsn = if runtime.inner.db.replication.is_some() {
701            let promotion_lsn = runtime
702                .primary_replica_timeline_history()?
703                .and_then(|history| history.entries.last().map(|entry| entry.fork_lsn))
704                .unwrap_or(0);
705            runtime
706                .config_u64("replication.last_applied_lsn", 0)
707                .max(promotion_lsn)
708        } else {
709            0
710        };
711        let restored_cdc_lsn = runtime
712            .inner
713            .db
714            .replication
715            .as_ref()
716            .map(|repl| {
717                repl.logical_wal_spool
718                    .as_ref()
719                    .map(|spool| spool.current_lsn())
720                    .unwrap_or(0)
721            })
722            .unwrap_or(0)
723            .max(runtime.config_u64("timeline.last_archived_lsn", 0))
724            .max(inherited_replication_lsn);
725        runtime.inner.cdc.set_current_lsn(restored_cdc_lsn);
726        runtime
727            .inner
728            .logical_allocated_lsn
729            .store(restored_cdc_lsn, std::sync::atomic::Ordering::Release);
730        runtime.rehydrate_snapshot_xid_floor()?;
731        runtime.rehydrate_vcs_snapshot_pins()?;
732        assert!(runtime
733            .inner
734            .db
735            .runtime
736            .set(super::WeakRuntime(Arc::downgrade(&runtime.inner)))
737            .is_ok());
738        assert!(
739            runtime
740                .inner
741                .db
742                .store()
743                .snapshot_manager
744                .set(runtime.snapshot_manager())
745                .is_ok(),
746            "a new runtime owns the store transaction outcomes"
747        );
748        runtime
749            .bootstrap_system_keyed_collections()
750            .map_err(|err| RedDBError::Internal(format!("bootstrap system collections: {err}")))?;
751        runtime.rehydrate_declared_column_schemas();
752        // Registry restoration can checkpoint missing required projections.
753        // Register their projectors before that epoch.
754        super::control_event_index::prepare(&runtime)?;
755        super::queue_storage_index::prepare(&runtime)?;
756        runtime.rehydrate_runtime_index_registry()?;
757        if runtime
758            .db()
759            .store()
760            .config()
761            .resident_memory_bytes_max
762            .is_some()
763        {
764            runtime
765                .db()
766                .store()
767                .checkpoint_missing_secondary_indices()?;
768        }
769        runtime.rehydrate_kv_tags()?;
770        runtime
771            .load_probabilistic_state()
772            .map_err(|err| RedDBError::Internal(format!("load probabilistic state: {err}")))?;
773
774        // Phase 2.5.4: replay `tenant_tables.{table}.column` markers so
775        // tables declared via `TENANT BY (col)` survive restart. Each
776        // entry re-registers the auto-policy and flips RLS on again.
777        runtime.rehydrate_tenant_tables();
778        // Issue #593 slice 9a — replay persisted materialized-view
779        // descriptors so `CREATE MATERIALIZED VIEW v AS …` survives a
780        // restart. Runs after the system-keyed collections bootstrap
781        // and before the API opens.
782        runtime.rehydrate_materialized_view_descriptors()?;
783        runtime.recover_store_forks()?;
784        if let Some(repl) = &runtime.inner.db.replication {
785            repl.wal_buffer.set_current_lsn(restored_cdc_lsn);
786            if let Some(spool) = &repl.logical_wal_spool {
787                spool.restore_lsn_floor(restored_cdc_lsn);
788            }
789        }
790        runtime.recover_transactional_replication()?;
791
792        // Save system info to red.config on boot
793        {
794            let sys = SystemInfo::collect();
795            let store = runtime.inner.db.store();
796            store.with_boot_system_info_update(|| {
797                store.set_config_tree(
798                    "system",
799                    &crate::serde_json::json!({
800                        "pid": sys.pid,
801                        "cpu_cores": sys.cpu_cores,
802                        "total_memory_bytes": sys.total_memory_bytes,
803                        "available_memory_bytes": sys.available_memory_bytes,
804                        "os": sys.os,
805                        "arch": sys.arch,
806                        "hostname": sys.hostname,
807                        "started_at": SystemTime::now()
808                            .duration_since(UNIX_EPOCH)
809                            .unwrap_or_default()
810                            .as_millis() as u64
811                    }),
812                )
813            });
814
815            // Seed defaults on first boot (only if red.config is empty or missing defaults)
816            let store = runtime.inner.db.store();
817            if store
818                .get_collection("red.config")
819                .map(|m| m.query_all(|_| true).len())
820                .unwrap_or(0)
821                <= 10
822            {
823                store.set_config_tree("ai", &crate::json!({
824                    "default": crate::json!({
825                        "provider": "openai",
826                        "model": crate::ai::DEFAULT_OPENAI_PROMPT_MODEL
827                    }),
828                    "max_embedding_inputs": 256,
829                    "max_prompt_batch": 256,
830                    "timeout": crate::json!({ "connect_secs": 10, "read_secs": 90, "write_secs": 30 })
831                }));
832                store.set_config_tree(
833                    "server",
834                    &crate::json!({
835                        "max_scan_limit": 1000,
836                        "max_body_size": 1048576,
837                        "read_timeout_ms": 5000,
838                        "write_timeout_ms": 5000
839                    }),
840                );
841                store.set_config_tree(
842                    "storage",
843                    &crate::json!({
844                        "page_size": 4096,
845                        "page_cache_capacity": 100000,
846                        "auto_checkpoint_pages": 1000,
847                        "snapshot_retention": 16,
848                        "verify_checksums": true,
849                        "segment": crate::json!({
850                            "max_entities": 100000,
851                            "max_bytes": 268435456_u64,
852                            "compression_level": 6
853                        }),
854                        "hnsw": crate::json!({ "m": 16, "ef_construction": 100, "ef_search": 50 }),
855                        "ivf": crate::json!({ "n_lists": 100, "n_probes": 10 }),
856                        "bm25": crate::json!({ "k1": 1.2, "b": 0.75 })
857                    }),
858                );
859                store.set_config_tree(
860                    "search",
861                    &crate::json!({
862                        "rag": crate::json!({
863                            "max_chunks_per_source": 10,
864                            "max_total_chunks": 25,
865                            "similarity_threshold": 0.8,
866                            "graph_depth": 2,
867                            "min_relevance": 0.3
868                        }),
869                        "fusion": crate::json!({
870                            "vector_weight": 0.5,
871                            "graph_weight": 0.3,
872                            "table_weight": 0.2,
873                            "dedup_threshold": 0.85
874                        })
875                    }),
876                );
877                store.set_config_tree(
878                    "auth",
879                    &crate::json!({
880                        "enabled": false,
881                        "session_ttl_secs": 3600,
882                        "require_auth": false
883                    }),
884                );
885                store.set_config_tree(
886                    "query",
887                    &crate::json!({
888                        "connection_pool": crate::json!({ "max_connections": 64, "max_idle": 16 }),
889                        "max_recursion_depth": 1000
890                    }),
891                );
892                store.set_config_tree(
893                    "indexes",
894                    &crate::json!({
895                        "auto_select": true,
896                        "bloom_filter": crate::json!({
897                            "enabled": true,
898                            "false_positive_rate": 0.01,
899                            "prune_on_scan": true
900                        }),
901                        "hash": crate::json!({ "enabled": true }),
902                        "bitmap": crate::json!({ "enabled": true, "max_cardinality": 1000 }),
903                        "spatial": crate::json!({ "enabled": true })
904                    }),
905                );
906                store.set_config_tree(
907                    "probabilistic",
908                    &crate::json!({
909                        "hll_registers": 16384,
910                        "sketch_default_width": 1000,
911                        "sketch_default_depth": 5,
912                        "filter_default_capacity": 100000
913                    }),
914                );
915                store.set_config_tree(
916                    "timeseries",
917                    &crate::json!({
918                        "default_chunk_size": 1024,
919                        "compression": crate::json!({
920                            "timestamps": "delta_of_delta",
921                            "values": "gorilla_xor"
922                        }),
923                        "default_retention_days": 0
924                    }),
925                );
926                store.set_config_tree(
927                    "queue",
928                    &crate::json!({
929                        "default_max_size": 0,
930                        "default_max_attempts": 3,
931                        "visibility_timeout_ms": 30000,
932                        "consumer_idle_timeout_ms": 60000
933                    }),
934                );
935                store.set_config_tree(
936                    "backup",
937                    &crate::json!({
938                        "enabled": false,
939                        "interval_secs": 3600,
940                        "retention_count": 24,
941                        "upload": false,
942                        "backend": "local"
943                    }),
944                );
945                store.set_config_tree(
946                    "wal",
947                    &crate::json!({
948                        "archive": crate::json!({
949                            "enabled": false,
950                            "retention_hours": 168,
951                            "prefix": reddb_file::backup_wal_prefix("")
952                        })
953                    }),
954                );
955                store.set_config_tree(
956                    "cdc",
957                    &crate::json!({
958                        "enabled": true,
959                        "buffer_size": 100000
960                    }),
961                );
962                store.set_config_tree(
963                    "secret",
964                    &crate::json!({
965                        "auto_encrypt": true,
966                        "auto_decrypt": true
967                    }),
968                );
969            }
970
971            // Perf-parity config matrix: heal the Tier A (critical)
972            // keys unconditionally on every boot. Idempotent — only
973            // writes the default when the key is missing. Keeps
974            // `SHOW CONFIG` showing every guarantee the operator has
975            // (durability.mode, concurrency.locking.enabled, …) even
976            // on long-running datadirs that predate the matrix.
977            crate::runtime::config_matrix::heal_critical_keys(store.as_ref());
978            seed_storage_deploy_config(store.as_ref(), options.storage_profile);
979
980            // Phase 5 — Lehman-Yao runtime flag. Read the Tier A
981            // `storage.btree.lehman_yao` value from the matrix (env
982            // > file > red.config > default) and publish it to the
983            // storage layer's atomic so the B-tree read / split
984            // paths can branch without re-reading the config on
985            // every hot-path call.
986            let lehman_yao = runtime.config_bool("storage.btree.lehman_yao", true);
987            crate::storage::engine::btree::lehman_yao::set_enabled(lehman_yao);
988            if lehman_yao {
989                tracing::info!(
990                    "storage.btree.lehman_yao=true — lock-free concurrent descent enabled"
991                );
992            }
993
994            // Config file overlay — mounted `/etc/reddb/config.json`
995            // (override path via REDDB_CONFIG_FILE). Writes keys with
996            // write-if-absent semantics so a later user `SET CONFIG`
997            // always wins. Missing file = silent no-op.
998            let overlay_path = crate::runtime::config_overlay::config_file_path();
999            let _ =
1000                crate::runtime::config_overlay::apply_config_file(store.as_ref(), &overlay_path);
1001        }
1002
1003        // Issue #2900 — bound `red.control_events` with the declarative
1004        // retention policy once env / file / red.config are all resolved.
1005        if let Err(err) = runtime.apply_control_events_retention() {
1006            tracing::warn!(
1007                target: "reddb::control_events",
1008                "could not apply control_events.retention: {err}"
1009            );
1010        }
1011
1012        // VCS ("Git for Data") — create the `red_*` metadata
1013        // collections on first boot. Idempotent: `get_or_create_collection`
1014        // is a no-op if the collection already exists.
1015        {
1016            let store = runtime.inner.db.store();
1017            for name in crate::application::vcs_collections::ALL {
1018                let _ = store.get_or_create_collection(*name);
1019            }
1020            // Seed VCS config namespace with sensible defaults on first
1021            // boot, matching the pattern used by ai / storage.
1022            store.set_config_tree(
1023                crate::application::vcs_collections::CONFIG_NAMESPACE,
1024                &crate::json!({
1025                    "default_branch": "main",
1026                    "author": crate::json!({
1027                        "name": "reddb",
1028                        "email": "reddb@localhost"
1029                    }),
1030                    "protected_branches": crate::json!(["main"]),
1031                    "closure": crate::json!({
1032                        "enabled": true,
1033                        "lazy": true
1034                    }),
1035                    "merge": crate::json!({
1036                        "default_strategy": "auto",
1037                        "fast_forward": true
1038                    })
1039                }),
1040            );
1041        }
1042
1043        // Migrations — create the `red.migration.definitions` / `red.migration.dependencies`
1044        // system collections on first boot. Idempotent.
1045        {
1046            let store = runtime.inner.db.store();
1047            for name in crate::application::migration_collections::ALL {
1048                let _ = store.get_or_create_collection(*name);
1049            }
1050        }
1051
1052        // Topology graph (#803) — ensure the built-in `red.topology.cluster`
1053        // graph collection (declared WITH ANALYTICS) and its metadata sidecar
1054        // exist. Idempotent and survives restarts via the WAL-backed contract.
1055        let _ = crate::application::topology_collections::ensure(&runtime);
1056
1057        // Bootstrapping topology can publish a metadata checkpoint. Register
1058        // the optional COUNT projection only after that publication, so old
1059        // data is not backfilled before readiness. Queries scan until the next
1060        // checkpoint publishes the projection.
1061        runtime.prepare_paged_counts()?;
1062
1063        // Anonymous access is the most consequential posture an operator can
1064        // choose. Record it before reserving the user-ID floor so the boot-time
1065        // audit entity remains in the internal range.
1066        if no_auth_boot {
1067            use crate::runtime::control_events::{
1068                ActorRef, ControlEvent, ControlEventCtx, EventKind, Outcome,
1069            };
1070            let ledger = std::sync::Arc::clone(&runtime.inner.control_event_ledger.read());
1071            let ctx = ControlEventCtx {
1072                actor: ActorRef::System("boot"),
1073                scope: None,
1074                request_id: None,
1075                trace_id: None,
1076            };
1077            let event = ControlEvent {
1078                kind: EventKind::AuthDisabled,
1079                outcome: Outcome::Allowed,
1080                action: std::borrow::Cow::Borrowed("auth.disabled"),
1081                resource: Some("server".to_string()),
1082                reason: Some("--no-auth / --dev".to_string()),
1083                matched_policy_id: None,
1084                fields: std::collections::HashMap::new(),
1085            };
1086            if let Err(err) = ledger.emit(&ctx, event) {
1087                tracing::warn!(
1088                    target: "reddb::security",
1089                    error = %err,
1090                    "could not record the auth-disabled boot in the control-event ledger"
1091                );
1092            }
1093        }
1094
1095        // Start background maintenance thread (context index refresh +
1096        // session purge). Held by a WEAK reference to `RuntimeInner`
1097        // to avoid an ownership cycle. The last foreground owner unparks
1098        // and joins the worker before releasing its inner reference, so
1099        // an active weak upgrade cannot retain the pager lock after close.
1100        // The 60-second work cadence is tracked via `last_work`.
1101        //
1102        // The previous version captured `rt = runtime.clone()` by
1103        // strong reference and ran an unterminated `loop`, which held
1104        // Arc<RuntimeInner> forever — reopening a persistent database
1105        // in the same process failed with "Database is locked" because
1106        // the pager could never drop. See the regression test
1107        // `finding_1_select_after_bulk_insert_persistent_reopen`.
1108        {
1109            let weak = Arc::downgrade(&runtime.inner);
1110            runtime
1111                .background_tasks
1112                .as_ref()
1113                .expect("foreground runtime")
1114                .spawn(
1115                    std::thread::Builder::new().name("reddb-maintenance".into()),
1116                    move |stopped| {
1117                        let tick = std::time::Duration::from_millis(200);
1118                        let work_interval = std::time::Duration::from_secs(60);
1119                        let mut last_work = std::time::Instant::now();
1120                        let mut allocator_pressure =
1121                            super::allocator_pressure::AllocatorPressure::default();
1122                        loop {
1123                            std::thread::park_timeout(tick);
1124                            if stopped.load(AtomicOrdering::Acquire) {
1125                                break;
1126                            }
1127                            let Some(inner) = weak.upgrade() else {
1128                                // All strong references dropped — the
1129                                // runtime is gone, exit cleanly.
1130                                break;
1131                            };
1132                            if last_work.elapsed() >= work_interval {
1133                                let _stats = inner.db.store().context_index().stats();
1134                                last_work = std::time::Instant::now();
1135                            }
1136                            let rt = RedDBRuntime {
1137                                background_tasks: None,
1138                                inner,
1139                            };
1140                            rt.try_reclaim_history_tick();
1141                            allocator_pressure.tick();
1142                        }
1143                    },
1144                );
1145        }
1146
1147        // Blob Cache expiration is active maintenance, not a read-path side
1148        // effect. Each pulse scans a rotating bounded slice so expired keys
1149        // release their L1 budget even when they are never accessed again.
1150        // A dedicated low-priority worker keeps this work isolated from query
1151        // execution workers.
1152        {
1153            let weak = Arc::downgrade(&runtime.inner);
1154            runtime
1155                .background_tasks
1156                .as_ref()
1157                .expect("foreground runtime")
1158                .spawn(
1159                    std::thread::Builder::new().name("reddb-cache-sweeper".into()),
1160                    move |stopped| loop {
1161                        std::thread::park_timeout(std::time::Duration::from_millis(250));
1162                        if stopped.load(AtomicOrdering::Acquire) {
1163                            break;
1164                        }
1165                        let Some(inner) = weak.upgrade() else {
1166                            break;
1167                        };
1168                        let _ = crate::storage::cache::sweeper::BlobCacheSweeper::sweep_expired(
1169                            &inner.result_blob_cache,
1170                            crate::storage::cache::sweeper::SweepLimit::Either {
1171                                entries: 512,
1172                                millis: 5,
1173                            },
1174                        );
1175                        let rt = RedDBRuntime {
1176                            background_tasks: None,
1177                            inner,
1178                        };
1179                        rt.promote_volatile_result_cache_entry();
1180                    },
1181                );
1182        }
1183
1184        // Start backup scheduler if enabled via red.config
1185        {
1186            let store = runtime.inner.db.store();
1187            let mut backup_enabled = false;
1188            let mut backup_interval = 3600u64;
1189
1190            if let Some(manager) = store.get_collection("red.config") {
1191                manager.for_each_entity(|entity| {
1192                    if let Some(row) = entity.data.as_row() {
1193                        let key = row.get_field("key").and_then(|v| match v {
1194                            reddb_types::Value::Text(s) => Some(s.as_ref()),
1195                            _ => None,
1196                        });
1197                        let val = row.get_field("value");
1198                        if key == Some("backup.enabled") {
1199                            backup_enabled = match val {
1200                                Some(reddb_types::Value::Boolean(true)) => true,
1201                                Some(reddb_types::Value::Text(s)) => &**s == "true",
1202                                _ => false,
1203                            };
1204                        } else if key == Some("backup.interval_secs") {
1205                            if let Some(reddb_types::Value::Integer(n)) = val {
1206                                backup_interval = *n as u64;
1207                            }
1208                        }
1209                    }
1210                    true
1211                });
1212            }
1213
1214            if backup_enabled {
1215                runtime.inner.backup_scheduler.set_interval(backup_interval);
1216                let rt = runtime.clone();
1217                runtime
1218                    .inner
1219                    .backup_scheduler
1220                    .start(move || rt.trigger_backup().map_err(|e| format!("{}", e)));
1221            }
1222        }
1223
1224        // Load EC registry from red.config and start worker
1225        {
1226            runtime
1227                .inner
1228                .ec_registry
1229                .load_from_config_store(runtime.inner.db.store().as_ref());
1230            if !runtime.inner.db.options().read_only
1231                && !runtime.inner.ec_registry.async_configs().is_empty()
1232            {
1233                runtime.inner.ec_worker.start(
1234                    Arc::clone(&runtime.inner.ec_registry),
1235                    Arc::clone(&runtime.inner.db.store()),
1236                );
1237            }
1238        }
1239
1240        if let (true, crate::replication::ReplicationRole::Replica { primary_addr }) = (
1241            runtime.inner.db.options().replica_loop_enabled
1242                && !runtime.inner.db.options().read_only,
1243            runtime.inner.db.options().replication.role.clone(),
1244        ) {
1245            let rt = runtime.clone();
1246            std::thread::Builder::new()
1247                .name("reddb-replica".into())
1248                .spawn(move || rt.run_replica_loop(primary_addr))
1249                .ok();
1250        }
1251
1252        // PLAN.md Phase 1 — Lifecycle Contract. Mark Ready once every
1253        // boot stage above has completed (WAL replay, restore-from-
1254        // remote, replica-loop spawn). Health probes flip from 503 to
1255        // 200 here; shutdown begins from this state.
1256        runtime.inner.lifecycle.mark_ready();
1257
1258        #[cfg(not(test))]
1259        if runtime
1260            .db()
1261            .store()
1262            .config()
1263            .resident_memory_bytes_max
1264            .is_some()
1265            && !runtime.db().options().read_only
1266        {
1267            runtime.start_count_projection_worker();
1268        }
1269
1270        // Issue #583 slice 10 — ContinuousMaterializedView scheduler.
1271        // Low-priority background ticker that drains the cache's
1272        // `claim_due_at` set every ~50ms. Holds only a Weak<RuntimeInner>
1273        // to avoid an ownership cycle; foreground close unparks and drains
1274        // an active refresh before releasing storage. Materialized views without
1275        // a `REFRESH EVERY` clause stay on the manual-refresh path
1276        // and are skipped by `claim_due_at`, so the loop is a no-op
1277        // when no scheduled views exist.
1278        {
1279            let weak_inner = Arc::downgrade(&runtime.inner);
1280            runtime
1281                .background_tasks
1282                .as_ref()
1283                .expect("foreground runtime")
1284                .spawn(
1285                    std::thread::Builder::new()
1286                        .name("reddb-mv-scheduler".into())
1287                        // Rust's default for spawned threads is 2 MiB, which is too
1288                        // small for the query-execution path that refresh_due_materialized_views
1289                        // runs (StatementExecutionFrame + guards per view). Match the
1290                        // 8 MiB that the OS gives the main thread.
1291                        .stack_size(8 * 1024 * 1024),
1292                    move |stopped| loop {
1293                        std::thread::park_timeout(std::time::Duration::from_millis(50));
1294                        if stopped.load(AtomicOrdering::Acquire) {
1295                            break;
1296                        }
1297                        let Some(inner) = weak_inner.upgrade() else {
1298                            break;
1299                        };
1300                        let rt = RedDBRuntime {
1301                            background_tasks: None,
1302                            inner,
1303                        };
1304                        rt.refresh_due_materialized_views();
1305                    },
1306                );
1307        }
1308
1309        // Issue #584 slice 12 — DeclarativeRetention background sweeper.
1310        // Low-priority ticker that physically reclaims rows whose
1311        // timestamp has fallen beyond the retention window. Holds a
1312        // `Weak<RuntimeInner>`; foreground close drains an active tick
1313        // before releasing storage (shutdown leaves storage consistent
1314        // because each tick goes through the standard DELETE path —
1315        // there is no half-finished mutation state to clean up). The
1316        // tick interval is intentionally longer than the MV scheduler
1317        // (500ms) because retention is order-of-seconds at minimum.
1318        if !runtime.write_gate().is_read_only() {
1319            let weak_inner = Arc::downgrade(&runtime.inner);
1320            runtime
1321                .background_tasks
1322                .as_ref()
1323                .expect("foreground runtime")
1324                .spawn(
1325                    std::thread::Builder::new().name("reddb-retention-sweeper".into()),
1326                    move |stopped| loop {
1327                        std::thread::park_timeout(std::time::Duration::from_millis(500));
1328                        if stopped.load(AtomicOrdering::Acquire) {
1329                            break;
1330                        }
1331                        let Some(inner) = weak_inner.upgrade() else {
1332                            break;
1333                        };
1334                        let rt = RedDBRuntime {
1335                            background_tasks: None,
1336                            inner,
1337                        };
1338                        rt.sweep_retention_tick(
1339                            crate::runtime::retention_sweeper::DEFAULT_SWEEPER_BATCH,
1340                        );
1341                        rt.sweep_individual_ttl_tick(
1342                            crate::runtime::retention_sweeper::DEFAULT_SWEEPER_BATCH,
1343                        );
1344                    },
1345                );
1346        }
1347
1348        // #1369 — reserve the fixed internal-id floor only after every boot
1349        // stage has finished. Some persistent-only startup paths publish
1350        // internal entities, so reserving it earlier lets those paths consume
1351        // the first documented user `rid`. `register_entity_id` only raises
1352        // the allocator, leaving databases already past the floor untouched.
1353        runtime
1354            .inner
1355            .db
1356            .store()
1357            .register_entity_id(crate::storage::EntityId::new(
1358                crate::storage::FIRST_USER_ENTITY_ID - 1,
1359            ));
1360
1361        Ok(runtime)
1362    }
1363
1364    fn rehydrate_snapshot_xid_floor(&self) -> RedDBResult<()> {
1365        let store = self.inner.db.store();
1366        let snapshot_manager = self.inner.transaction_state.snapshot_manager();
1367        let base_high_water_mark = store.startup_xid_high_water_mark();
1368        let mut high_water_mark = base_high_water_mark.unwrap_or(0);
1369        for collection in store.list_collections() {
1370            let Some(manager) = store.get_collection(&collection) else {
1371                continue;
1372            };
1373            let observe = |entity: &crate::storage::UnifiedEntity| {
1374                high_water_mark = high_water_mark.max(entity.xmin).max(entity.xmax);
1375                true
1376            };
1377            if base_high_water_mark.is_some() {
1378                // The catalog covers the exact immutable roots. Committed WAL
1379                // replay remains resident and must still advance the floor.
1380                manager.for_each_entity(observe);
1381            } else {
1382                // Older or unproven generations require complete physical
1383                // validation, one bounded record at a time, before filtering.
1384                manager.try_for_each_entity(usize::MAX, observe)?;
1385            }
1386        }
1387        // At boot only the maximum advances the allocator and retires reserved slots.
1388        snapshot_manager.observe_committed_xid(high_water_mark);
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}