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