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
use crate::error::{DbError, DbResult};
/// Bitcask flush-path I/O strategy. Tunable; in-memory effect only — the
/// on-disk format is identical regardless. Default: `Pwrite`.
///
/// `Uring` requires BOTH the non-default `io-uring` Cargo feature AND Linux; if
/// either is missing it falls back to blocking `pwrite` (logged once at open).
/// io_uring is off by default because its SQPOLL kernel poller busy-polls a CPU
/// per shard — opt in only when benchmarks on your workload justify it. See
/// `docs/research/sqpoll-noise.md`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(
any(feature = "armour", feature = "postcard-codec"),
derive(serde::Deserialize)
)]
pub enum IoBackend {
/// io_uring writer. `sqpoll_idle_ms = Some(ms)` spawns a dedicated SQPOLL
/// kernel poller (`iou-sqp-*`) with that idle timeout in milliseconds;
/// `None` uses io_uring without a poller (each submit makes an
/// `io_uring_enter` syscall — no kernel thread).
Uring { sqpoll_idle_ms: Option<u32> },
/// Blocking `pwrite` via `FileExt::write_all_at` — no io_uring, no poller.
#[default]
Pwrite,
}
/// Database configuration.
///
/// # Immutable vs tunable parameters
///
/// **Immutable** (fixed at creation, changing breaks the database):
/// - `shard_count` — stored in `db.meta`, determines key→shard routing
/// - `shard_prefix_bits` — determines key→shard grouping; changing breaks
/// `atomic` guarantees and dead_bytes tracking across shards
/// - `encryption_key` — presence/absence stored in `db.meta`
///
/// **Tunable** (safe to change between restarts):
/// - `max_file_size`, `compaction_threshold`, `enable_fsync`, `write_buffer_size`
/// - `cache` — in-memory only, no on-disk state
/// - `reversed` — only affects in-memory index ordering
/// - `hints` — controls hint file generation/use during recovery
#[derive(Debug, Clone)]
#[cfg_attr(
any(feature = "armour", feature = "postcard-codec"),
derive(serde::Deserialize)
)]
pub struct Config {
/// Number of shards. **Immutable** — stored in `db.meta`, changing requires
/// recreating the database. Default: `available_parallelism()`.
pub shard_count: usize,
/// Maximum size of a single data file before rotation. Tunable.
/// Default: 256 MB.
pub max_file_size: u64,
/// Ratio of dead_bytes / total_bytes required to trigger compaction. Tunable.
/// Default: 0.3.
pub compaction_threshold: f64,
/// Whether to fsync after writes. **Currently a no-op for the Bitcask write
/// path** — Bitcask never fsyncs per write (`DurabilityInner::sync()` for
/// Bitcask is a no-op). Durability comes from write-buffer flush plus an
/// explicit `flush()`/`close()`, or the optional periodic [`Flusher`].
/// Tunable. Default: false.
pub enable_fsync: bool,
/// Write buffer size per shard in bytes. Tunable. Writes are buffered in
/// memory and flushed to disk when the buffer is full or on explicit
/// flush/close. Default: 1 MB.
pub write_buffer_size: usize,
/// Value cache configuration (for VarTree). Tunable — in-memory only.
#[cfg(feature = "var-collections")]
pub cache: CacheConfig,
/// Number of prefix bits of the key to use for shard routing. **Immutable** —
/// changing breaks `atomic` guarantees (keys regroup across shards) and
/// dead_bytes tracking (old entries attributed to wrong shard).
/// 0 = hash full key (default). Non-zero = hash first N bits for locality.
pub shard_prefix_bits: usize,
/// Reverse key ordering in the index. Tunable — only affects in-memory
/// index ordering. When `true`, forward iteration yields keys in
/// descending order (newest first for monotonic IDs). Default: true.
pub reversed: bool,
/// Generate and use hint files for faster recovery. Tunable.
/// When `true`, hint files are written on graceful shutdown and file
/// rotation, and used during recovery to skip full data scans.
/// Recommended `true` for VarTree (avoids decoding values on recovery),
/// `false` for ConstTree/TypedTree (values are small, full scan is fast).
/// Default: false.
pub hints: bool,
/// Use `O_DIRECT` on Linux for the hot serving path (active-file write +
/// live read fds). Tunable — in-memory effect only; the on-disk format is
/// identical regardless. Falls back to buffered if the filesystem rejects
/// `O_DIRECT`. No effect off Linux. Default: false.
pub direct_io: bool,
/// Bitcask flush-path I/O strategy. Tunable. Default: `Pwrite`.
/// See [`IoBackend`].
#[cfg_attr(any(feature = "armour", feature = "postcard-codec"), serde(default))]
pub io_backend: IoBackend,
/// 32-byte AES-256 encryption key. **Immutable** — presence/absence is
/// stored in `db.meta`. `None` = no encryption.
/// Use `PageCipher::key_from_env("ARMDB_KEY")` to read from environment.
#[cfg(feature = "encryption")]
pub encryption_key: Option<[u8; 32]>,
}
/// Configuration for the value cache used by `VarTree`.
#[cfg(feature = "var-collections")]
#[derive(Debug, Clone)]
#[cfg_attr(
any(feature = "armour", feature = "postcard-codec"),
derive(serde::Deserialize)
)]
pub struct CacheConfig {
/// Maximum cache size in bytes. 0 = disabled. Default: 0.
pub max_size: u64,
/// Estimated number of items (for hash table pre-allocation). Default: 100_000.
pub estimated_items: usize,
}
impl Config {
/// Config with small shard count for tests. Keeps fd usage low
/// so `cargo test` doesn't hit "Too many open files" on default ulimit.
pub fn test() -> Self {
Self {
shard_count: 2,
hints: true,
..Self::default()
}
}
pub fn validate(&self) -> DbResult<()> {
if self.shard_count == 0 || self.shard_count > 255 {
return Err(DbError::Config("shard_count must be between 1 and 255"));
}
if self.max_file_size < 4096 {
return Err(DbError::Config("max_file_size must be at least 4096"));
}
if self.write_buffer_size < 4096 {
return Err(DbError::Config("write_buffer_size must be at least 4096"));
}
if self.max_file_size > u32::MAX as u64 {
return Err(DbError::Config(
"max_file_size must not exceed u32::MAX (4 GiB)",
));
}
if (self.write_buffer_size as u64) > (u32::MAX as u64) - 4096 {
return Err(DbError::Config(
"write_buffer_size must not exceed u32::MAX - 4096",
));
}
if (self.write_buffer_size as u64) > self.max_file_size {
return Err(DbError::Config(
"max_file_size must be >= write_buffer_size",
));
}
if self.shard_prefix_bits > u8::MAX as usize {
return Err(DbError::Config("shard_prefix_bits must be <= 255"));
}
if !self.compaction_threshold.is_finite()
|| !(0.0..=1.0).contains(&self.compaction_threshold)
{
return Err(DbError::Config(
"compaction_threshold must be a finite value in [0.0, 1.0]",
));
}
let page_aligned = {
#[cfg(feature = "encryption")]
{
self.direct_io || self.encryption_key.is_some()
}
#[cfg(not(feature = "encryption"))]
{
self.direct_io
}
};
if page_aligned {
if self.write_buffer_size < 8192 {
return Err(DbError::Config(
"write_buffer_size must be at least 8192 when direct_io or encryption is enabled",
));
}
if !self.write_buffer_size.is_multiple_of(4096) {
return Err(DbError::Config(
"write_buffer_size must be a multiple of 4096 when direct_io or encryption is enabled",
));
}
}
Ok(())
}
}
impl Default for Config {
fn default() -> Self {
#[cfg(debug_assertions)]
let shard_count = std::thread::available_parallelism()
.map(|p| p.get() / 2)
.unwrap_or(2)
.clamp(1, 4);
#[cfg(not(debug_assertions))]
let shard_count = std::thread::available_parallelism()
.map(|p| p.get() / 2)
.unwrap_or(4)
.clamp(1, 8);
Self {
shard_count,
max_file_size: 256 * 1024 * 1024,
compaction_threshold: 0.3,
enable_fsync: false,
write_buffer_size: 1024 * 1024, // 1 MB
#[cfg(feature = "var-collections")]
cache: CacheConfig::default(),
shard_prefix_bits: 0,
reversed: true,
hints: false,
direct_io: false,
io_backend: IoBackend::default(),
#[cfg(feature = "encryption")]
encryption_key: None,
}
}
}
#[cfg(feature = "var-collections")]
impl Default for CacheConfig {
fn default() -> Self {
Self {
max_size: 0,
estimated_items: 100_000,
}
}
}
#[cfg(test)]
mod io_backend_tests {
use super::*;
#[test]
fn default_io_backend_is_pwrite() {
let cfg = Config::default();
assert_eq!(cfg.io_backend, IoBackend::Pwrite);
}
#[test]
fn io_backend_default_impl_matches_config_default() {
assert_eq!(IoBackend::default(), IoBackend::Pwrite);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn default_for_test() -> Config {
Config {
shard_count: 2,
max_file_size: 256 * 1024 * 1024,
compaction_threshold: 0.3,
enable_fsync: false,
write_buffer_size: 1024 * 1024,
#[cfg(feature = "var-collections")]
cache: CacheConfig::default(),
shard_prefix_bits: 0,
reversed: true,
hints: false,
direct_io: false,
io_backend: IoBackend::default(),
#[cfg(feature = "encryption")]
encryption_key: None,
}
}
#[test]
fn test_default_config_is_valid() {
let cfg = Config::default();
assert!(cfg.shard_count >= 1);
assert!(cfg.validate().is_ok());
}
#[test]
fn validate_rejects_max_file_size_smaller_than_write_buffer() {
let mut cfg = default_for_test();
cfg.max_file_size = 4096;
cfg.write_buffer_size = 8192;
assert!(cfg.validate().is_err());
}
#[test]
fn validate_rejects_write_buffer_at_u32_limit() {
let mut cfg = default_for_test();
cfg.write_buffer_size = (u32::MAX as usize) - 4095;
cfg.max_file_size = u32::MAX as u64;
assert!(cfg.validate().is_err());
}
#[cfg(feature = "encryption")]
#[test]
fn validate_rejects_small_write_buffer_under_encryption() {
let mut cfg = default_for_test();
cfg.encryption_key = Some([0u8; 32]);
cfg.write_buffer_size = 4096;
assert!(cfg.validate().is_err());
}
#[cfg(feature = "encryption")]
#[test]
fn validate_rejects_non_page_multiple_write_buffer_under_encryption() {
let mut cfg = default_for_test();
cfg.encryption_key = Some([0u8; 32]);
cfg.write_buffer_size = 8192 + 100;
cfg.max_file_size = 256 * 1024 * 1024;
assert!(cfg.validate().is_err());
}
#[cfg(feature = "encryption")]
#[test]
fn validate_accepts_page_multiple_8k_under_encryption() {
let mut cfg = default_for_test();
cfg.encryption_key = Some([0u8; 32]);
cfg.write_buffer_size = 8192;
cfg.max_file_size = 256 * 1024 * 1024;
assert!(cfg.validate().is_ok());
}
#[test]
fn validate_accepts_plain_4096_write_buffer() {
let mut cfg = default_for_test();
cfg.write_buffer_size = 4096;
cfg.max_file_size = 8192;
assert!(cfg.validate().is_ok());
}
#[test]
fn validate_rejects_shard_prefix_bits_over_255() {
let mut cfg = default_for_test();
cfg.shard_prefix_bits = 256;
let err = cfg.validate().unwrap_err();
assert!(
err.to_string().contains("shard_prefix_bits"),
"expected shard_prefix_bits error, got: {err}"
);
}
#[test]
fn validate_rejects_compaction_threshold_nan() {
let mut cfg = default_for_test();
cfg.compaction_threshold = f64::NAN;
assert!(cfg.validate().is_err());
}
#[test]
fn validate_rejects_compaction_threshold_negative() {
let mut cfg = default_for_test();
cfg.compaction_threshold = -0.1;
assert!(cfg.validate().is_err());
}
#[test]
fn validate_rejects_compaction_threshold_over_one() {
let mut cfg = default_for_test();
cfg.compaction_threshold = 1.1;
assert!(cfg.validate().is_err());
}
#[test]
fn validate_accepts_compaction_threshold_half() {
let mut cfg = default_for_test();
cfg.compaction_threshold = 0.5;
assert!(cfg.validate().is_ok());
}
#[test]
fn validate_accepts_compaction_threshold_boundaries() {
let mut cfg = default_for_test();
cfg.compaction_threshold = 0.0;
assert!(cfg.validate().is_ok());
cfg.compaction_threshold = 1.0;
assert!(cfg.validate().is_ok());
}
#[test]
fn direct_io_requires_page_aligned_write_buffer() {
let mut c = default_for_test();
c.direct_io = true;
c.write_buffer_size = 5000; // not a multiple of 4096
assert!(c.validate().is_err());
c.write_buffer_size = 8192;
assert!(c.validate().is_ok());
c.write_buffer_size = 4096; // < 8192
assert!(c.validate().is_err());
}
#[test]
fn direct_io_defaults_false() {
assert!(!Config::default().direct_io);
}
}