reddb-io-server 1.0.8

RedDB server-side engine: storage, runtime, replication, MCP, AI, and the gRPC/HTTP/RedWire/PG-wire dispatchers. Re-exported by the umbrella `reddb` crate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
use super::*;

impl RedDB {
    pub fn tree_definitions(&self) -> Vec<crate::physical::PhysicalTreeDefinition> {
        self.physical_metadata()
            .map(|metadata| metadata.tree_definitions)
            .unwrap_or_default()
    }

    pub fn tree_definition(
        &self,
        collection: &str,
        name: &str,
    ) -> Option<crate::physical::PhysicalTreeDefinition> {
        self.tree_definitions()
            .into_iter()
            .find(|definition| definition.collection == collection && definition.name == name)
    }

    pub fn save_tree_definition(
        &self,
        definition: crate::physical::PhysicalTreeDefinition,
    ) -> Result<crate::physical::PhysicalTreeDefinition, Box<dyn std::error::Error>> {
        self.update_physical_metadata(|metadata| {
            if let Some(existing) = metadata.tree_definitions.iter_mut().find(|existing| {
                existing.collection == definition.collection && existing.name == definition.name
            }) {
                *existing = definition.clone();
            } else {
                metadata.tree_definitions.push(definition.clone());
            }
            metadata.tree_definitions.sort_by(|left, right| {
                left.collection
                    .cmp(&right.collection)
                    .then_with(|| left.name.cmp(&right.name))
            });
            definition.clone()
        })
    }

    pub fn remove_tree_definition(
        &self,
        collection: &str,
        name: &str,
    ) -> Result<Option<crate::physical::PhysicalTreeDefinition>, Box<dyn std::error::Error>> {
        self.update_physical_metadata(|metadata| {
            metadata
                .tree_definitions
                .iter()
                .position(|definition| {
                    definition.collection == collection && definition.name == name
                })
                .map(|index| metadata.tree_definitions.remove(index))
        })
    }

    pub fn collection_default_ttl_ms(&self, collection: &str) -> Option<u64> {
        self.collection_ttl_defaults_ms
            .read()
            .ok()
            .and_then(|defaults| defaults.get(collection).copied())
    }

    pub fn set_collection_default_ttl_ms(&self, collection: impl Into<String>, ttl_ms: u64) {
        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
            defaults.insert(collection.into(), ttl_ms);
        }
    }

    pub fn clear_collection_default_ttl_ms(&self, collection: &str) {
        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
            defaults.remove(collection);
        }
    }

    pub fn collection_contracts(&self) -> Vec<crate::physical::CollectionContract> {
        self.contract_cache_map()
            .values()
            .map(|arc| (**arc).clone())
            .collect()
    }

    pub fn collection_contract(
        &self,
        collection: &str,
    ) -> Option<crate::physical::CollectionContract> {
        self.contract_cache_map()
            .get(collection)
            .map(|arc| (**arc).clone())
    }

    /// Arc-bumping variant — callers that only need read access skip
    /// the per-call full `CollectionContract` clone. Deep clones cost
    /// ~200-400 ns each (vec of declared columns + string allocs);
    /// the UPDATE fast path hits this 2-3× per mutation.
    pub fn collection_contract_arc(
        &self,
        collection: &str,
    ) -> Option<std::sync::Arc<crate::physical::CollectionContract>> {
        self.contract_cache_map()
            .get(collection)
            .map(std::sync::Arc::clone)
    }

    /// Return (or lazily build) the in-memory contract map.
    /// Reparses PhysicalMetadataFile JSON only once per invalidation.
    /// Called 3× per insert (ensure_model, enforce_uniqueness, normalize_fields)
    /// so the cache is load-bearing for insert throughput.
    fn contract_cache_map(
        &self,
    ) -> std::sync::Arc<
        std::collections::HashMap<String, std::sync::Arc<crate::physical::CollectionContract>>,
    > {
        if let Ok(guard) = self.collection_contract_cache.read() {
            if let Some(map) = guard.as_ref() {
                return std::sync::Arc::clone(map);
            }
        }
        let contracts: Vec<crate::physical::CollectionContract> = self
            .physical_metadata()
            .map(|metadata| metadata.collection_contracts)
            .unwrap_or_default();
        let map: std::collections::HashMap<_, _> = contracts
            .into_iter()
            .map(|contract| (contract.name.clone(), std::sync::Arc::new(contract)))
            .collect();
        let arc = std::sync::Arc::new(map);
        if let Ok(mut guard) = self.collection_contract_cache.write() {
            *guard = Some(std::sync::Arc::clone(&arc));
        }
        arc
    }

    pub(crate) fn invalidate_collection_contract_cache(&self) {
        if let Ok(mut guard) = self.collection_contract_cache.write() {
            *guard = None;
        }
    }

    pub fn save_collection_contract(
        &self,
        contract: crate::physical::CollectionContract,
    ) -> Result<crate::physical::CollectionContract, Box<dyn std::error::Error>> {
        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
            if let Some(ttl_ms) = contract.default_ttl_ms {
                defaults.insert(contract.name.clone(), ttl_ms);
            } else {
                defaults.remove(&contract.name);
            }
        }

        self.store()
            .context_index()
            .set_collection_enabled(&contract.name, contract.context_index_enabled);

        self.invalidate_collection_contract_cache();

        self.update_physical_metadata(|metadata| {
            if let Some(existing) = metadata
                .collection_contracts
                .iter_mut()
                .find(|existing| existing.name == contract.name)
            {
                *existing = contract.clone();
            } else {
                metadata.collection_contracts.push(contract.clone());
            }
            metadata
                .collection_contracts
                .sort_by(|left, right| left.name.cmp(&right.name));

            if let Some(ttl_ms) = contract.default_ttl_ms {
                metadata
                    .collection_ttl_defaults_ms
                    .insert(contract.name.clone(), ttl_ms);
            } else {
                metadata.collection_ttl_defaults_ms.remove(&contract.name);
            }

            contract.clone()
        })
    }

    pub fn remove_collection_contract(
        &self,
        collection: &str,
    ) -> Result<Option<crate::physical::CollectionContract>, Box<dyn std::error::Error>> {
        if let Ok(mut defaults) = self.collection_ttl_defaults_ms.write() {
            defaults.remove(collection);
        }

        self.store()
            .context_index()
            .set_collection_enabled(collection, false);

        self.invalidate_collection_contract_cache();

        self.update_physical_metadata(|metadata| {
            let removed = metadata
                .collection_contracts
                .iter()
                .position(|contract| contract.name == collection)
                .map(|index| metadata.collection_contracts.remove(index));
            metadata.collection_ttl_defaults_ms.remove(collection);
            metadata
                .indexes
                .retain(|index| index.collection.as_deref() != Some(collection));
            removed
        })
    }

    pub(crate) fn collection_ttl_defaults_snapshot(&self) -> BTreeMap<String, u64> {
        self.collection_ttl_defaults_ms
            .read()
            .map(|defaults| {
                defaults
                    .iter()
                    .map(|(collection, ttl_ms)| (collection.clone(), *ttl_ms))
                    .collect()
            })
            .unwrap_or_default()
    }

    pub(crate) fn load_collection_ttl_defaults_from_metadata(&self) {
        let metadata = self.physical_metadata();
        let defaults = metadata
            .as_ref()
            .map(|m| m.collection_ttl_defaults_ms.clone())
            .unwrap_or_default();

        if let Ok(mut current) = self.collection_ttl_defaults_ms.write() {
            current.clear();
            current.extend(defaults);
        }

        if let Some(metadata) = metadata {
            let store = self.store();
            let index = store.context_index();
            for contract in &metadata.collection_contracts {
                index.set_collection_enabled(&contract.name, contract.context_index_enabled);
            }
        }
    }

    pub fn run_maintenance(&self) -> Result<(), Box<dyn std::error::Error>> {
        self.store.run_maintenance()?;
        self.persist_metadata()?;
        Ok(())
    }

    /// Path to the physical metadata sidecar, if persistent.
    pub fn metadata_path(&self) -> Option<PathBuf> {
        self.path
            .as_ref()
            .map(|path| PhysicalMetadataFile::metadata_path_for(path))
    }

    /// Load the current physical metadata view, bootstrapping from native state when needed.
    pub fn physical_metadata(&self) -> Option<PhysicalMetadataFile> {
        self.load_or_bootstrap_physical_metadata(!self.options.read_only)
            .ok()
    }

    /// Physical index registry derived for the current database state.
    pub fn physical_indexes(&self) -> Vec<PhysicalIndexState> {
        let indexes = self
            .physical_metadata()
            .map(|metadata| metadata.indexes)
            .filter(|indexes| !indexes.is_empty())
            .or_else(|| {
                self.native_physical_state()
                    .map(|state| self.physical_index_state_from_native_state(&state, None))
            })
            .unwrap_or_else(|| self.physical_index_state());
        self.reconcile_index_states_with_native_artifacts(indexes)
    }

    /// List registered named exports from the current physical metadata view.
    pub fn exports(&self) -> Vec<ExportDescriptor> {
        self.physical_metadata()
            .map(|metadata| metadata.exports)
            .or_else(|| {
                self.native_physical_state()
                    .map(|state| self.exports_from_native_state(&state))
            })
            .unwrap_or_default()
    }

    /// List recorded snapshots from the current physical metadata view.
    pub fn snapshots(&self) -> Vec<crate::physical::SnapshotDescriptor> {
        self.physical_metadata()
            .map(|metadata| metadata.snapshots)
            .or_else(|| {
                self.native_physical_state()
                    .map(|state| self.snapshots_from_native_state(&state))
            })
            .unwrap_or_default()
    }

    /// List persisted named graph projections from the current physical metadata view.
    pub fn graph_projections(&self) -> Vec<PhysicalGraphProjection> {
        self.physical_metadata()
            .map(|metadata| metadata.graph_projections)
            .or_else(|| {
                self.native_physical_state()
                    .map(|state| self.graph_projections_from_native_state(&state))
            })
            .unwrap_or_default()
    }

    /// List graph projections declared in the catalog view.
    pub fn declared_graph_projections(&self) -> Vec<PhysicalGraphProjection> {
        self.catalog_model_snapshot().declared_graph_projections
    }

    /// List graph projections currently observed in the operational view.
    pub fn operational_graph_projections(&self) -> Vec<PhysicalGraphProjection> {
        self.graph_projections()
            .into_iter()
            .filter(|projection| {
                projection.last_materialized_sequence.is_some()
                    || matches!(projection.state.as_str(), "materialized" | "stale")
            })
            .collect()
    }

    /// List persisted analytics job metadata from the current physical metadata view.
    pub fn analytics_jobs(&self) -> Vec<PhysicalAnalyticsJob> {
        self.physical_metadata()
            .map(|metadata| metadata.analytics_jobs)
            .or_else(|| {
                self.native_physical_state()
                    .map(|state| self.analytics_jobs_from_native_state(&state))
            })
            .unwrap_or_default()
    }

    /// List analytics jobs declared in the catalog view.
    pub fn declared_analytics_jobs(&self) -> Vec<PhysicalAnalyticsJob> {
        self.catalog_model_snapshot().declared_analytics_jobs
    }

    /// List analytics jobs currently observed in the operational view.
    pub fn operational_analytics_jobs(&self) -> Vec<PhysicalAnalyticsJob> {
        self.analytics_jobs()
            .into_iter()
            .filter(|job| {
                job.last_run_sequence.is_some()
                    || matches!(
                        job.state.as_str(),
                        "running" | "completed" | "failed" | "queued" | "stale"
                    )
            })
            .collect()
    }

    /// List indexes declared in the catalog view.
    pub fn declared_indexes(&self) -> Vec<PhysicalIndexState> {
        self.catalog_model_snapshot().declared_indexes
    }

    /// List indexes currently observed in the operational view.
    pub fn operational_indexes(&self) -> Vec<PhysicalIndexState> {
        self.catalog_model_snapshot().operational_indexes
    }

    /// List reconciled index status entries from the catalog snapshot.
    pub fn index_statuses(&self) -> Vec<CatalogIndexStatus> {
        self.catalog_model_snapshot().index_statuses
    }

    /// Resolve one index status entry from the catalog snapshot.
    pub fn index_status(&self, name: &str) -> Option<CatalogIndexStatus> {
        self.catalog_model_snapshot()
            .index_statuses
            .into_iter()
            .find(|status| status.name == name)
    }

    /// Upsert a named graph projection in the persisted physical metadata.
    pub fn save_graph_projection(
        &self,
        name: impl Into<String>,
        node_labels: Vec<String>,
        node_types: Vec<String>,
        edge_labels: Vec<String>,
        source: impl Into<String>,
    ) -> Result<PhysicalGraphProjection, Box<dyn std::error::Error>> {
        let name = name.into();
        let source = source.into();
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            let projection = if let Some(existing) = metadata
                .graph_projections
                .iter_mut()
                .find(|projection| projection.name == name)
            {
                existing.updated_at_unix_ms = now;
                existing.state = "declared".to_string();
                existing.source = source.clone();
                existing.node_labels = node_labels.clone();
                existing.node_types = node_types.clone();
                existing.edge_labels = edge_labels.clone();
                existing.last_materialized_sequence = None;
                existing.clone()
            } else {
                let projection = PhysicalGraphProjection {
                    name: name.clone(),
                    created_at_unix_ms: now,
                    updated_at_unix_ms: now,
                    state: "declared".to_string(),
                    source: source.clone(),
                    node_labels: node_labels.clone(),
                    node_types: node_types.clone(),
                    edge_labels: edge_labels.clone(),
                    last_materialized_sequence: None,
                };
                metadata.graph_projections.push(projection.clone());
                projection
            };

            Self::mark_projection_dependent_jobs_stale(metadata, &name, now);

            metadata
                .graph_projections
                .sort_by(|left, right| left.name.cmp(&right.name));
            projection
        })
    }

    /// Mark a declared graph projection as materialized in the current physical metadata.
    pub fn materialize_graph_projection(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            let idx = metadata
                .graph_projections
                .iter()
                .position(|projection| projection.name == name);
            if let Some(idx) = idx {
                metadata.graph_projections[idx].updated_at_unix_ms = now;
                metadata.graph_projections[idx].state = "materialized".to_string();
                metadata.graph_projections[idx].last_materialized_sequence =
                    Some(metadata.superblock.sequence);
                let result = metadata.graph_projections[idx].clone();
                Self::rearm_projection_dependent_jobs_declared(metadata, name, now);
                return Some(result);
            }
            None
        })
    }

    /// Mark a declared graph projection as materializing.
    pub fn mark_graph_projection_materializing(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            let idx = metadata
                .graph_projections
                .iter()
                .position(|projection| projection.name == name);
            if let Some(idx) = idx {
                metadata.graph_projections[idx].updated_at_unix_ms = now;
                metadata.graph_projections[idx].state = "materializing".to_string();
                metadata.graph_projections[idx].last_materialized_sequence = None;
                let result = metadata.graph_projections[idx].clone();
                Self::mark_projection_dependent_jobs_stale(metadata, name, now);
                return Some(result);
            }
            None
        })
    }

    /// Mark a graph projection as failed.
    pub fn fail_graph_projection(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            let idx = metadata
                .graph_projections
                .iter()
                .position(|projection| projection.name == name);
            if let Some(idx) = idx {
                metadata.graph_projections[idx].updated_at_unix_ms = now;
                metadata.graph_projections[idx].state = "failed".to_string();
                metadata.graph_projections[idx].last_materialized_sequence = None;
                let result = metadata.graph_projections[idx].clone();
                Self::mark_projection_dependent_jobs_stale(metadata, name, now);
                return Some(result);
            }
            None
        })
    }

    /// Mark a graph projection as stale while preserving any last materialized sequence.
    pub fn mark_graph_projection_stale(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalGraphProjection>, Box<dyn std::error::Error>> {
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            let idx = metadata
                .graph_projections
                .iter()
                .position(|projection| projection.name == name);
            if let Some(idx) = idx {
                metadata.graph_projections[idx].updated_at_unix_ms = now;
                metadata.graph_projections[idx].state = "stale".to_string();
                let result = metadata.graph_projections[idx].clone();
                Self::mark_projection_dependent_jobs_stale(metadata, name, now);
                return Some(result);
            }
            None
        })
    }

    fn mark_projection_dependent_jobs_stale(
        metadata: &mut PhysicalMetadataFile,
        projection_name: &str,
        now: u128,
    ) {
        for job in metadata.analytics_jobs.iter_mut() {
            if job.projection.as_deref() == Some(projection_name) && job.state != "declared" {
                job.state = "stale".to_string();
                job.updated_at_unix_ms = now;
            }
        }
    }

    fn rearm_projection_dependent_jobs_declared(
        metadata: &mut PhysicalMetadataFile,
        projection_name: &str,
        now: u128,
    ) {
        for job in metadata.analytics_jobs.iter_mut() {
            if job.projection.as_deref() == Some(projection_name) && job.state == "stale" {
                job.state = "declared".to_string();
                job.last_run_sequence = None;
                job.updated_at_unix_ms = now;
            }
        }
    }

    /// Declare or update analytics job metadata without marking it as executed.
    pub fn save_analytics_job(
        &self,
        kind: impl Into<String>,
        projection: Option<String>,
        metadata_entries: BTreeMap<String, String>,
    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
        let kind = kind.into();
        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
        if let Some(projection_name) = projection.as_deref() {
            if !self.graph_projection_is_declared(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is not declared in physical metadata"
                )
                .into());
            }
        }

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let job = if let Some(existing) = metadata
                .analytics_jobs
                .iter_mut()
                .find(|job| job.id == job_id)
            {
                existing.kind = kind.clone();
                existing.projection = projection.clone();
                existing.updated_at_unix_ms = now;
                existing.metadata = metadata_entries.clone();
                if existing.last_run_sequence.is_none() {
                    existing.state = "declared".to_string();
                }
                existing.clone()
            } else {
                let job = PhysicalAnalyticsJob {
                    id: job_id.clone(),
                    kind: kind.clone(),
                    state: "declared".to_string(),
                    projection: projection.clone(),
                    created_at_unix_ms: now,
                    updated_at_unix_ms: now,
                    last_run_sequence: None,
                    metadata: metadata_entries.clone(),
                };
                metadata.analytics_jobs.push(job.clone());
                job
            };

            metadata
                .analytics_jobs
                .sort_by(|left, right| left.id.cmp(&right.id));
            job
        })
    }

    /// Record or update analytics job metadata in the persisted physical metadata.
    pub fn record_analytics_job(
        &self,
        kind: impl Into<String>,
        projection: Option<String>,
        metadata_entries: BTreeMap<String, String>,
    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
        let kind = kind.into();
        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
        if let Some(projection_name) = projection.as_deref() {
            if !self.graph_projection_is_declared(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is not declared in physical metadata"
                )
                .into());
            }
            if !self.graph_projection_is_operational(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is declared but not operationally materialized"
                )
                .into());
            }
        }

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let existing = metadata
                .analytics_jobs
                .iter_mut()
                .find(|job| job.id == job_id)?;
            existing.state = "completed".to_string();
            existing.kind = kind.clone();
            existing.projection = projection.clone();
            existing.updated_at_unix_ms = now;
            existing.last_run_sequence = Some(metadata.superblock.sequence);
            existing.metadata = metadata_entries.clone();
            let job = existing.clone();

            metadata
                .analytics_jobs
                .sort_by(|left, right| left.id.cmp(&right.id));
            Some(job)
        })
        .and_then(|job| {
            job.ok_or_else(|| {
                format!("analytics job '{job_id}' is not declared in physical metadata").into()
            })
        })
    }

    /// Mark a declared analytics job as running.
    pub fn queue_analytics_job(
        &self,
        kind: impl Into<String>,
        projection: Option<String>,
        metadata_entries: BTreeMap<String, String>,
    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
        let kind = kind.into();
        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
        if let Some(projection_name) = projection.as_deref() {
            if !self.graph_projection_is_declared(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is not declared in physical metadata"
                )
                .into());
            }
            if !self.graph_projection_is_operational(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is declared but not operationally materialized"
                )
                .into());
            }
        }

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let existing = metadata
                .analytics_jobs
                .iter_mut()
                .find(|job| job.id == job_id)?;
            existing.state = "queued".to_string();
            existing.kind = kind.clone();
            existing.projection = projection.clone();
            existing.updated_at_unix_ms = now;
            existing.metadata = metadata_entries.clone();
            let job = existing.clone();

            metadata
                .analytics_jobs
                .sort_by(|left, right| left.id.cmp(&right.id));
            Some(job)
        })
        .and_then(|job| {
            job.ok_or_else(|| {
                format!("analytics job '{job_id}' is not declared in physical metadata").into()
            })
        })
    }

    /// Mark a declared analytics job as running.
    pub fn start_analytics_job(
        &self,
        kind: impl Into<String>,
        projection: Option<String>,
        metadata_entries: BTreeMap<String, String>,
    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
        let kind = kind.into();
        let job_id = Self::analytics_job_id(&kind, projection.as_deref());
        if let Some(projection_name) = projection.as_deref() {
            if !self.graph_projection_is_declared(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is not declared in physical metadata"
                )
                .into());
            }
            if !self.graph_projection_is_operational(projection_name) {
                return Err(format!(
                    "graph projection '{projection_name}' is declared but not operationally materialized"
                )
                .into());
            }
        }

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let existing = metadata
                .analytics_jobs
                .iter_mut()
                .find(|job| job.id == job_id)?;
            existing.state = "running".to_string();
            existing.kind = kind.clone();
            existing.projection = projection.clone();
            existing.updated_at_unix_ms = now;
            existing.metadata = metadata_entries.clone();
            let job = existing.clone();

            metadata
                .analytics_jobs
                .sort_by(|left, right| left.id.cmp(&right.id));
            Some(job)
        })
        .and_then(|job| {
            job.ok_or_else(|| {
                format!("analytics job '{job_id}' is not declared in physical metadata").into()
            })
        })
    }

    /// Mark a declared analytics job as failed.
    pub fn fail_analytics_job(
        &self,
        kind: impl Into<String>,
        projection: Option<String>,
        metadata_entries: BTreeMap<String, String>,
    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
        let kind = kind.into();
        let job_id = Self::analytics_job_id(&kind, projection.as_deref());

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let existing = metadata
                .analytics_jobs
                .iter_mut()
                .find(|job| job.id == job_id)?;
            existing.state = "failed".to_string();
            existing.kind = kind.clone();
            existing.projection = projection.clone();
            existing.updated_at_unix_ms = now;
            existing.metadata = metadata_entries.clone();
            let job = existing.clone();

            metadata
                .analytics_jobs
                .sort_by(|left, right| left.id.cmp(&right.id));
            Some(job)
        })
        .and_then(|job| {
            job.ok_or_else(|| {
                format!("analytics job '{job_id}' is not declared in physical metadata").into()
            })
        })
    }

    /// Mark a declared analytics job as stale.
    pub fn mark_analytics_job_stale(
        &self,
        kind: impl Into<String>,
        projection: Option<String>,
        metadata_entries: BTreeMap<String, String>,
    ) -> Result<PhysicalAnalyticsJob, Box<dyn std::error::Error>> {
        let kind = kind.into();
        let job_id = Self::analytics_job_id(&kind, projection.as_deref());

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let existing = metadata
                .analytics_jobs
                .iter_mut()
                .find(|job| job.id == job_id)?;
            existing.state = "stale".to_string();
            existing.kind = kind.clone();
            existing.projection = projection.clone();
            existing.updated_at_unix_ms = now;
            existing.metadata = metadata_entries.clone();
            let job = existing.clone();

            metadata
                .analytics_jobs
                .sort_by(|left, right| left.id.cmp(&right.id));
            Some(job)
        })
        .and_then(|job| {
            job.ok_or_else(|| {
                format!("analytics job '{job_id}' is not declared in physical metadata").into()
            })
        })
    }

    /// Create a named export by copying the current database file and metadata sidecar.
    pub fn create_named_export(
        &self,
        name: impl Into<String>,
    ) -> Result<ExportDescriptor, Box<dyn std::error::Error>> {
        let name = name.into();
        if self.options.mode != StorageMode::Persistent {
            return Err("exports require persistent mode".into());
        }
        let Some(path) = self.path() else {
            return Err("database path is not available".into());
        };

        self.flush()?;

        let mut metadata = self.load_or_bootstrap_physical_metadata(true)?;
        let export_data_path = PhysicalMetadataFile::export_data_path_for(path, &name);
        let export_metadata_path = PhysicalMetadataFile::metadata_path_for(&export_data_path);
        let export_metadata_binary_path =
            PhysicalMetadataFile::metadata_binary_path_for(&export_data_path);

        fs::copy(path, &export_data_path)?;

        let descriptor = ExportDescriptor {
            name: name.clone(),
            created_at_unix_ms: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis(),
            snapshot_id: metadata
                .snapshots
                .last()
                .map(|snapshot| snapshot.snapshot_id),
            superblock_sequence: metadata.superblock.sequence,
            data_path: export_data_path.display().to_string(),
            metadata_path: export_metadata_path.display().to_string(),
            collection_count: metadata.catalog.total_collections,
            total_entities: metadata.catalog.total_entities,
        };

        metadata
            .exports
            .retain(|export| export.name != descriptor.name);
        metadata.exports.push(descriptor.clone());
        self.prune_export_registry(&mut metadata.exports);
        metadata.save_for_data_path(path)?;
        metadata.save_to_binary_path(&export_metadata_binary_path)?;
        metadata.save_to_path(&export_metadata_path)?;

        Ok(descriptor)
    }

    /// Enable or disable a physical index entry in the persisted registry.
    pub fn set_index_enabled(
        &self,
        name: &str,
        enabled: bool,
    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
        let Some(status) = self.index_status(name) else {
            return Err(format!("index '{name}' is not present in catalog status").into());
        };
        if !status.declared {
            return Err(format!("index '{name}' is not declared in physical metadata").into());
        }
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
                index.enabled = enabled;
                if !enabled {
                    index.build_state = "disabled".to_string();
                } else if index.build_state == "disabled" {
                    index.build_state = if index.artifact_root_page.is_some() {
                        "ready".to_string()
                    } else {
                        "declared-unbuilt".to_string()
                    };
                }
                index.last_refresh_ms = Some(now);
                return Some(index.clone());
            }
            None
        })
    }

    /// Mark a declared physical index as building in the persisted registry.
    pub fn mark_index_building(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
        let Some(status) = self.index_status(name) else {
            return Err(format!("index '{name}' is not present in catalog status").into());
        };
        if !status.declared {
            return Err(format!("index '{name}' is not declared in physical metadata").into());
        }
        if status.lifecycle_state == "disabled" {
            return Err(format!("index '{name}' is disabled").into());
        }
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
                index.build_state = "building".to_string();
                index.last_refresh_ms = Some(now);
                return Some(index.clone());
            }
            None
        })
    }

    /// Mark a declared physical index as failed in the persisted registry.
    pub fn fail_index(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
        let Some(status) = self.index_status(name) else {
            return Err(format!("index '{name}' is not present in catalog status").into());
        };
        if !status.declared {
            return Err(format!("index '{name}' is not declared in physical metadata").into());
        }
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
                index.build_state = "failed".to_string();
                index.last_refresh_ms = Some(now);
                return Some(index.clone());
            }
            None
        })
    }

    /// Mark a declared physical index as stale in the persisted registry.
    pub fn mark_index_stale(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
        let Some(status) = self.index_status(name) else {
            return Err(format!("index '{name}' is not present in catalog status").into());
        };
        if !status.declared {
            return Err(format!("index '{name}' is not declared in physical metadata").into());
        }
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
                index.build_state = if index.enabled {
                    "stale".to_string()
                } else {
                    "disabled".to_string()
                };
                index.last_refresh_ms = Some(now);
                return Some(index.clone());
            }
            None
        })
    }

    /// Mark a declared physical index as ready in the persisted registry.
    pub fn mark_index_ready(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
        self.warmup_index(name)
    }

    /// Mark a physical index as warmed up/refreshed in the persisted registry.
    pub fn warmup_index(
        &self,
        name: &str,
    ) -> Result<Option<PhysicalIndexState>, Box<dyn std::error::Error>> {
        let Some(status) = self.index_status(name) else {
            return Err(format!("index '{name}' is not present in catalog status").into());
        };
        if !status.declared {
            return Err(format!("index '{name}' is not declared in physical metadata").into());
        }
        if status.lifecycle_state == "disabled" {
            return Err(format!("index '{name}' is disabled").into());
        }
        if !status.operational {
            return Err(
                format!("index '{name}' is declared but not operationally materialized").into(),
            );
        }
        let warmed_artifact = self
            .physical_indexes()
            .into_iter()
            .find(|index| index.name == name)
            .map(|mut index| {
                self.warmup_native_vector_artifact_for_index(&index)?;
                self.apply_runtime_native_artifact_to_index_state(&mut index)?;
                Ok::<_, String>(index)
            })
            .transpose()
            .map_err(|err| -> Box<dyn std::error::Error> { err.into() })?;

        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();
            if let Some(index) = metadata.indexes.iter_mut().find(|index| index.name == name) {
                if let Some(warmed) = warmed_artifact.as_ref() {
                    index.entries = warmed.entries;
                    index.estimated_memory_bytes = warmed.estimated_memory_bytes;
                    index.backend = warmed.backend.clone();
                    index.build_state = "ready".to_string();
                }
                index.last_refresh_ms = Some(now);
                return Some(index.clone());
            }
            None
        })
    }

    /// Rebuild physical index metadata from the current catalog, optionally restricted to one collection.
    pub fn rebuild_index_registry(
        &self,
        collection: Option<&str>,
    ) -> Result<Vec<PhysicalIndexState>, Box<dyn std::error::Error>> {
        let fresh = self.reconcile_index_states_with_native_artifacts(self.physical_index_state());
        self.update_physical_metadata(|metadata| {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis();

            let mut affected = Vec::new();
            let declared = metadata.indexes.clone();
            for declared_index in declared {
                let matches_collection = collection.is_none_or(|collection_name| {
                    declared_index.collection.as_deref() == Some(collection_name)
                });
                if !matches_collection {
                    continue;
                }

                let mut rebuilt = fresh
                    .iter()
                    .find(|index| index.name == declared_index.name)
                    .cloned()
                    .unwrap_or_else(|| {
                        let mut index = declared_index.clone();
                        index.build_state = "declared-unbuilt".to_string();
                        index
                    });
                rebuilt.enabled = declared_index.enabled;
                rebuilt.artifact_kind = rebuilt
                    .artifact_kind
                    .or_else(|| declared_index.artifact_kind.clone());
                rebuilt.artifact_root_page = rebuilt
                    .artifact_root_page
                    .or(declared_index.artifact_root_page);
                rebuilt.artifact_checksum = rebuilt
                    .artifact_checksum
                    .or(declared_index.artifact_checksum);
                rebuilt.build_state =
                    Self::finalize_rebuilt_index_build_state(&declared_index, &rebuilt);
                rebuilt.last_refresh_ms = Some(now);

                if let Some(existing) = metadata
                    .indexes
                    .iter_mut()
                    .find(|index| index.name == rebuilt.name)
                {
                    *existing = rebuilt.clone();
                } else {
                    metadata.indexes.push(rebuilt.clone());
                }

                affected.push(rebuilt);
            }

            affected
        })
    }

    fn finalize_rebuilt_index_build_state(
        declared: &PhysicalIndexState,
        rebuilt: &PhysicalIndexState,
    ) -> String {
        if !rebuilt.enabled {
            return "disabled".to_string();
        }

        if declared.build_state == "failed" || rebuilt.build_state == "failed" {
            return "failed".to_string();
        }

        let native_artifact_family = Self::native_artifact_kind_for_index(rebuilt.kind).is_some();
        if native_artifact_family {
            if rebuilt.artifact_root_page.is_some() && rebuilt.artifact_checksum.is_some() {
                return "ready".to_string();
            }
            if declared.artifact_root_page.is_some()
                || declared.artifact_checksum.is_some()
                || declared.artifact_kind.is_some()
            {
                return "stale".to_string();
            }
            return "declared-unbuilt".to_string();
        }

        if rebuilt.entries > 0 {
            return "ready".to_string();
        }

        if matches!(
            declared.build_state.as_str(),
            "stale" | "artifact-published" | "registry-loaded"
        ) {
            return "stale".to_string();
        }

        "declared-unbuilt".to_string()
    }
}