Skip to main content

hawdb_storage/
config.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub enum DurabilityPolicy {
17    /// Flush complete transaction WAL records to the operating system before
18    /// acknowledging writes, without synchronizing each commit to storage.
19    /// Power loss may discard recent acknowledged transactions. Successful
20    /// checkpoint/seal boundaries synchronize covered writes; branch namespace
21    /// and head publication retain their required durability barriers.
22    /// Starting a new relaxed WAL interval may synchronize recovery metadata.
23    SyncOnCheckpoint,
24    /// Synchronize transaction recovery dependencies before acknowledging a
25    /// commit. Grouped commits wait for their shared durability barrier.
26    #[default]
27    SyncOnEveryWrite,
28}
29
30#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
31pub enum RecoveryMode {
32    Strict,
33    /// Repair physically incomplete tails and fenced unsynchronized suffixes.
34    /// Discarded bytes and an identity-bound audit are durable before truncation.
35    /// Read-only opens must explicitly select Strict.
36    #[default]
37    AutoRepairTornTail,
38    /// Legacy report value; database open rejects this mode.
39    DoctorRepairTornTail,
40}
41
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub enum DurableCompression {
44    #[default]
45    Zstd,
46}
47
48pub const DEFAULT_MAX_WAL_REPLAY_ENTRIES: usize = 1_000_000;
49pub const DEFAULT_MAX_WAL_REPLAY_BYTES: u64 = 1024 * 1024 * 1024;
50pub const DEFAULT_MAX_BRANCH_SEALED_WAL_INTERVALS: usize = 256;
51pub const DEFAULT_MAX_WAL_QUARANTINE_BYTES: u64 = DEFAULT_MAX_WAL_REPLAY_BYTES;
52pub const DEFAULT_MAX_WAL_RECORD_BYTES: usize = 16 * 1024 * 1024;
53pub const DEFAULT_MAX_WAL_BATCH_OPERATIONS: usize = 100_000;
54pub const DEFAULT_MAX_CHECKPOINT_ENCODED_BYTES: u64 = 1024 * 1024 * 1024 * 1024;
55pub const DEFAULT_MAX_CHECKPOINT_DECODED_BYTES: u64 = 4 * 1024 * 1024 * 1024 * 1024;
56pub const DEFAULT_SEGMENT_CACHE_CAPACITY_BYTES: u64 = 256 * 1024 * 1024;
57/// Aggregate encoded graph-manifest bytes admitted during one database open.
58///
59/// Graph payload pages remain demand-paged. This separate bound prevents the
60/// non-evictable descriptor manifests from consuming the storage cache or the
61/// process memory budget before a query is admitted.
62pub const DEFAULT_MAX_GRAPH_MANIFEST_OPEN_BYTES: u64 = 64 * 1024 * 1024;
63pub const DEFAULT_AUTO_MATERIALIZE_CHECKPOINT_BYTES: u64 = 64 * 1024 * 1024;
64pub const DEFAULT_MAX_OUT_OF_CORE_DELTA_BYTES: u64 = 256 * 1024 * 1024;
65
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67pub enum StorageResidencyMode {
68    #[default]
69    Auto,
70    Materialized,
71    OutOfCore,
72}
73
74/// Selects the relational-index implementation used by one database handle.
75///
76/// Persistent index publication and demand-paged reads advance together
77/// through this state machine. Keeping them in one mode prevents callers from
78/// selecting a reader that can never have a published generation.
79#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
80pub enum RelationalIndexMode {
81    /// Keep materialized relational indexes as the only serving path.
82    #[default]
83    Materialized,
84    /// Publish and recover persistent index generations without serving reads.
85    Shadow,
86    /// Publish persistent generations and use them for eligible SQL reads.
87    DemandPaged,
88    /// Require a current persistent view for SQL reads and constraint checks.
89    ///
90    /// This mode is deliberately opt-in. Missing, stale, corrupt, or
91    /// admission-unavailable required indexes fail closed instead of falling
92    /// back to materialized postings.
93    Authoritative,
94}
95
96impl RelationalIndexMode {
97    pub const fn publishes_persistent_indexes(self) -> bool {
98        !matches!(self, Self::Materialized)
99    }
100
101    pub const fn serves_demand_paged_reads(self) -> bool {
102        matches!(self, Self::DemandPaged | Self::Authoritative)
103    }
104
105    pub const fn requires_authoritative_indexes(self) -> bool {
106        matches!(self, Self::Authoritative)
107    }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111pub struct WalReplayConfig {
112    /// Descriptor capacity target for the canonical project. Native Unix
113    /// observes OS capacity and can install a smaller effective target.
114    pub max_open_files: usize,
115    /// Enforce foreground descriptor capacity. Internal I/O is always non-strict.
116    pub strict_capacity_limit: bool,
117    pub recovery_mode: RecoveryMode,
118    pub max_entries: Option<usize>,
119    pub max_bytes: Option<u64>,
120    /// Sealed generations admitted before checkpoint compaction is required.
121    /// This bounds metadata/file-open work independently of replay byte/entry
122    /// limits and applies before branch materialization or WAL replay.
123    pub max_branch_sealed_wal_intervals: usize,
124    /// Maximum aggregate bytes retained under the automatic corrupt-WAL
125    /// quarantine directory. A corrupt WAL larger than this bound remains in
126    /// place and is not copied.
127    pub max_quarantine_bytes: u64,
128    pub max_record_bytes: Option<usize>,
129    pub max_batch_operations: Option<usize>,
130    pub max_checkpoint_encoded_bytes: Option<u64>,
131    pub max_checkpoint_decoded_bytes: Option<u64>,
132    pub segment_cache_capacity_bytes: u64,
133    pub max_graph_manifest_open_bytes: u64,
134    pub residency_mode: StorageResidencyMode,
135    pub auto_materialize_checkpoint_bytes: u64,
136    pub max_out_of_core_delta_bytes: Option<u64>,
137    /// Derived columnar shadow double-write: checkpoints additionally
138    /// publish a column-group catalog under `column-groups/` and recovery
139    /// validates it. Off by default; reads are never served from the shadow.
140    pub graph_columnar_shadow_checkpoint: bool,
141    /// Persistent relational-index publication and read activation mode.
142    pub relational_index_mode: RelationalIndexMode,
143}
144
145impl Default for WalReplayConfig {
146    fn default() -> Self {
147        Self {
148            max_open_files: crate::file_descriptors::DEFAULT_MAX_OPEN_FILES,
149            strict_capacity_limit: false,
150            recovery_mode: RecoveryMode::default(),
151            max_entries: Some(DEFAULT_MAX_WAL_REPLAY_ENTRIES),
152            max_bytes: Some(DEFAULT_MAX_WAL_REPLAY_BYTES),
153            max_branch_sealed_wal_intervals: DEFAULT_MAX_BRANCH_SEALED_WAL_INTERVALS,
154            max_quarantine_bytes: DEFAULT_MAX_WAL_QUARANTINE_BYTES,
155            max_record_bytes: Some(DEFAULT_MAX_WAL_RECORD_BYTES),
156            max_batch_operations: Some(DEFAULT_MAX_WAL_BATCH_OPERATIONS),
157            max_checkpoint_encoded_bytes: Some(DEFAULT_MAX_CHECKPOINT_ENCODED_BYTES),
158            max_checkpoint_decoded_bytes: Some(DEFAULT_MAX_CHECKPOINT_DECODED_BYTES),
159            segment_cache_capacity_bytes: DEFAULT_SEGMENT_CACHE_CAPACITY_BYTES,
160            max_graph_manifest_open_bytes: DEFAULT_MAX_GRAPH_MANIFEST_OPEN_BYTES,
161            residency_mode: StorageResidencyMode::Auto,
162            auto_materialize_checkpoint_bytes: DEFAULT_AUTO_MATERIALIZE_CHECKPOINT_BYTES,
163            max_out_of_core_delta_bytes: Some(DEFAULT_MAX_OUT_OF_CORE_DELTA_BYTES),
164            graph_columnar_shadow_checkpoint: false,
165            relational_index_mode: RelationalIndexMode::default(),
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn defaults_are_bounded_and_recoverable() {
176        assert_eq!(
177            DurabilityPolicy::default(),
178            DurabilityPolicy::SyncOnEveryWrite
179        );
180        assert_eq!(RecoveryMode::default(), RecoveryMode::AutoRepairTornTail);
181        assert_eq!(DurableCompression::default(), DurableCompression::Zstd);
182        assert_eq!(
183            RelationalIndexMode::default(),
184            RelationalIndexMode::Materialized
185        );
186        assert!(!RelationalIndexMode::Materialized.publishes_persistent_indexes());
187        assert!(!RelationalIndexMode::Materialized.serves_demand_paged_reads());
188        assert!(RelationalIndexMode::Shadow.publishes_persistent_indexes());
189        assert!(!RelationalIndexMode::Shadow.serves_demand_paged_reads());
190        assert!(RelationalIndexMode::DemandPaged.publishes_persistent_indexes());
191        assert!(RelationalIndexMode::DemandPaged.serves_demand_paged_reads());
192        assert!(!RelationalIndexMode::DemandPaged.requires_authoritative_indexes());
193        assert!(RelationalIndexMode::Authoritative.publishes_persistent_indexes());
194        assert!(RelationalIndexMode::Authoritative.serves_demand_paged_reads());
195        assert!(RelationalIndexMode::Authoritative.requires_authoritative_indexes());
196        let replay = WalReplayConfig::default();
197        assert_eq!(replay.max_entries, Some(DEFAULT_MAX_WAL_REPLAY_ENTRIES));
198        assert_eq!(replay.max_bytes, Some(DEFAULT_MAX_WAL_REPLAY_BYTES));
199        assert_eq!(
200            replay.max_quarantine_bytes,
201            DEFAULT_MAX_WAL_QUARANTINE_BYTES
202        );
203        assert_eq!(replay.max_record_bytes, Some(DEFAULT_MAX_WAL_RECORD_BYTES));
204        assert_eq!(
205            replay.max_batch_operations,
206            Some(DEFAULT_MAX_WAL_BATCH_OPERATIONS)
207        );
208        assert_eq!(
209            replay.max_out_of_core_delta_bytes,
210            Some(DEFAULT_MAX_OUT_OF_CORE_DELTA_BYTES)
211        );
212        assert_eq!(
213            replay.max_graph_manifest_open_bytes,
214            DEFAULT_MAX_GRAPH_MANIFEST_OPEN_BYTES
215        );
216    }
217}