Skip to main content

reddb_server/storage/unified/devx/reddb/
impl_registry.rs

1use super::*;
2
3impl RedDB {
4    pub(crate) fn write_column_block_page(
5        &self,
6        bytes: &[u8],
7    ) -> Result<crate::storage::engine::PageLocation, Box<dyn std::error::Error>> {
8        use crate::storage::engine::PageType;
9
10        let store = self.store();
11        let Some(pager) = store.pager() else {
12            return Ok(crate::storage::engine::PageLocation::new(
13                0,
14                0,
15                bytes.len() as u32,
16            ));
17        };
18        let content_size = crate::storage::engine::page::CONTENT_SIZE;
19        let page_count = bytes.len().max(1).div_ceil(content_size);
20        let mut first_page_id = None;
21        for page_index in 0..page_count {
22            let mut page = pager.allocate_page(PageType::ColumnBlock)?;
23            let page_id = page.page_id();
24            if let Some(first) = first_page_id {
25                let expected = first + page_index as u32;
26                if page_id != expected {
27                    return Err(format!(
28                        "column block page allocation was not contiguous: got {page_id}, expected {expected}"
29                    )
30                    .into());
31                }
32            } else {
33                first_page_id = Some(page_id);
34            }
35            let start = page_index * content_size;
36            let end = (start + content_size).min(bytes.len());
37            if start < end {
38                page.content_mut()[..end - start].copy_from_slice(&bytes[start..end]);
39            }
40            pager.write_page_encrypted(page_id, page)?;
41        }
42        Ok(crate::storage::engine::PageLocation::new(
43            first_page_id.expect("page_count is at least one"),
44            0,
45            bytes.len() as u32,
46        ))
47    }
48
49    pub(crate) fn read_column_block_page(
50        &self,
51        loc: crate::storage::engine::PageLocation,
52    ) -> Result<Option<Vec<u8>>, Box<dyn std::error::Error>> {
53        let store = self.store();
54        let Some(pager) = store.pager() else {
55            return Ok(None);
56        };
57        let content_size = crate::storage::engine::page::CONTENT_SIZE;
58        let mut remaining = loc.length as usize;
59        let mut page_id = loc.page_id;
60        let mut offset = loc.offset as usize;
61        let mut out = Vec::with_capacity(remaining);
62        while remaining > 0 {
63            let page = pager.read_page_decrypted(page_id)?;
64            if page.page_type()? != crate::storage::engine::PageType::ColumnBlock {
65                return Err(format!("page {page_id} is not a ColumnBlock page").into());
66            }
67            if offset > content_size {
68                return Err(format!(
69                    "column block page location offset out of bounds: {offset} > {content_size}"
70                )
71                .into());
72            }
73            let available = content_size - offset;
74            let take = remaining.min(available);
75            out.extend_from_slice(&page.content()[offset..offset + take]);
76            remaining -= take;
77            page_id = page_id.saturating_add(1);
78            offset = 0;
79        }
80        Ok(Some(out))
81    }
82
83    pub fn tree_definitions(&self) -> Vec<crate::physical::PhysicalTreeDefinition> {
84        self.physical_metadata()
85            .map(|metadata| metadata.tree_definitions)
86            .unwrap_or_default()
87    }
88
89    pub fn tree_definition(
90        &self,
91        collection: &str,
92        name: &str,
93    ) -> Option<crate::physical::PhysicalTreeDefinition> {
94        self.tree_definitions()
95            .into_iter()
96            .find(|definition| definition.collection == collection && definition.name == name)
97    }
98
99    pub fn save_tree_definition(
100        &self,
101        definition: crate::physical::PhysicalTreeDefinition,
102    ) -> Result<crate::physical::PhysicalTreeDefinition, Box<dyn std::error::Error>> {
103        self.update_physical_metadata(|metadata| {
104            if let Some(existing) = metadata.tree_definitions.iter_mut().find(|existing| {
105                existing.collection == definition.collection && existing.name == definition.name
106            }) {
107                *existing = definition.clone();
108            } else {
109                metadata.tree_definitions.push(definition.clone());
110            }
111            metadata.tree_definitions.sort_by(|left, right| {
112                left.collection
113                    .cmp(&right.collection)
114                    .then_with(|| left.name.cmp(&right.name))
115            });
116            definition.clone()
117        })
118    }
119
120    pub fn remove_tree_definition(
121        &self,
122        collection: &str,
123        name: &str,
124    ) -> Result<Option<crate::physical::PhysicalTreeDefinition>, Box<dyn std::error::Error>> {
125        self.update_physical_metadata(|metadata| {
126            metadata
127                .tree_definitions
128                .iter()
129                .position(|definition| {
130                    definition.collection == collection && definition.name == name
131                })
132                .map(|index| metadata.tree_definitions.remove(index))
133        })
134    }
135
136    pub fn collection_default_ttl_ms(&self, collection: &str) -> Option<u64> {
137        self.collection_ttl_defaults_ms
138            .read()
139            .ok()
140            .and_then(|defaults| defaults.get(collection).copied())
141    }
142
143    pub fn set_collection_default_ttl_ms(&self, collection: impl Into<String>, ttl_ms: u64) {
144        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
145            defaults.insert(collection.into(), ttl_ms);
146        }
147    }
148
149    pub fn clear_collection_default_ttl_ms(&self, collection: &str) {
150        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
151            defaults.remove(collection);
152        }
153    }
154
155    pub fn collection_contracts(&self) -> Vec<crate::physical::CollectionContract> {
156        self.contract_cache_map()
157            .values()
158            .map(|arc| (**arc).clone())
159            .collect()
160    }
161
162    pub fn collection_contract(
163        &self,
164        collection: &str,
165    ) -> Option<crate::physical::CollectionContract> {
166        self.contract_cache_map()
167            .get(collection)
168            .map(|arc| (**arc).clone())
169    }
170
171    /// Arc-bumping variant — callers that only need read access skip
172    /// the per-call full `CollectionContract` clone. Deep clones cost
173    /// ~200-400 ns each (vec of declared columns + string allocs);
174    /// the UPDATE fast path hits this 2-3× per mutation.
175    pub fn collection_contract_arc(
176        &self,
177        collection: &str,
178    ) -> Option<std::sync::Arc<crate::physical::CollectionContract>> {
179        self.contract_cache_map()
180            .get(collection)
181            .map(std::sync::Arc::clone)
182    }
183
184    /// Return (or lazily build) the in-memory contract map.
185    /// Reparses PhysicalMetadataFile JSON only once per invalidation.
186    /// Called 3× per insert (ensure_model, enforce_uniqueness, normalize_fields)
187    /// so the cache is load-bearing for insert throughput.
188    fn contract_cache_map(
189        &self,
190    ) -> std::sync::Arc<
191        std::collections::HashMap<String, std::sync::Arc<crate::physical::CollectionContract>>,
192    > {
193        self.collection_contract_cache.get_or_load(|| {
194            self.physical_metadata()
195                .map(|metadata| metadata.collection_contracts)
196                .unwrap_or_default()
197        })
198    }
199
200    pub(crate) fn invalidate_collection_contract_cache(&self) {
201        self.collection_contract_cache.invalidate();
202    }
203
204    /// Single-file artifact only: mirror the current contract set into the
205    /// store's auxiliary-metadata blob so it rides the binary dump. Without
206    /// this the contracts live only in the in-memory cache and a collection's
207    /// declared model (e.g. `kv`) is lost on reopen — recovery would re-infer
208    /// it from the stored entities and a KV collection would come back as a
209    /// table. No-op for other profiles, which persist contracts via the
210    /// metadata sidecar.
211    pub(crate) fn sync_single_file_contract_blob(&self) -> Result<(), Box<dyn std::error::Error>> {
212        let contracts = self.collection_contracts();
213        let bytes = crate::physical::serialize_collection_contracts(&contracts);
214        self.store().persist_aux_metadata(bytes)?;
215        Ok(())
216    }
217
218    /// Seed the in-memory contract cache from the store's auxiliary-metadata
219    /// blob (single-file artifact). Called on open so a collection's declared
220    /// model survives a restart. Does nothing when the blob is absent (older
221    /// V9 dumps) or empty.
222    pub(crate) fn seed_contract_cache_from_store_aux(&self) -> std::io::Result<()> {
223        let bytes = self.store().aux_metadata();
224        if bytes.is_empty() {
225            return Ok(());
226        }
227        let contracts = crate::physical::deserialize_collection_contracts(&bytes)?;
228        let map: std::collections::HashMap<_, _> = contracts
229            .into_iter()
230            .map(|contract| (contract.name.clone(), std::sync::Arc::new(contract)))
231            .collect();
232        // Restore the per-collection state derived from contracts (context
233        // index enablement + default TTLs) so the full collection definition —
234        // not just the declared model — survives a restart.
235        let store = self.store();
236        let index = store.context_index();
237        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
238            for contract in map.values() {
239                index.set_collection_enabled(&contract.name, contract.context_index_enabled);
240                if let Some(ttl_ms) = contract.default_ttl_ms {
241                    defaults.insert(contract.name.clone(), ttl_ms);
242                }
243            }
244        }
245        self.collection_contract_cache.replace(map);
246        Ok(())
247    }
248
249    fn update_collection_contract_metadata<T, F>(
250        &self,
251        mutator: F,
252    ) -> Result<T, Box<dyn std::error::Error>>
253    where
254        F: FnOnce(&mut PhysicalMetadataFile) -> T,
255    {
256        if !self.paged_mode
257            || self.options.storage_profile.deploy_profile
258                != crate::storage::DeployProfile::Embedded
259            || self.options.storage_profile.packaging
260                != crate::storage::StoragePackaging::SingleFile
261        {
262            return self.update_physical_metadata(mutator);
263        }
264        if self.options.read_only {
265            return Err("physical metadata operations are not allowed in read-only mode".into());
266        }
267        let Some(_) = self.path() else {
268            return Err("database path is not available".into());
269        };
270
271        // Paged contracts live in an internal record protected by the WAL.
272        // Native artifact summaries are not a complete contract representation.
273        // A definition edit must not rebuild every collection's search indexes.
274        // Retain publication serialization and the canonical atomic writer.
275        let _publication = self.store.vault_publication_lock.lock();
276        let mut metadata = self.load_or_bootstrap_physical_metadata(false)?;
277        let result = mutator(&mut metadata);
278        self.persist_physical_metadata_record(&metadata)?;
279        Ok(result)
280    }
281
282    /// Supply missing system contracts during read-only boot without creating
283    /// a metadata sidecar. Runtime schema rehydration consumes this private view.
284    pub(crate) fn cache_read_only_bootstrap_contract(
285        &self,
286        contract: crate::physical::CollectionContract,
287    ) {
288        assert!(self.options.read_only);
289        self.contract_cache_map();
290        self.collection_contract_cache.insert(contract);
291    }
292
293    pub fn save_collection_contract(
294        &self,
295        contract: crate::physical::CollectionContract,
296    ) -> Result<crate::physical::CollectionContract, Box<dyn std::error::Error>> {
297        let required_capabilities =
298            reddb_engine::storage::entity_codec::required_file_capabilities_for_contract(&contract);
299        self.store()
300            .fence_required_capabilities(required_capabilities)?;
301        let _publication = self.store.vault_publication_lock.lock();
302        self.save_collection_contract_locked(contract)
303    }
304
305    pub fn save_generated_descriptions_if_version(
306        &self,
307        collection: &str,
308        expected_version: u32,
309        expected_created_at_unix_ms: u128,
310        description: Option<String>,
311        columns: &std::collections::HashMap<String, String>,
312    ) -> Result<bool, Box<dyn std::error::Error>> {
313        let _publication = self.store.vault_publication_lock.lock();
314        let Some(mut contract) = self.collection_contract(collection) else {
315            return Ok(false);
316        };
317        if contract.version != expected_version
318            || contract.created_at_unix_ms != expected_created_at_unix_ms
319            || self.store.get_collection(collection).is_none()
320        {
321            return Ok(false);
322        }
323        let mut changed = false;
324        if (contract.description.is_none() || contract.description_generated)
325            && description.as_ref().is_some_and(|text| !text.is_empty())
326        {
327            contract.description = description;
328            contract.description_generated = true;
329            changed = true;
330        }
331        for column in &mut contract.declared_columns {
332            if let Some(text) = columns.get(&column.name) {
333                if !text.is_empty()
334                    && (column.description.is_none() || column.description_generated)
335                {
336                    column.description = Some(text.clone());
337                    column.description_generated = true;
338                    changed = true;
339                }
340            }
341        }
342        if changed {
343            contract.version = contract.version.saturating_add(1);
344            contract.updated_at_unix_ms = std::time::SystemTime::now()
345                .duration_since(std::time::UNIX_EPOCH)
346                .unwrap_or_default()
347                .as_millis();
348            self.save_collection_contract_locked(contract)?;
349        }
350        Ok(changed)
351    }
352
353    fn save_collection_contract_locked(
354        &self,
355        contract: crate::physical::CollectionContract,
356    ) -> Result<crate::physical::CollectionContract, Box<dyn std::error::Error>> {
357        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
358            if let Some(ttl_ms) = contract.default_ttl_ms {
359                defaults.insert(contract.name.clone(), ttl_ms);
360            } else {
361                defaults.remove(&contract.name);
362            }
363        }
364
365        self.store()
366            .context_index()
367            .set_collection_enabled(&contract.name, contract.context_index_enabled);
368        if let Some(manager) = self.store().get_collection(&contract.name) {
369            let columns = contract
370                .declared_columns
371                .iter()
372                .map(|column| column.name.clone())
373                .collect();
374            manager.set_column_schema_if_empty(columns);
375        }
376
377        // Existing paged files can be opened with embedded options. Their
378        // checkpoints do not encode the binary dump's auxiliary contract blob.
379        if self.options.storage_profile.deploy_profile == crate::storage::DeployProfile::Embedded
380            && self.options.storage_profile.packaging
381                == crate::storage::StoragePackaging::SingleFile
382            && !self.paged_mode
383        {
384            let mut contracts = self.collection_contracts();
385            contracts.retain(|existing| existing.name != contract.name);
386            contracts.push(contract.clone());
387            let bytes = crate::physical::serialize_collection_contracts(&contracts);
388            self.store.persist_aux_metadata(bytes)?;
389            self.collection_contract_cache.insert(contract.clone());
390            return Ok(contract);
391        }
392
393        self.invalidate_collection_contract_cache();
394
395        let saved = self.update_collection_contract_metadata(|metadata| {
396            if let Some(existing) = metadata
397                .collection_contracts
398                .iter_mut()
399                .find(|existing| existing.name == contract.name)
400            {
401                *existing = contract.clone();
402            } else {
403                metadata.collection_contracts.push(contract.clone());
404            }
405            metadata
406                .collection_contracts
407                .sort_by(|left, right| left.name.cmp(&right.name));
408
409            if let Some(ttl_ms) = contract.default_ttl_ms {
410                metadata
411                    .collection_ttl_defaults_ms
412                    .insert(contract.name.clone(), ttl_ms);
413            } else {
414                metadata.collection_ttl_defaults_ms.remove(&contract.name);
415            }
416
417            contract.clone()
418        })?;
419        self.invalidate_collection_contract_cache();
420        Ok(saved)
421    }
422
423    pub fn remove_collection_contract(
424        &self,
425        collection: &str,
426    ) -> Result<Option<crate::physical::CollectionContract>, Box<dyn std::error::Error>> {
427        if self.options.read_only {
428            return Err("physical metadata operations are not allowed in read-only mode".into());
429        }
430        let _publication = self.store.vault_publication_lock.lock();
431        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
432            defaults.remove(collection);
433        }
434
435        self.store()
436            .context_index()
437            .set_collection_enabled(collection, false);
438
439        if self.options.storage_profile.deploy_profile == crate::storage::DeployProfile::Embedded
440            && self.options.storage_profile.packaging
441                == crate::storage::StoragePackaging::SingleFile
442            && !self.paged_mode
443        {
444            let removed = self.collection_contract_cache.remove(collection);
445            self.sync_single_file_contract_blob()?;
446            return Ok(removed);
447        }
448
449        self.invalidate_collection_contract_cache();
450
451        if self.paged_mode {
452            let Some(_) = self.path() else {
453                return Err("database path is not available".into());
454            };
455            // DROP already published the native collection registry before it
456            // reaches this contract edit.  Rebuild only the small physical
457            // metadata catalogue from its last durable roots, removing the
458            // dropped root and descriptors explicitly.  Calling the generic
459            // metadata updater here used to fingerprint every row in changed
460            // internal collections (notably append-heavy red.config) while
461            // holding the publication lock, turning a tiny DROP after cold
462            // boot into work proportional to the database's history.
463            //
464            // Other collection fingerprints describe their last checkpoint,
465            // just as they do between ordinary DML and the next checkpoint;
466            // the canonical checkpoint path remains responsible for
467            // recomputing changed fingerprints.
468            let previous = self.load_or_bootstrap_physical_metadata(false)?;
469            let mut roots = previous.superblock.collection_roots.clone();
470            roots.remove(collection);
471            let indexes = previous
472                .indexes
473                .iter()
474                .filter(|index| index.collection.as_deref() != Some(collection))
475                .cloned()
476                .collect();
477            let mut metadata = PhysicalMetadataFile::from_state(
478                self.options.clone(),
479                self.catalog_snapshot(),
480                roots,
481                indexes,
482                Some(&previous),
483            );
484            let removed = metadata
485                .collection_contracts
486                .iter()
487                .position(|contract| contract.name == collection)
488                .map(|index| metadata.collection_contracts.remove(index));
489            metadata.collection_ttl_defaults_ms.remove(collection);
490            self.persist_physical_metadata_record(&metadata)?;
491            self.persist_native_physical_header(&metadata)?;
492            self.invalidate_collection_contract_cache();
493            return Ok(removed);
494        }
495
496        let removed = self.update_collection_contract_metadata(|metadata| {
497            let removed = metadata
498                .collection_contracts
499                .iter()
500                .position(|contract| contract.name == collection)
501                .map(|index| metadata.collection_contracts.remove(index));
502            metadata.collection_ttl_defaults_ms.remove(collection);
503            metadata
504                .indexes
505                .retain(|index| index.collection.as_deref() != Some(collection));
506            removed
507        })?;
508        self.invalidate_collection_contract_cache();
509        Ok(removed)
510    }
511
512    pub(crate) fn collection_ttl_defaults_snapshot(&self) -> BTreeMap<String, u64> {
513        self.collection_ttl_defaults_ms
514            .read()
515            .map(|defaults| {
516                defaults
517                    .iter()
518                    .map(|(collection, ttl_ms)| (collection.clone(), *ttl_ms))
519                    .collect()
520            })
521            .unwrap_or_default()
522    }
523
524    pub(super) fn load_collection_ttl_defaults_from_metadata(
525        &self,
526        metadata: Option<&PhysicalMetadataFile>,
527    ) {
528        let defaults = metadata
529            .map(|m| m.collection_ttl_defaults_ms.clone())
530            .unwrap_or_default();
531
532        if let Ok(mut current) = self.collection_ttl_defaults_ms.write() {
533            current.clear();
534            current.extend(defaults);
535        }
536
537        if let Some(metadata) = metadata {
538            let store = self.store();
539            let index = store.context_index();
540            for contract in &metadata.collection_contracts {
541                index.set_collection_enabled(&contract.name, contract.context_index_enabled);
542            }
543        }
544    }
545
546    /// Snapshot the live hypertable registry (specs + every chunk)
547    /// into the sidecar-serialisable form. Called from
548    /// [`persist_metadata`] so the chunk routing spine is durable on
549    /// the same metadata path as collection contracts — issue #866.
550    /// Returns an empty vec (and touches nothing) when no hypertable
551    /// has ever been declared, so non-hypertable databases pay no
552    /// persist cost.
553    pub(crate) fn hypertable_registry_snapshot(&self) -> Vec<crate::physical::PhysicalHypertable> {
554        let registry = self.hypertables();
555        if registry.is_empty() {
556            return Vec::new();
557        }
558        use std::collections::BTreeMap;
559        let mut chunks_by_table: BTreeMap<String, Vec<crate::physical::PhysicalHypertableChunk>> =
560            BTreeMap::new();
561        for chunk in registry.snapshot_chunks() {
562            chunks_by_table
563                .entry(chunk.id.hypertable.clone())
564                .or_default()
565                .push(crate::physical::PhysicalHypertableChunk {
566                    start_ns: chunk.id.start_ns,
567                    end_ns_exclusive: chunk.end_ns_exclusive,
568                    row_count: chunk.row_count,
569                    min_ts_ns: chunk.min_ts_ns,
570                    max_ts_ns: chunk.max_ts_ns,
571                    sealed: chunk.sealed,
572                    ttl_override_ns: chunk.ttl_override_ns,
573                    columnar_page: chunk.columnar_page,
574                    columnar_derived: chunk.columnar_page.is_some(),
575                });
576        }
577        registry
578            .list()
579            .into_iter()
580            .map(|spec| crate::physical::PhysicalHypertable {
581                chunks: chunks_by_table.remove(&spec.name).unwrap_or_default(),
582                name: spec.name,
583                time_column: spec.time_column,
584                chunk_interval_ns: spec.chunk_interval_ns,
585                default_ttl_ns: spec.default_ttl_ns,
586            })
587            .collect()
588    }
589
590    /// Rehydrate the hypertable registry from the physical metadata
591    /// sidecar at boot. Mirror of
592    /// [`load_collection_ttl_defaults_from_metadata`] — specs and
593    /// chunks are restored verbatim so bounds / routing / TTL are
594    /// identical to the pre-restart state (issue #866).
595    pub(super) fn load_hypertables_from_metadata(&self, metadata: &PhysicalMetadataFile) {
596        if metadata.hypertables.is_empty() {
597            return;
598        }
599        let registry = self.hypertables();
600        for hypertable in &metadata.hypertables {
601            let mut spec = crate::storage::timeseries::HypertableSpec::new(
602                hypertable.name.clone(),
603                hypertable.time_column.clone(),
604                hypertable.chunk_interval_ns,
605            );
606            if let Some(ttl) = hypertable.default_ttl_ns {
607                spec = spec.with_ttl_ns(ttl);
608            }
609            registry.register(spec);
610            for chunk in &hypertable.chunks {
611                let meta = crate::storage::timeseries::ChunkMeta {
612                    id: crate::storage::timeseries::ChunkId {
613                        hypertable: hypertable.name.clone(),
614                        start_ns: chunk.start_ns,
615                    },
616                    end_ns_exclusive: chunk.end_ns_exclusive,
617                    row_count: chunk.row_count,
618                    min_ts_ns: chunk.min_ts_ns,
619                    max_ts_ns: chunk.max_ts_ns,
620                    sealed: chunk.sealed,
621                    ttl_override_ns: chunk.ttl_override_ns,
622                    columnar_page: chunk.columnar_page,
623                };
624                let id = meta.id.clone();
625                let columnar_page = meta.columnar_page;
626                registry.restore_chunk(meta);
627                if let Some(loc) = columnar_page {
628                    if let Ok(Some(bytes)) = self.read_column_block_page(loc) {
629                        registry.restore_columnar_block(&id, bytes);
630                    }
631                }
632            }
633        }
634    }
635
636    pub fn run_maintenance(&self) -> Result<(), Box<dyn std::error::Error>> {
637        self.store.run_maintenance()?;
638        self.persist_metadata()?;
639        if self.paged_mode {
640            if let Some(path) = self.path() {
641                self.remove_imported_metadata_sidecars(path)?;
642            }
643        }
644        Ok(())
645    }
646
647    /// Path to the physical metadata sidecar, if persistent.
648    pub fn metadata_path(&self) -> Option<PathBuf> {
649        self.path
650            .as_ref()
651            .map(|path| PhysicalMetadataFile::metadata_path_for(path))
652    }
653
654    /// Inspect the current physical metadata view without publishing repairs.
655    pub fn physical_metadata(&self) -> Option<PhysicalMetadataFile> {
656        self.load_or_bootstrap_physical_metadata(false).ok()
657    }
658
659    /// Physical index registry derived for the current database state.
660    pub fn physical_indexes(&self) -> Vec<PhysicalIndexState> {
661        let indexes = self
662            .physical_metadata()
663            .map(|metadata| metadata.indexes)
664            .unwrap_or_default();
665        self.physical_indexes_from_declarations(indexes)
666    }
667
668    pub(crate) fn physical_indexes_from_declarations(
669        &self,
670        indexes: Vec<PhysicalIndexState>,
671    ) -> Vec<PhysicalIndexState> {
672        let indexes = Some(indexes)
673            .filter(|indexes| !indexes.is_empty())
674            .or_else(|| {
675                self.native_physical_state()
676                    .map(|state| self.physical_index_state_from_native_state(&state, None))
677            })
678            .unwrap_or_else(|| self.physical_index_state());
679        self.reconcile_index_states_with_native_artifacts(indexes)
680    }
681
682    /// List registered named exports from the current physical metadata view.
683    pub fn exports(&self) -> Vec<ExportDescriptor> {
684        self.physical_metadata()
685            .map(|metadata| metadata.exports)
686            .or_else(|| {
687                self.native_physical_state()
688                    .map(|state| self.exports_from_native_state(&state))
689            })
690            .unwrap_or_default()
691    }
692
693    /// List recorded snapshots from the current physical metadata view.
694    pub fn snapshots(&self) -> Vec<crate::physical::SnapshotDescriptor> {
695        if let Some(metadata) = self.physical_metadata() {
696            if !metadata.snapshots.is_empty() {
697                return metadata.snapshots;
698            }
699        }
700        self.native_physical_state()
701            .map(|state| self.snapshots_from_native_state(&state))
702            .unwrap_or_default()
703    }
704
705    /// List persisted named graph projections from the current physical metadata view.
706    pub fn graph_projections(&self) -> Vec<PhysicalGraphProjection> {
707        self.physical_metadata()
708            .map(|metadata| metadata.graph_projections)
709            .or_else(|| {
710                self.native_physical_state()
711                    .map(|state| self.graph_projections_from_native_state(&state))
712            })
713            .unwrap_or_default()
714    }
715
716    /// List graph projections declared in the catalog view.
717    pub fn declared_graph_projections(&self) -> Vec<PhysicalGraphProjection> {
718        self.catalog_model_snapshot().declared_graph_projections
719    }
720
721    /// List graph projections currently observed in the operational view.
722    pub fn operational_graph_projections(&self) -> Vec<PhysicalGraphProjection> {
723        self.graph_projections()
724            .into_iter()
725            .filter(|projection| {
726                projection.last_materialized_sequence.is_some()
727                    || matches!(projection.state.as_str(), "materialized" | "stale")
728            })
729            .collect()
730    }
731
732    /// List persisted analytics job metadata from the current physical metadata view.
733    pub fn analytics_jobs(&self) -> Vec<PhysicalAnalyticsJob> {
734        self.physical_metadata()
735            .map(|metadata| metadata.analytics_jobs)
736            .or_else(|| {
737                self.native_physical_state()
738                    .map(|state| self.analytics_jobs_from_native_state(&state))
739            })
740            .unwrap_or_default()
741    }
742
743    /// List analytics jobs declared in the catalog view.
744    pub fn declared_analytics_jobs(&self) -> Vec<PhysicalAnalyticsJob> {
745        self.catalog_model_snapshot().declared_analytics_jobs
746    }
747
748    /// List analytics jobs currently observed in the operational view.
749    pub fn operational_analytics_jobs(&self) -> Vec<PhysicalAnalyticsJob> {
750        self.analytics_jobs()
751            .into_iter()
752            .filter(|job| {
753                job.last_run_sequence.is_some()
754                    || matches!(
755                        job.state.as_str(),
756                        "running" | "completed" | "failed" | "queued" | "stale"
757                    )
758            })
759            .collect()
760    }
761
762    /// List indexes declared in the catalog view.
763    pub fn declared_indexes(&self) -> Vec<PhysicalIndexState> {
764        self.catalog_model_snapshot().declared_indexes
765    }
766
767    /// List indexes currently observed in the operational view.
768    pub fn operational_indexes(&self) -> Vec<PhysicalIndexState> {
769        self.catalog_model_snapshot().operational_indexes
770    }
771
772    /// List reconciled index status entries from the catalog snapshot.
773    pub fn index_statuses(&self) -> Vec<CatalogIndexStatus> {
774        self.catalog_model_snapshot().index_statuses
775    }
776
777    /// Resolve one index status entry from the catalog snapshot.
778    pub fn index_status(&self, name: &str) -> Option<CatalogIndexStatus> {
779        self.catalog_model_snapshot()
780            .index_statuses
781            .into_iter()
782            .find(|status| status.name == name)
783    }
784
785    /// Upsert a named graph projection in the persisted physical metadata.
786    pub fn save_graph_projection(
787        &self,
788        name: impl Into<String>,
789        node_labels: Vec<String>,
790        node_types: Vec<String>,
791        edge_labels: Vec<String>,
792        source: impl Into<String>,
793    ) -> Result<PhysicalGraphProjection, Box<dyn std::error::Error>> {
794        let name = name.into();
795        let source = source.into();
796        self.update_physical_metadata(|metadata| {
797            let now = SystemTime::now()
798                .duration_since(UNIX_EPOCH)
799                .unwrap_or_default()
800                .as_millis();
801            let projection = if let Some(existing) = metadata
802                .graph_projections
803                .iter_mut()
804                .find(|projection| projection.name == name)
805            {
806                existing.updated_at_unix_ms = now;
807                existing.state = "declared".to_string();
808                existing.source = source.clone();
809                existing.node_labels = node_labels.clone();
810                existing.node_types = node_types.clone();
811                existing.edge_labels = edge_labels.clone();
812                existing.last_materialized_sequence = None;
813                existing.clone()
814            } else {
815                let projection = PhysicalGraphProjection {
816                    name: name.clone(),
817                    created_at_unix_ms: now,
818                    updated_at_unix_ms: now,
819                    state: "declared".to_string(),
820                    source: source.clone(),
821                    node_labels: node_labels.clone(),
822                    node_types: node_types.clone(),
823                    edge_labels: edge_labels.clone(),
824                    last_materialized_sequence: None,
825                };
826                metadata.graph_projections.push(projection.clone());
827                projection
828            };
829
830            Self::mark_projection_dependent_jobs_stale(metadata, &name, now);
831
832            metadata
833                .graph_projections
834                .sort_by(|left, right| left.name.cmp(&right.name));
835            projection
836        })
837    }
838
839    /// Mark a declared graph projection as materialized in the current physical metadata.
840    pub fn materialize_graph_projection(
841        &self,
842        name: &str,
843    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
844        self.update_physical_metadata(|metadata| {
845            let now = SystemTime::now()
846                .duration_since(UNIX_EPOCH)
847                .unwrap_or_default()
848                .as_millis();
849            let idx = metadata
850                .graph_projections
851                .iter()
852                .position(|projection| projection.name == name);
853            if let Some(idx) = idx {
854                metadata.graph_projections[idx].updated_at_unix_ms = now;
855                metadata.graph_projections[idx].state = "materialized".to_string();
856                metadata.graph_projections[idx].last_materialized_sequence =
857                    Some(metadata.superblock.sequence);
858                let result = metadata.graph_projections[idx].clone();
859                Self::rearm_projection_dependent_jobs_declared(metadata, name, now);
860                return Some(result);
861            }
862            None
863        })
864    }
865
866    /// Mark a declared graph projection as materializing.
867    pub fn mark_graph_projection_materializing(
868        &self,
869        name: &str,
870    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
871        self.update_physical_metadata(|metadata| {
872            let now = SystemTime::now()
873                .duration_since(UNIX_EPOCH)
874                .unwrap_or_default()
875                .as_millis();
876            let idx = metadata
877                .graph_projections
878                .iter()
879                .position(|projection| projection.name == name);
880            if let Some(idx) = idx {
881                metadata.graph_projections[idx].updated_at_unix_ms = now;
882                metadata.graph_projections[idx].state = "materializing".to_string();
883                metadata.graph_projections[idx].last_materialized_sequence = None;
884                let result = metadata.graph_projections[idx].clone();
885                Self::mark_projection_dependent_jobs_stale(metadata, name, now);
886                return Some(result);
887            }
888            None
889        })
890    }
891
892    /// Mark a graph projection as failed.
893    pub fn fail_graph_projection(
894        &self,
895        name: &str,
896    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
897        self.update_physical_metadata(|metadata| {
898            let now = SystemTime::now()
899                .duration_since(UNIX_EPOCH)
900                .unwrap_or_default()
901                .as_millis();
902            let idx = metadata
903                .graph_projections
904                .iter()
905                .position(|projection| projection.name == name);
906            if let Some(idx) = idx {
907                metadata.graph_projections[idx].updated_at_unix_ms = now;
908                metadata.graph_projections[idx].state = "failed".to_string();
909                metadata.graph_projections[idx].last_materialized_sequence = None;
910                let result = metadata.graph_projections[idx].clone();
911                Self::mark_projection_dependent_jobs_stale(metadata, name, now);
912                return Some(result);
913            }
914            None
915        })
916    }
917
918    /// Mark a graph projection as stale while preserving any last materialized sequence.
919    pub fn mark_graph_projection_stale(
920        &self,
921        name: &str,
922    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
923        self.update_physical_metadata(|metadata| {
924            let now = SystemTime::now()
925                .duration_since(UNIX_EPOCH)
926                .unwrap_or_default()
927                .as_millis();
928            let idx = metadata
929                .graph_projections
930                .iter()
931                .position(|projection| projection.name == name);
932            if let Some(idx) = idx {
933                metadata.graph_projections[idx].updated_at_unix_ms = now;
934                metadata.graph_projections[idx].state = "stale".to_string();
935                let result = metadata.graph_projections[idx].clone();
936                Self::mark_projection_dependent_jobs_stale(metadata, name, now);
937                return Some(result);
938            }
939            None
940        })
941    }
942
943    fn mark_projection_dependent_jobs_stale(
944        metadata: &mut PhysicalMetadataFile,
945        projection_name: &str,
946        now: u128,
947    ) {
948        for job in metadata.analytics_jobs.iter_mut() {
949            if job.projection.as_deref() == Some(projection_name) && job.state != "declared" {
950                job.state = "stale".to_string();
951                job.updated_at_unix_ms = now;
952            }
953        }
954    }
955
956    fn rearm_projection_dependent_jobs_declared(
957        metadata: &mut PhysicalMetadataFile,
958        projection_name: &str,
959        now: u128,
960    ) {
961        for job in metadata.analytics_jobs.iter_mut() {
962            if job.projection.as_deref() == Some(projection_name) && job.state == "stale" {
963                job.state = "declared".to_string();
964                job.last_run_sequence = None;
965                job.updated_at_unix_ms = now;
966            }
967        }
968    }
969
970    /// Declare or update analytics job metadata without marking it as executed.
971    pub fn save_analytics_job(
972        &self,
973        kind: impl Into<String>,
974        projection: Option<String>,
975        metadata_entries: BTreeMap<String, String>,
976    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
977        let kind = kind.into();
978        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
979        if let Some(projection_name) = projection.as_deref() {
980            if !self.graph_projection_is_declared(projection_name) {
981                return Err(format!(
982                    "graph projection '{projection_name}' is not declared in physical metadata"
983                )
984                .into());
985            }
986        }
987
988        self.update_physical_metadata(|metadata| {
989            let now = SystemTime::now()
990                .duration_since(UNIX_EPOCH)
991                .unwrap_or_default()
992                .as_millis();
993
994            let job = if let Some(existing) = metadata
995                .analytics_jobs
996                .iter_mut()
997                .find(|job| job.id == job_id)
998            {
999                existing.kind = kind.clone();
1000                existing.projection = projection.clone();
1001                existing.updated_at_unix_ms = now;
1002                existing.metadata = metadata_entries.clone();
1003                if existing.last_run_sequence.is_none() {
1004                    existing.state = "declared".to_string();
1005                }
1006                existing.clone()
1007            } else {
1008                let job = PhysicalAnalyticsJob {
1009                    id: job_id.clone(),
1010                    kind: kind.clone(),
1011                    state: "declared".to_string(),
1012                    projection: projection.clone(),
1013                    created_at_unix_ms: now,
1014                    updated_at_unix_ms: now,
1015                    last_run_sequence: None,
1016                    metadata: metadata_entries.clone(),
1017                };
1018                metadata.analytics_jobs.push(job.clone());
1019                job
1020            };
1021
1022            metadata
1023                .analytics_jobs
1024                .sort_by(|left, right| left.id.cmp(&right.id));
1025            job
1026        })
1027    }
1028
1029    /// Record or update analytics job metadata in the persisted physical metadata.
1030    pub fn record_analytics_job(
1031        &self,
1032        kind: impl Into<String>,
1033        projection: Option<String>,
1034        metadata_entries: BTreeMap<String, String>,
1035    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
1036        let kind = kind.into();
1037        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
1038        if let Some(projection_name) = projection.as_deref() {
1039            if !self.graph_projection_is_declared(projection_name) {
1040                return Err(format!(
1041                    "graph projection '{projection_name}' is not declared in physical metadata"
1042                )
1043                .into());
1044            }
1045            if !self.graph_projection_is_operational(projection_name) {
1046                return Err(format!(
1047                    "graph projection '{projection_name}' is declared but not operationally materialized"
1048                )
1049                .into());
1050            }
1051        }
1052
1053        self.update_physical_metadata(|metadata| {
1054            let now = SystemTime::now()
1055                .duration_since(UNIX_EPOCH)
1056                .unwrap_or_default()
1057                .as_millis();
1058
1059            let existing = metadata
1060                .analytics_jobs
1061                .iter_mut()
1062                .find(|job| job.id == job_id)?;
1063            existing.state = "completed".to_string();
1064            existing.kind = kind.clone();
1065            existing.projection = projection.clone();
1066            existing.updated_at_unix_ms = now;
1067            existing.last_run_sequence = Some(metadata.superblock.sequence);
1068            existing.metadata = metadata_entries.clone();
1069            let job = existing.clone();
1070
1071            metadata
1072                .analytics_jobs
1073                .sort_by(|left, right| left.id.cmp(&right.id));
1074            Some(job)
1075        })
1076        .and_then(|job| {
1077            job.ok_or_else(|| {
1078                format!("analytics job '{job_id}' is not declared in physical metadata").into()
1079            })
1080        })
1081    }
1082
1083    /// Mark a declared analytics job as running.
1084    pub fn queue_analytics_job(
1085        &self,
1086        kind: impl Into<String>,
1087        projection: Option<String>,
1088        metadata_entries: BTreeMap<String, String>,
1089    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
1090        let kind = kind.into();
1091        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
1092        if let Some(projection_name) = projection.as_deref() {
1093            if !self.graph_projection_is_declared(projection_name) {
1094                return Err(format!(
1095                    "graph projection '{projection_name}' is not declared in physical metadata"
1096                )
1097                .into());
1098            }
1099            if !self.graph_projection_is_operational(projection_name) {
1100                return Err(format!(
1101                    "graph projection '{projection_name}' is declared but not operationally materialized"
1102                )
1103                .into());
1104            }
1105        }
1106
1107        self.update_physical_metadata(|metadata| {
1108            let now = SystemTime::now()
1109                .duration_since(UNIX_EPOCH)
1110                .unwrap_or_default()
1111                .as_millis();
1112
1113            let existing = metadata
1114                .analytics_jobs
1115                .iter_mut()
1116                .find(|job| job.id == job_id)?;
1117            existing.state = "queued".to_string();
1118            existing.kind = kind.clone();
1119            existing.projection = projection.clone();
1120            existing.updated_at_unix_ms = now;
1121            existing.metadata = metadata_entries.clone();
1122            let job = existing.clone();
1123
1124            metadata
1125                .analytics_jobs
1126                .sort_by(|left, right| left.id.cmp(&right.id));
1127            Some(job)
1128        })
1129        .and_then(|job| {
1130            job.ok_or_else(|| {
1131                format!("analytics job '{job_id}' is not declared in physical metadata").into()
1132            })
1133        })
1134    }
1135
1136    /// Mark a declared analytics job as running.
1137    pub fn start_analytics_job(
1138        &self,
1139        kind: impl Into<String>,
1140        projection: Option<String>,
1141        metadata_entries: BTreeMap<String, String>,
1142    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
1143        let kind = kind.into();
1144        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
1145        if let Some(projection_name) = projection.as_deref() {
1146            if !self.graph_projection_is_declared(projection_name) {
1147                return Err(format!(
1148                    "graph projection '{projection_name}' is not declared in physical metadata"
1149                )
1150                .into());
1151            }
1152            if !self.graph_projection_is_operational(projection_name) {
1153                return Err(format!(
1154                    "graph projection '{projection_name}' is declared but not operationally materialized"
1155                )
1156                .into());
1157            }
1158        }
1159
1160        self.update_physical_metadata(|metadata| {
1161            let now = SystemTime::now()
1162                .duration_since(UNIX_EPOCH)
1163                .unwrap_or_default()
1164                .as_millis();
1165
1166            let existing = metadata
1167                .analytics_jobs
1168                .iter_mut()
1169                .find(|job| job.id == job_id)?;
1170            existing.state = "running".to_string();
1171            existing.kind = kind.clone();
1172            existing.projection = projection.clone();
1173            existing.updated_at_unix_ms = now;
1174            existing.metadata = metadata_entries.clone();
1175            let job = existing.clone();
1176
1177            metadata
1178                .analytics_jobs
1179                .sort_by(|left, right| left.id.cmp(&right.id));
1180            Some(job)
1181        })
1182        .and_then(|job| {
1183            job.ok_or_else(|| {
1184                format!("analytics job '{job_id}' is not declared in physical metadata").into()
1185            })
1186        })
1187    }
1188
1189    /// Mark a declared analytics job as failed.
1190    pub fn fail_analytics_job(
1191        &self,
1192        kind: impl Into<String>,
1193        projection: Option<String>,
1194        metadata_entries: BTreeMap<String, String>,
1195    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
1196        let kind = kind.into();
1197        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
1198
1199        self.update_physical_metadata(|metadata| {
1200            let now = SystemTime::now()
1201                .duration_since(UNIX_EPOCH)
1202                .unwrap_or_default()
1203                .as_millis();
1204
1205            let existing = metadata
1206                .analytics_jobs
1207                .iter_mut()
1208                .find(|job| job.id == job_id)?;
1209            existing.state = "failed".to_string();
1210            existing.kind = kind.clone();
1211            existing.projection = projection.clone();
1212            existing.updated_at_unix_ms = now;
1213            existing.metadata = metadata_entries.clone();
1214            let job = existing.clone();
1215
1216            metadata
1217                .analytics_jobs
1218                .sort_by(|left, right| left.id.cmp(&right.id));
1219            Some(job)
1220        })
1221        .and_then(|job| {
1222            job.ok_or_else(|| {
1223                format!("analytics job '{job_id}' is not declared in physical metadata").into()
1224            })
1225        })
1226    }
1227
1228    /// Mark a declared analytics job as stale.
1229    pub fn mark_analytics_job_stale(
1230        &self,
1231        kind: impl Into<String>,
1232        projection: Option<String>,
1233        metadata_entries: BTreeMap<String, String>,
1234    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
1235        let kind = kind.into();
1236        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
1237
1238        self.update_physical_metadata(|metadata| {
1239            let now = SystemTime::now()
1240                .duration_since(UNIX_EPOCH)
1241                .unwrap_or_default()
1242                .as_millis();
1243
1244            let existing = metadata
1245                .analytics_jobs
1246                .iter_mut()
1247                .find(|job| job.id == job_id)?;
1248            existing.state = "stale".to_string();
1249            existing.kind = kind.clone();
1250            existing.projection = projection.clone();
1251            existing.updated_at_unix_ms = now;
1252            existing.metadata = metadata_entries.clone();
1253            let job = existing.clone();
1254
1255            metadata
1256                .analytics_jobs
1257                .sort_by(|left, right| left.id.cmp(&right.id));
1258            Some(job)
1259        })
1260        .and_then(|job| {
1261            job.ok_or_else(|| {
1262                format!("analytics job '{job_id}' is not declared in physical metadata").into()
1263            })
1264        })
1265    }
1266
1267    /// Create a named export by copying the current database file, including its internal metadata.
1268    pub fn create_named_export(
1269        &self,
1270        name: impl Into<String>,
1271    ) -> Result<ExportDescriptor, Box<dyn std::error::Error>> {
1272        let name = name.into();
1273        if self.options.mode != StorageMode::Persistent {
1274            return Err("exports require persistent mode".into());
1275        }
1276        let Some(path) = self.path() else {
1277            return Err("database path is not available".into());
1278        };
1279
1280        self.flush()?;
1281
1282        let _publication = self.store.vault_publication_lock.lock();
1283        let mut metadata = match self.load_or_bootstrap_physical_metadata(true) {
1284            Ok(metadata) => metadata,
1285            Err(_)
1286                if self.options.storage_profile.deploy_profile
1287                    == crate::storage::DeployProfile::Embedded
1288                    && self.options.storage_profile.packaging
1289                        == crate::storage::StoragePackaging::SingleFile =>
1290            {
1291                crate::physical::PhysicalMetadataFile::from_state(
1292                    self.options.clone(),
1293                    self.catalog_snapshot(),
1294                    self.physical_collection_roots(),
1295                    self.physical_index_state(),
1296                    None,
1297                )
1298            }
1299            Err(err) => return Err(err),
1300        };
1301        let export_data_path = reddb_file::copy_physical_export_data_file(path, &name)?;
1302
1303        let descriptor = ExportDescriptor {
1304            name: name.clone(),
1305            created_at_unix_ms: SystemTime::now()
1306                .duration_since(UNIX_EPOCH)
1307                .unwrap_or_default()
1308                .as_millis(),
1309            snapshot_id: metadata
1310                .snapshots
1311                .last()
1312                .map(|snapshot| snapshot.snapshot_id),
1313            superblock_sequence: metadata.superblock.sequence,
1314            data_path: export_data_path.display().to_string(),
1315            metadata_path: export_data_path.display().to_string(),
1316            collection_count: metadata.catalog.total_collections,
1317            total_entities: metadata.catalog.total_entities,
1318        };
1319
1320        metadata
1321            .exports
1322            .retain(|export| export.name != descriptor.name);
1323        metadata.exports.push(descriptor.clone());
1324        self.prune_export_registry(&mut metadata.exports);
1325        self.persist_physical_metadata_record(&metadata)?;
1326
1327        Ok(descriptor)
1328    }
1329
1330    /// Enable or disable a physical index entry in the persisted registry.
1331    pub fn set_index_enabled(
1332        &self,
1333        name: &str,
1334        enabled: bool,
1335    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
1336        let Some(status) = self.index_status(name) else {
1337            return Err(format!("index '{name}' is not present in catalog status").into());
1338        };
1339        if !status.declared {
1340            return Err(format!("index '{name}' is not declared in physical metadata").into());
1341        }
1342        self.update_physical_metadata(|metadata| {
1343            let now = SystemTime::now()
1344                .duration_since(UNIX_EPOCH)
1345                .unwrap_or_default()
1346                .as_millis();
1347            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
1348                index.enabled = enabled;
1349                if !enabled {
1350                    index.build_state = "disabled".to_string();
1351                } else if index.build_state == "disabled" {
1352                    index.build_state = if index.artifact_root_page.is_some() {
1353                        "ready".to_string()
1354                    } else {
1355                        "declared-unbuilt".to_string()
1356                    };
1357                }
1358                index.last_refresh_ms = Some(now);
1359                return Some(index.clone());
1360            }
1361            None
1362        })
1363    }
1364
1365    /// Mark a declared physical index as building in the persisted registry.
1366    pub fn mark_index_building(
1367        &self,
1368        name: &str,
1369    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
1370        let Some(status) = self.index_status(name) else {
1371            return Err(format!("index '{name}' is not present in catalog status").into());
1372        };
1373        if !status.declared {
1374            return Err(format!("index '{name}' is not declared in physical metadata").into());
1375        }
1376        if status.lifecycle_state == "disabled" {
1377            return Err(format!("index '{name}' is disabled").into());
1378        }
1379        self.update_physical_metadata(|metadata| {
1380            let now = SystemTime::now()
1381                .duration_since(UNIX_EPOCH)
1382                .unwrap_or_default()
1383                .as_millis();
1384            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
1385                index.build_state = "building".to_string();
1386                index.last_refresh_ms = Some(now);
1387                return Some(index.clone());
1388            }
1389            None
1390        })
1391    }
1392
1393    /// Mark a declared physical index as failed in the persisted registry.
1394    pub fn fail_index(
1395        &self,
1396        name: &str,
1397    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
1398        let Some(status) = self.index_status(name) else {
1399            return Err(format!("index '{name}' is not present in catalog status").into());
1400        };
1401        if !status.declared {
1402            return Err(format!("index '{name}' is not declared in physical metadata").into());
1403        }
1404        self.update_physical_metadata(|metadata| {
1405            let now = SystemTime::now()
1406                .duration_since(UNIX_EPOCH)
1407                .unwrap_or_default()
1408                .as_millis();
1409            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
1410                index.build_state = "failed".to_string();
1411                index.last_refresh_ms = Some(now);
1412                return Some(index.clone());
1413            }
1414            None
1415        })
1416    }
1417
1418    /// Mark a declared physical index as stale in the persisted registry.
1419    pub fn mark_index_stale(
1420        &self,
1421        name: &str,
1422    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
1423        let Some(status) = self.index_status(name) else {
1424            return Err(format!("index '{name}' is not present in catalog status").into());
1425        };
1426        if !status.declared {
1427            return Err(format!("index '{name}' is not declared in physical metadata").into());
1428        }
1429        self.update_physical_metadata(|metadata| {
1430            let now = SystemTime::now()
1431                .duration_since(UNIX_EPOCH)
1432                .unwrap_or_default()
1433                .as_millis();
1434            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
1435                index.build_state = if index.enabled {
1436                    "stale".to_string()
1437                } else {
1438                    "disabled".to_string()
1439                };
1440                index.last_refresh_ms = Some(now);
1441                return Some(index.clone());
1442            }
1443            None
1444        })
1445    }
1446
1447    /// Mark a declared physical index as ready in the persisted registry.
1448    pub fn mark_index_ready(
1449        &self,
1450        name: &str,
1451    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
1452        self.warmup_index(name)
1453    }
1454
1455    /// Mark a physical index as warmed up/refreshed in the persisted registry.
1456    pub fn warmup_index(
1457        &self,
1458        name: &str,
1459    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
1460        let Some(status) = self.index_status(name) else {
1461            return Err(format!("index '{name}' is not present in catalog status").into());
1462        };
1463        if !status.declared {
1464            return Err(format!("index '{name}' is not declared in physical metadata").into());
1465        }
1466        if status.lifecycle_state == "disabled" {
1467            return Err(format!("index '{name}' is disabled").into());
1468        }
1469        if !status.operational {
1470            return Err(
1471                format!("index '{name}' is declared but not operationally materialized").into(),
1472            );
1473        }
1474        let warmed_artifact = self
1475            .physical_indexes()
1476            .into_iter()
1477            .find(|index| index.name == name)
1478            .map(|mut index| {
1479                self.warmup_native_vector_artifact_for_index(&index)?;
1480                self.apply_runtime_native_artifact_to_index_state(&mut index)?;
1481                Ok::<_, String>(index)
1482            })
1483            .transpose()
1484            .map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;
1485
1486        self.update_physical_metadata(|metadata| {
1487            let now = SystemTime::now()
1488                .duration_since(UNIX_EPOCH)
1489                .unwrap_or_default()
1490                .as_millis();
1491            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
1492                if let Some(warmed) = warmed_artifact.as_ref() {
1493                    index.entries = warmed.entries;
1494                    index.estimated_memory_bytes = warmed.estimated_memory_bytes;
1495                    index.backend = warmed.backend.clone();
1496                    index.build_state = "ready".to_string();
1497                }
1498                index.last_refresh_ms = Some(now);
1499                return Some(index.clone());
1500            }
1501            None
1502        })
1503    }
1504
1505    /// Rebuild physical index metadata from the current catalog, optionally restricted to one collection.
1506    pub fn rebuild_index_registry(
1507        &self,
1508        collection: Option<&str>,
1509    ) -> Result<Vec<PhysicalIndexState>, Box<dyn std::error::Error>> {
1510        let fresh = self.reconcile_index_states_with_native_artifacts(self.physical_index_state());
1511        self.update_physical_metadata(|metadata| {
1512            let now = SystemTime::now()
1513                .duration_since(UNIX_EPOCH)
1514                .unwrap_or_default()
1515                .as_millis();
1516
1517            let mut affected = Vec::new();
1518            let declared = metadata.indexes.clone();
1519            for declared_index in declared {
1520                let matches_collection = collection.is_none_or(|collection_name| {
1521                    declared_index.collection.as_deref() == Some(collection_name)
1522                });
1523                if !matches_collection {
1524                    continue;
1525                }
1526
1527                let mut rebuilt = fresh
1528                    .iter()
1529                    .find(|index| index.name == declared_index.name)
1530                    .cloned()
1531                    .unwrap_or_else(|| {
1532                        let mut index = declared_index.clone();
1533                        index.build_state = "declared-unbuilt".to_string();
1534                        index
1535                    });
1536                rebuilt.enabled = declared_index.enabled;
1537                rebuilt.artifact_kind = rebuilt
1538                    .artifact_kind
1539                    .or_else(|| declared_index.artifact_kind.clone());
1540                rebuilt.artifact_root_page = rebuilt
1541                    .artifact_root_page
1542                    .or(declared_index.artifact_root_page);
1543                rebuilt.artifact_checksum = rebuilt
1544                    .artifact_checksum
1545                    .or(declared_index.artifact_checksum);
1546                rebuilt.build_state =
1547                    Self::finalize_rebuilt_index_build_state(&declared_index, &rebuilt);
1548                rebuilt.last_refresh_ms = Some(now);
1549
1550                if let Some(existing) = metadata
1551                    .indexes
1552                    .iter_mut()
1553                    .find(|index| index.name == rebuilt.name)
1554                {
1555                    *existing = rebuilt.clone();
1556                } else {
1557                    metadata.indexes.push(rebuilt.clone());
1558                }
1559
1560                affected.push(rebuilt);
1561            }
1562
1563            affected
1564        })
1565    }
1566
1567    fn finalize_rebuilt_index_build_state(
1568        declared: &PhysicalIndexState,
1569        rebuilt: &PhysicalIndexState,
1570    ) -> String {
1571        if !rebuilt.enabled {
1572            return "disabled".to_string();
1573        }
1574
1575        if declared.build_state == "failed" || rebuilt.build_state == "failed" {
1576            return "failed".to_string();
1577        }
1578
1579        let native_artifact_family = Self::native_artifact_kind_for_index(rebuilt.kind).is_some();
1580        if native_artifact_family {
1581            if rebuilt.artifact_root_page.is_some() && rebuilt.artifact_checksum.is_some() {
1582                return "ready".to_string();
1583            }
1584            if declared.artifact_root_page.is_some()
1585                || declared.artifact_checksum.is_some()
1586                || declared.artifact_kind.is_some()
1587            {
1588                return "stale".to_string();
1589            }
1590            return "declared-unbuilt".to_string();
1591        }
1592
1593        if rebuilt.entries > 0 {
1594            return "ready".to_string();
1595        }
1596
1597        if matches!(
1598            declared.build_state.as_str(),
1599            "stale" | "artifact-published" | "registry-loaded"
1600        ) {
1601            return "stale".to_string();
1602        }
1603
1604        "declared-unbuilt".to_string()
1605    }
1606}