armdb 0.15.1

sharded bitcask key-value storage optimized for NVMe
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
//! Typed-to-byte forwarding and full visible-source reconciliation.
#[cfg(test)]
use super::SegConfig;
use super::{SegMap, SegTree};
use crate::codec::Codec;
use crate::error::{DbError, DbResult};
use crate::hook::TypedWriteHook;
use crate::hook::WriteHook;
use crate::key::Key;
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops::ControlFlow;

/// Borrows only during planning/scanning; no adapter escapes into a commit event.
struct ByteHook<'a, K, T, C, H> {
    codec: &'a C,
    hook: &'a H,
    marker: PhantomData<fn() -> (K, T)>,
}
impl<K: Key, T, C: Codec<T>, H: TypedWriteHook<K, T>> WriteHook<K> for ByteHook<'_, K, T, C, H> {
    const NEEDS_INIT: bool = false;
    const NEEDS_WRITE: bool = H::NEEDS_WRITE;
    const PROJECTS: bool = true;
    const COUNTS: bool = true;
    fn on_write(&self, key: &K, old: Option<&[u8]>, new: Option<&[u8]>) {
        if !H::NEEDS_WRITE {
            return;
        }
        let decode = |b: &[u8]| {
            self.codec
                .decode_from(b)
                .map_err(|e| tracing::warn!(error=%e, "segmented on_write decode failed"))
                .ok()
        };
        let old = old.and_then(decode);
        let new = new.and_then(decode);
        self.hook.on_write(key, old.as_ref(), new.as_ref());
    }
    fn project(
        &self,
        key: &K,
        _: Option<&[u8]>,
        new: Option<&[u8]>,
        sink: &mut crate::ProjectionSink<'_>,
    ) -> DbResult<()> {
        if let Some(bytes) = new {
            self.hook
                .project(key, &self.codec.decode_from(bytes)?, sink)?;
        }
        Ok(())
    }
    fn counter_project(
        &self,
        key: &K,
        _: Option<&[u8]>,
        new: Option<&[u8]>,
        sink: &mut crate::CounterSink<'_>,
    ) -> DbResult<()> {
        if let Some(bytes) = new {
            self.hook
                .counter_project(key, &self.codec.decode_from(bytes)?, sink)?;
        }
        Ok(())
    }
}
/// Process-loss injection for index maintenance, driven like the migration
/// crash matrix: the child exits with 71 when `ARMDB_MIGRATION_CRASH` names this boundary.
#[cfg(feature = "test-faults")]
pub(crate) fn crash_at(boundary: &str) {
    if std::env::var("ARMDB_MIGRATION_CRASH").ok().as_deref() == Some(boundary) {
        std::process::exit(71);
    }
}

// The typed/byte adapter and reconcile behavior are identical for both orders.
macro_rules! impl_segmented_projections {
    ($facade:ident $(, $managed:meta)?) => {
        impl<K, T, C, H> $facade<K, T, C, H>
        where
            K: Key + Hash + Eq + Send + Sync + 'static,
            C: Codec<T>,
            H: TypedWriteHook<K, T>,
        {
            /// Apply a typed migration to every visible row (spec, variant A): rows whose
            /// segmented-index difference is non-empty are batched; each batch writes the
            /// index, makes it durable, then writes the source.
            $(#[$managed])?
            pub(crate) fn migrate_rows(
                &self,
                f: impl Fn(&K, &T) -> crate::MigrateAction<T>,
            ) -> DbResult<usize> {
                use crate::seg::index_migration::*;
                let seg = self.hook.projection_targets().filter(|t| t.has_segmented());
                let (rows, bytes) = self.effective_projection_limits();
                let mut batch = MigrationBatch::new(batch_max_entries(), BATCH_MAX_BYTES);
                let mut batch_no = 0u64;
                let mut changed = 0usize;
                let mut failure = None;
                self.core().scan(&mut |row| {
                    let step = (|| -> DbResult<()> {
                        let (key, old_bytes) = row?;
                        let old = self.codec.decode_from(&old_bytes)?;
                        let action = f(&key, &old);
                        if matches!(action, crate::MigrateAction::Keep) {
                            return Ok(());
                        }
                        self.check_own_migration_action()?;
                        let new_bytes = match &action {
                            crate::MigrateAction::Update(new) => Some(self.codec.encode(new)?),
                            _ => None,
                        };
                        drop(action);
                        drop(old);
                        changed += 1;
                        let ops = match seg {
                            None => Vec::new(),
                            Some(targets) => {
                                let plan = crate::projection::diff_projection_bytes(
                                    &self.byte_hook(),
                                    targets,
                                    rows,
                                    bytes,
                                    &key,
                                    Some(&old_bytes),
                                    new_bytes.as_deref(),
                                )?;
                                plan.check_segmented_ownership(key.as_bytes())?;
                                plan.segmented_ops()
                            }
                        };
                        if ops.is_empty() {
                            return self.apply_source_action(&key, new_bytes.as_deref());
                        }
                        let action = match new_bytes {
                            Some(b) => SourceAction::Put(b),
                            None => SourceAction::Delete,
                        };
                        let entry = BatchEntry {
                            key: key.as_bytes().to_vec(),
                            action,
                            ops,
                        };
                        if batch.must_drain_before(&entry) {
                            batch_no += 1;
                            self.apply_migration_batch(batch_no, batch.drain())?;
                        }
                        if batch.push(entry) {
                            batch_no += 1;
                            self.apply_migration_batch(batch_no, batch.drain())?;
                        }
                        Ok(())
                    })();
                    match step {
                        Ok(()) => ControlFlow::Continue(()),
                        Err(e) => {
                            failure = Some(e);
                            ControlFlow::Break(())
                        }
                    }
                });
                if let Some(e) = failure {
                    return Err(e);
                }
                if !batch.is_empty() {
                    batch_no += 1;
                    self.apply_migration_batch(batch_no, batch.drain())?;
                }
                Ok(changed)
            }

            fn apply_source_action(&self, key: &K, new: Option<&[u8]>) -> DbResult<()> {
                let admission = crate::seg::freeze::Admission::until_seal_fails(&self.core().config)?;
                match new {
                    Some(b) => self.core().put_with(key, b, admission),
                    None => self.core().delete_with(key, admission),
                }
            }

            fn apply_migration_batch(
                &self,
                _batch_no: u64,
                entries: Vec<crate::seg::index_migration::BatchEntry>,
            ) -> DbResult<()> {
                // Measure retained encoded allocations before entering any target capability.
                // This differs from conservative charged overhead and process-wide peak.
                let allocated = entries.capacity() * std::mem::size_of::<crate::seg::index_migration::BatchEntry>()
                    + entries.iter().map(|entry| {
                        entry.key.capacity()
                            + match &entry.action {
                                crate::seg::index_migration::SourceAction::Put(value) => value.capacity(),
                                crate::seg::index_migration::SourceAction::Delete => 0,
                            }
                            + entry.ops.capacity() * std::mem::size_of::<crate::seg::index_migration::DerivedOp>()
                            + entry.ops.iter().map(|op| op.key.capacity() + op.value.as_ref().map_or(0, Vec::capacity)).sum::<usize>()
                    }).sum::<usize>();
                metrics::histogram!("armdb.seg.index_migration.batch_allocated_bytes", "collection" => self.name()).record(allocated as f64);
                let targets = self
                    .hook
                    .projection_targets()
                    .ok_or(DbError::Internal("batch without targets"))?;
                let mut touched: Vec<&'static str> = Vec::new();
                for e in &entries {
                    for op in &e.ops {
                        let handle = targets
                            .segmented()
                            .find(|h| h.name == op.target)
                            .ok_or(DbError::UndeclaredIndexTarget { index: op.target })?;
                        let _cap = crate::index_maintenance::IndexMaintenance::enter(op.target);
                        match &op.value {
                            Some(v) => handle.inner.put_bytes(&op.key, v)?,
                            None => handle.inner.delete_bytes(&op.key)?,
                        }
                        if !touched.contains(&op.target) {
                            touched.push(op.target);
                        }
                    }
                }
                #[cfg(feature = "test-faults")]
                crate::seg::projections::crash_at(&format!("segidx:derived:{_batch_no}"));
                for name in &touched {
                    let handle = targets
                        .segmented()
                        .find(|h| h.name == *name)
                        .expect("touched target is declared");
                    handle.inner.durable_flush()?;
                    metrics::counter!("armdb.seg.index_migration.durable_flushes", "collection" => self.name(), "target" => *name).increment(1);
                }
                #[cfg(feature = "test-faults")]
                crate::seg::projections::crash_at(&format!("segidx:flushed:{_batch_no}"));
                for (_i, e) in entries.into_iter().enumerate() {
                    let key = K::from_bytes(&e.key);
                    match e.action {
                        crate::seg::index_migration::SourceAction::Put(b) => {
                            self.apply_source_action(&key, Some(&b))?
                        }
                        crate::seg::index_migration::SourceAction::Delete => {
                            self.apply_source_action(&key, None)?
                        }
                    }
                    #[cfg(feature = "test-faults")]
                    crate::seg::projections::crash_at(&format!("segidx:source:{_batch_no}:{}", _i + 1));
                }
                Ok(())
            }

            fn byte_hook(&self) -> ByteHook<'_, K, T, C, H> {
                ByteHook {
                    codec: &self.codec,
                    hook: &self.hook,
                    marker: PhantomData,
                }
            }
            /// Whether writes require a transaction, including empty declared halves.
            pub fn hook_active(&self) -> bool {
                H::NEEDS_WRITE
                    || self.hook.projection_targets().is_some()
                    || self.hook.counter_targets().is_some()
                    || H::EMITS
            }
            pub(crate) fn facade_guard(&self) -> DbResult<()> {
                if self.hook_active() {
                    Err(DbError::SegHookRequiresTx {
                        collection: self.name(),
                    })
                } else {
                    Ok(())
                }
            }
            /// Shared global projection budgets, clamped by this hook's limits.
            pub fn effective_projection_limits(&self) -> (usize, usize) {
                let (rows, bytes) = self.hook.projection_limits();
                (
                    rows.min(crate::projection::DEFAULT_MAX_PROJECTED_ROWS),
                    bytes.min(crate::projection::DEFAULT_MAX_PROJECTED_BYTES),
                )
            }
            $(#[$managed])?
            fn scan_bytes(&self, visit: &mut dyn FnMut(&K, &[u8]) -> DbResult<()>) -> DbResult<()> {
                let mut failure = None;
                self.core().scan(&mut |row| match row.and_then(|(k, v)| {
                    crate::projection::reconcile_value_read_fault()?;
                    visit(&k, &v)
                }) {
                    Ok(()) => ControlFlow::Continue(()),
                    Err(e) => {
                        failure = Some(e);
                        ControlFlow::Break(())
                    }
                });
                failure.map_or(Ok(()), Err)
            }
            /// Build one segmented target from every live row of this source.
            $(#[$managed])?
            pub(crate) fn backfill_index_target(&self, name: &'static str) -> DbResult<u64> {
                let Some(targets) = self.hook.projection_targets() else {
                    return Ok(0);
                };
                let Some(handle) = targets.segmented().find(|h| h.name == name) else {
                    return Err(DbError::Internal("backfill: undeclared segmented target"));
                };
                let (rows, bytes) = self.effective_projection_limits();
                let mut written = 0u64;
                self.scan_bytes(&mut |key, value| {
                    let mut sink = crate::ProjectionSink::new(targets, rows, bytes);
                    self.byte_hook().project(key, None, Some(value), &mut sink)?;
                    // Validate the complete segmented emission before this source row
                    // writes anything, including emissions for other declared targets.
                    for row in sink.rows() {
                        if targets.segmented().any(|h| h.name == row.target) {
                            crate::projection::check_owned_key(row.target, &row.key, key.as_bytes())?;
                        }
                    }
                    for row in sink.rows().iter().filter(|r| r.target == name) {
                        let _cap = crate::index_maintenance::IndexMaintenance::enter(name);
                        handle.inner.put_bytes(&row.key, &row.value)?;
                        written += 1;
                        #[cfg(feature = "test-faults")]
                        crate::seg::projections::crash_at(&format!("segidx:backfill:{written}"));
                    }
                    Ok(())
                })?;
                handle.inner.durable_flush()?;
                #[cfg(feature = "test-faults")]
                crate::seg::projections::crash_at("segidx:backfill-flushed");
                Ok(written)
            }
            /// Rebuild declared index targets only after a complete fallible scan.
            $(#[$managed])?
            pub(crate) fn reconcile_projections(&self) -> DbResult<()> {
                let Some(targets) = self.hook.projection_targets() else {
                    return Ok(());
                };
                let (rows, bytes) = self.effective_projection_limits();
                crate::projection::reconcile_carrier_projections(
                    targets,
                    |emit| {
                        self.scan_bytes(&mut |key, value| {
                            let mut sink = crate::ProjectionSink::new(targets, rows, bytes);
                            self.byte_hook()
                                .project(key, None, Some(value), &mut sink)?;
                            for row in sink.rows() {
                                emit(row.target, &row.key, &row.value)?;
                            }
                            Ok(())
                        })
                    },
                    true,
                )
            }
            /// Two-pass recount; target barriers precede clearing migration evidence.
            $(#[$managed])?
            pub(crate) fn reconcile_counters(&self) -> DbResult<u64> {
                let Some(targets) = self.hook.counter_targets() else {
                    return Ok(0);
                };
                crate::counter::recount(
                    |key, value: &[u8], sink| {
                        self.byte_hook()
                            .counter_project(key, None, Some(value), sink)
                    },
                    targets,
                    self.effective_projection_limits(),
                    &mut |visit| self.scan_bytes(visit),
                )
            }
            /// Names whose persisted migration evidence triggers a recount.
            $(#[$managed])?
            pub(crate) fn counter_target_names(&self) -> Vec<&'static str> {
                self.hook
                    .counter_targets()
                    .map(|t| t.all().map(|m| m.collection_name()).collect())
                    .unwrap_or_default()
            }
            pub(crate) fn fire_event(&self, event: &(K, Option<Vec<u8>>, Option<Vec<u8>>)) {
                self.byte_hook()
                    .on_write(&event.0, event.1.as_deref(), event.2.as_deref());
            }
            pub(crate) fn project_bytes(
                &self,
                key: &K,
                old: Option<&[u8]>,
                new: Option<&[u8]>,
            ) -> DbResult<Vec<crate::txn::participant::TxDerivedWrite>> {
                let Some(targets) = self.hook.projection_targets() else {
                    return Ok(Vec::new());
                };
                let (rows, bytes) = self.effective_projection_limits();
                let plan = crate::projection::diff_projection_bytes(
                    &self.byte_hook(),
                    targets,
                    rows,
                    bytes,
                    key,
                    old,
                    new,
                )?;
                // D10, before the log append: a refused plan applies nothing.
                plan.check_segmented_ownership(key.as_bytes())?;
                plan.into_tx_derived(targets)
            }
            pub(crate) fn counter_bytes(
                &self,
                key: &K,
                old: Option<&[u8]>,
                new: Option<&[u8]>,
            ) -> DbResult<Vec<crate::txn::participant::TxCounterDelta>> {
                let Some(targets) = self.hook.counter_targets() else {
                    return Ok(Vec::new());
                };
                let (rows, bytes) = self.effective_projection_limits();
                let deltas = crate::counter::diff_counters_bytes(
                    &self.byte_hook(),
                    targets,
                    rows,
                    bytes,
                    key,
                    old,
                    new,
                )?;
                crate::counter::into_tx_counter_deltas(targets, deltas)
            }
        }
    };
}
impl_segmented_projections!(SegMap);
impl_segmented_projections!(SegTree);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::armour::Db;
    use crate::counter_tests::Group;
    use crate::seg::testkit::{TestKey, TextCodec, key_of, meta};
    use crate::{Config, IndexTargets, NoHook, Projected, RapiraCodec};

    #[test]
    fn segmented_projection_decode_failure_preserves_orphans() {
        let dir = tempfile::tempdir().unwrap();
        let db = Db::open_test(dir.path()).unwrap();
        let index = db
            .open_var_typed_map::<Group, RapiraCodec, _>(Config::test(), NoHook, &[])
            .unwrap();
        let target = index.clone();
        let hook = Projected::<TestKey, String>::new(
            IndexTargets::new().with_index(&index),
            move |_, value, sink| {
                let n: u64 = value.parse().unwrap();
                sink.row(&target, n.to_be_bytes(), Group { member_count: n })
            },
        );
        let map = SegMap::open_deferred(
            &dir.path().join("source"),
            meta(),
            SegConfig::test(),
            TextCodec,
            hook,
        )
        .unwrap();
        for n in 0..20 {
            map.core()
                .put(&key_of(n), n.to_string().as_bytes())
                .unwrap();
        }
        // Arrange a corrupt value after readable rows in the actual scan order.
        let mut order = Vec::new();
        map.core().scan(&mut |row| {
            order.push(row.unwrap().0);
            ControlFlow::Continue(())
        });
        let bad = order.last().unwrap();
        map.core().put(bad, &[0xff]).unwrap();
        index
            .put(&999u64.to_be_bytes(), &Group { member_count: 999 })
            .unwrap();
        let result = map.reconcile_projections();
        assert!(index.try_get(&999u64.to_be_bytes()).unwrap().is_some());
        assert!(matches!(result, Err(DbError::CorruptedEntry { .. })));
        // Repaired scan is complete before orphan deletion may proceed.
        map.core().put(bad, b"500").unwrap();
        map.reconcile_projections().unwrap();
        assert!(index.try_get(&999u64.to_be_bytes()).unwrap().is_none());
        assert!(index.try_get(&500u64.to_be_bytes()).unwrap().is_some());
    }
    #[test]
    fn tree_reconcile_decode_failure_preserves_orphans() {
        let dir = tempfile::tempdir().unwrap();
        let db = Db::open_test(dir.path()).unwrap();
        let index = db
            .open_var_typed_map::<Group, RapiraCodec, _>(Config::test(), NoHook, &[])
            .unwrap();
        let target = index.clone();
        let hook = Projected::<TestKey, String>::new(
            IndexTargets::new().with_index(&index),
            move |_, value, sink| {
                let n: u64 = value.parse().unwrap();
                sink.row(&target, n.to_be_bytes(), Group { member_count: n })
            },
        );
        let map = crate::seg::SegTree::open_deferred(
            &dir.path().join("source"),
            meta(),
            &[],
            false,
            SegConfig::test(),
            TextCodec,
            hook,
        )
        .unwrap();
        for n in 0..300 {
            map.core()
                .put(&key_of(n), n.to_string().as_bytes())
                .unwrap();
        }
        // Arrange a corrupt value after readable rows in the actual scan order.
        let mut order = Vec::new();
        map.core().scan(&mut |row| {
            order.push(row.unwrap().0);
            ControlFlow::Continue(())
        });
        let bad = order.last().unwrap();
        map.core().put(bad, &[0xff]).unwrap();
        index
            .put(&999u64.to_be_bytes(), &Group { member_count: 999 })
            .unwrap();
        map.seal().unwrap();
        assert!(map.core().seal_oldest().unwrap());
        // Warm a user read before the internal cache-bypassing full scan.
        map.try_get(&order[0]).unwrap();
        let before = (map.stats().cache_hits, map.stats().cache_misses);
        assert!(matches!(
            map.project_bytes(bad, Some(&[0xff]), Some(b"500")),
            Err(DbError::CorruptedEntry { .. })
        ));
        let result = map.reconcile_projections();
        assert_eq!((map.stats().cache_hits, map.stats().cache_misses), before);
        assert!(index.try_get(&999u64.to_be_bytes()).unwrap().is_some());
        assert!(matches!(result, Err(DbError::CorruptedEntry { .. })));
        // Repaired scan is complete before orphan deletion may proceed.
        map.core().put(bad, b"500").unwrap();
        map.reconcile_projections().unwrap();
        assert_eq!((map.stats().cache_hits, map.stats().cache_misses), before);
        assert!(index.try_get(&999u64.to_be_bytes()).unwrap().is_none());
        assert!(index.try_get(&500u64.to_be_bytes()).unwrap().is_some());
    }
}