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
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
//! `SegTree`: the segmented collection with typed values.

use crate::hook::{NoHook, TypedWriteHook};

use super::freeze::Admission;
use super::index_target::{self, IndexState, IndexStateCell};
use std::hash::Hash;
use std::marker::PhantomData;
use std::ops::{Bound, ControlFlow};
use std::path::Path;
use std::sync::{Arc, OnceLock, Weak};
use std::time::Duration;

use super::config::SegConfig;
use super::core::{OpenOptions, SegCore, SegMeta};
use super::ordered::RawOrderedIter;
use super::query::SegRange;
use super::verify::{SegmentInfo, VerifyReport, VerifyScope};
use super::worker::SealStatus;
use crate::codec::Codec;
use crate::error::{DbError, DbResult};
use crate::key::Key;
use crate::{CollectionMeta, KeyPage, Page};

/// Declared prefix-filter lengths for future segments of a managed tree.
/// Lengths must be valid key component boundaries; reopening affects future seals.
pub trait SegTreeMeta: CollectionMeta {
    /// Optional filter lengths in bytes. Missing filters never suppress older rows.
    const PREFIX_FILTERS: &'static [usize] = &[];
    /// This collection holds derived index rows: no retention, no segment
    /// drops, no direct writes, only `Keep` in its own typed migrations.
    const INDEX_TARGET: bool = false;
}

/// A byte-ordered collection for large, mostly immutable data: an active generation with
/// its keys in RAM, and sealed segments with their keys on disk.
///
/// Values are written once and read many times. `put` and `delete` are
/// blind: they do not look at older layers. `insert` does, at the price of a
/// probe. The facade has no read-modify-write; managed transactions support
/// `upsert` and `guard`. Active hooks require writes through `Db::tx`.
/// Older-layer lookups hold transaction participant locks, and concurrent
/// readers may observe partial application across collections.
///
/// Order follows encoded key bytes; use big-endian numeric key components for
/// numeric order. Scans are weakly consistent and buffer owned batches. `len()`
/// counts layer entries and is an upper bound on visible rows.
///
/// A `SegTree` whose type declares `SegTreeMeta::INDEX_TARGET` can be an index target of a
/// segmented source; it is never a counter, queue or replication target.
///
/// ```compile_fail
/// use armdb::{QueueTargets, RapiraCodec, seg::SegTree};
/// use std::sync::Arc;
/// fn reject(tree: Arc<SegTree<[u8;8],u64,RapiraCodec>>) {
///     QueueTargets::new().with(&tree);
/// }
/// ```
///
/// ```compile_fail
/// use armdb::{RapiraCodec, seg::SegTree};
/// fn reject(tree: SegTree<[u8;8],u64,RapiraCodec>) {
///     tree.scope::<8>(&[0;8]);
/// }
/// ```
///
/// ```compile_fail
/// use armdb::{CounterCollection, RapiraCodec, seg::SegTree};
/// fn require_counter<T: CounterCollection>() {}
/// require_counter::<SegTree<[u8; 8], u64, RapiraCodec>>();
/// ```
///
/// ```compile_fail
/// use armdb::{RapiraCodec, seg::SegTree, replication::ReplicationTarget};
/// fn require_replication<T: ReplicationTarget>() {}
/// require_replication::<SegTree<[u8; 8], u64, RapiraCodec>>();
/// ```
///
/// Typed migrations run through [`crate::Db::open_seg_tree`], which coordinates
/// durable version publication and projection reconciliation. The hook-free
/// migration helper is internal to managed opening.
///
/// ```compile_fail
/// use armdb::{RapiraCodec, seg::SegTree};
/// fn reject(tree: &SegTree<[u8; 8], u64, RapiraCodec>) {
///     let keep: fn(&[u8; 8], &u64) -> armdb::MigrateAction<u64> =
///         |_, _| armdb::MigrateAction::Keep;
///     tree.migrate_rows(&keep);
/// }
/// ```
pub struct SegTree<K: Key + Hash + Eq + Send + Sync + 'static, T, C, H = NoHook> {
    core: Arc<SegCore<K>>,
    pub(crate) codec: C,
    pub(crate) hook: H,
    pub(crate) tx_self: OnceLock<Weak<Self>>,
    /// Declared by `SegTreeMeta::INDEX_TARGET`: derived index rows, written
    /// only by the engine.
    index_target: bool,
    /// Bound by the `Db` at a managed open; `None` for any other collection.
    index_state: OnceLock<Arc<IndexStateCell>>,
    _value: PhantomData<fn() -> T>,
}

impl<K, T, C> SegTree<K, T, C>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    C: Codec<T>,
{
    /// Open or create the collection in `path`.
    ///
    /// The handle is never an index target, whatever `SegTreeMeta::INDEX_TARGET`
    /// declares: the role belongs to `Db::open_seg_tree`.
    pub fn open(
        path: &Path,
        meta: SegMeta,
        prefix_filters: &'static [usize],
        config: SegConfig,
        codec: C,
    ) -> DbResult<Self> {
        Self::open_with(
            path,
            meta,
            prefix_filters,
            config,
            codec,
            OpenOptions::production(),
        )
    }

    /// Open with injectable filesystem, clock and worker options.
    pub(crate) fn open_with(
        path: &Path,
        meta: SegMeta,
        prefix_filters: &'static [usize],
        config: SegConfig,
        codec: C,
        options: OpenOptions,
    ) -> DbResult<Self> {
        Ok(Self {
            core: SegCore::open_tree(path, meta, prefix_filters, config, options)?,
            codec,
            hook: NoHook,
            tx_self: OnceLock::new(),
            index_target: false,
            index_state: OnceLock::new(),
            _value: PhantomData,
        })
    }
}

impl<K, T, C, H> SegTree<K, T, C, H>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    C: Codec<T>,
    H: TypedWriteHook<K, T>,
{
    pub(crate) fn open_deferred(
        path: &Path,
        meta: SegMeta,
        prefix_filters: &'static [usize],
        index_target: bool,
        config: SegConfig,
        codec: C,
        hook: H,
    ) -> DbResult<Self> {
        Ok(Self {
            core: SegCore::open_tree_deferred(
                path,
                meta,
                prefix_filters,
                config,
                OpenOptions::production(),
            )?,
            codec,
            hook,
            tx_self: OnceLock::new(),
            index_target,
            index_state: OnceLock::new(),
            _value: PhantomData,
        })
    }

    /// The byte-oriented core used by internal integrations.
    pub(crate) fn core(&self) -> &Arc<SegCore<K>> {
        &self.core
    }

    /// The collection name supplied in its metadata.
    pub fn name(&self) -> &'static str {
        self.core.meta.name
    }

    /// The lifecycle state of a managed index target, or `None` for any other collection.
    pub fn index_state(&self) -> Option<IndexState> {
        self.index_state.get().map(|cell| cell.get())
    }

    pub(crate) fn is_index_target(&self) -> bool {
        self.index_target
    }

    /// Whether a transaction participant refuses explicit operations. One name
    /// for `SegMap` and `SegTree`, which share the participant implementation.
    pub(crate) fn is_index_target_participant(&self) -> bool {
        self.is_index_target()
    }

    pub(crate) fn bind_index_state(&self, cell: Arc<IndexStateCell>) {
        let _ = self.index_state.set(cell);
    }

    /// A write by the engine's own maintenance (build, migration, repair).
    /// Refused unless the caller holds the capability for this collection.
    pub(crate) fn maintenance_write(&self, key: &[u8], value: Option<&[u8]>) -> DbResult<()> {
        if !crate::index_maintenance::IndexMaintenance::consume(self.name()) {
            return Err(DbError::Config(index_target::DIRECT_WRITE));
        }
        if key.len() != size_of::<K>() {
            return Err(DbError::CorruptedEntry { offset: 0 });
        }
        let k = K::from_bytes(key);
        let admission = Admission::until_seal_fails(&self.core.config)?;
        match value {
            Some(v) => self.core.put_with(&k, v, admission),
            None => self.core.delete_with(&k, admission),
        }
    }

    /// Current sizes and counters from the current segments. Dropped segments
    /// take their read counters with them. Cache counters cover this open
    /// collection handle.
    pub fn stats(&self) -> super::verify::SegStats {
        self.core.stats()
    }

    /// The configuration used when opening this collection.
    pub fn config(&self) -> &SegConfig {
        &self.core.config
    }

    /// Write `value`, shadowing any older version in any layer.
    pub fn put(&self, key: &K, value: &T) -> DbResult<()> {
        if self.is_index_target() {
            return Err(DbError::Config(index_target::DIRECT_WRITE));
        }
        self.facade_guard()?;
        self.core.put(key, &self.codec.encode(value)?)
    }

    /// Write `value` only when no layer holds a live version of `key`;
    /// otherwise `DbError::KeyExists`.
    pub fn insert(&self, key: &K, value: &T) -> DbResult<()> {
        if self.is_index_target() {
            return Err(DbError::Config(index_target::DIRECT_WRITE));
        }
        self.facade_guard()?;
        self.core.insert(key, &self.codec.encode(value)?)
    }

    /// Insert-if-absent that trusts the caller's claim: this key, if it exists,
    /// was last written at or after `written_since_ms` (epoch milliseconds).
    /// Layers frozen before it are skipped; the active layer is always checked.
    /// A false claim can shadow an existing key instead of returning `KeyExists`.
    /// The claim is not validated or logged. See [`Self::try_get_hinted`].
    pub fn insert_hinted(&self, key: &K, value: &T, written_since_ms: u64) -> DbResult<()> {
        if self.is_index_target() {
            return Err(DbError::Config(index_target::DIRECT_WRITE));
        }
        self.facade_guard()?;
        self.core
            .insert_since(key, &self.codec.encode(value)?, Some(written_since_ms))
    }

    /// Write a tombstone. It is written whether or not the key exists.
    pub fn delete(&self, key: &K) -> DbResult<()> {
        if self.is_index_target() {
            return Err(DbError::Config(index_target::DIRECT_WRITE));
        }
        self.facade_guard()?;
        self.core.delete(key)
    }

    fn decode(&self, bytes: Option<Vec<u8>>) -> DbResult<Option<T>> {
        bytes.map(|b| self.codec.decode_from(&b)).transpose()
    }

    /// `Ok(None)` only when the key is absent. A key that cannot be read or
    /// decoded is an error.
    pub fn try_get(&self, key: &K) -> DbResult<Option<T>> {
        self.decode(self.core.get(key)?)
    }

    /// Lenient read: an error is logged and reads as `None`.
    pub fn get(&self, key: &K) -> Option<T> {
        metrics::counter!("armdb.ops", "op" => "get", "tree" => "seg_tree").increment(1);
        match self.try_get(key) {
            Ok(value) => value,
            Err(e) => {
                tracing::error!(collection = self.name(), error = %e, "SegTree get error");
                None
            }
        }
    }

    /// Read and decode a value, returning [`DbError::KeyNotFound`] only
    /// when the key is absent. Storage and codec errors are preserved.
    pub fn get_or_err(&self, key: &K) -> DbResult<T> {
        self.try_get(key)?.ok_or(DbError::KeyNotFound)
    }

    /// Whether a live version of `key` exists. Does not decode the value.
    pub fn try_contains(&self, key: &K) -> DbResult<bool> {
        self.core.contains(key)
    }

    /// Lenient: an error is logged and reads as `false`.
    pub fn contains(&self, key: &K) -> bool {
        match self.try_contains(key) {
            Ok(found) => found,
            Err(e) => {
                tracing::error!(collection = self.name(), error = %e, "SegTree contains error");
                false
            }
        }
    }

    /// A point read that trusts the caller's claim: the key, if it exists,
    /// was last written at or after `written_since_ms` (epoch milliseconds).
    ///
    /// When the claim holds the result equals [`try_get`](Self::try_get).
    /// When it does not, the result may be `None` for a key that exists.
    /// This is pruning by layer, not a filter on write time: a version older
    /// than the hint is returned when its layer was frozen after it.
    pub fn try_get_hinted(&self, key: &K, written_since_ms: u64) -> DbResult<Option<T>> {
        self.decode(self.core.get_hinted(key, written_since_ms)?)
    }

    /// Live entries of every layer. An **upper bound** on the number of
    /// visible keys: a shadowed or deleted version is counted while its
    /// layer lives.
    pub fn len(&self) -> usize {
        self.core.len()
    }

    /// `true` proves that no key is visible. `false` does not prove that
    /// one is.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Freeze the active generation and queue its seal. Returns once the
    /// freeze is durable; it does not wait for the segment. A no-op on an
    /// empty generation.
    pub fn seal(&self) -> DbResult<()> {
        self.core.seal()
    }

    /// Block until no generation waits for a seal. `Ok(false)` on timeout.
    pub fn wait_sealed(&self, timeout: Duration) -> DbResult<bool> {
        self.core.wait_sealed(timeout)
    }

    /// Snapshot the pending seals and the worker's latest result.
    pub fn seal_status(&self) -> SealStatus {
        self.core.seal_status()
    }

    /// The sealed segments, oldest first.
    pub fn segments(&self) -> Vec<SegmentInfo> {
        self.core.segments()
    }

    /// Drop the longest prefix of oldest segments frozen before `ts_ms`.
    /// Segments go one at a time: on an error, those dropped before it stay
    /// dropped, and [`Self::segments`] shows what is left.
    pub fn drop_segments_before(&self, ts_ms: u64) -> DbResult<usize> {
        if self.is_index_target() {
            return Err(DbError::Config(index_target::NO_DROP));
        }
        if self.hook.projection_targets().is_some() || self.hook.counter_targets().is_some() {
            return Err(DbError::Config(
                "segmented projection sources cannot drop segments",
            ));
        }
        self.core.drop_segments_before(ts_ms)
    }

    /// Check sealed segments against the manifest. Reads every block of the
    /// segments in scope.
    pub fn verify(&self, scope: VerifyScope) -> DbResult<VerifyReport> {
        self.core.verify(scope)
    }

    /// Write buffers of every generation to the operating system, without
    /// an fsync.
    pub fn flush(&self) -> DbResult<()> {
        self.core.flush()
    }

    /// The strongest barrier: buffers and fsync of every generation, frozen
    /// ones included.
    pub fn durable_flush(&self) -> DbResult<()> {
        self.core.durable_flush()
    }

    /// Shards of any generation that hold writes no barrier covers yet.
    pub fn dirty_shards(&self) -> usize {
        self.core.dirty_shards()
    }

    /// Stop the worker, make every generation durable and write its hint
    /// files. A running seal is aborted and runs again after the next open.
    ///
    /// Stop writers first. A write after this is still taken while the
    /// active generation has room, and costs the clean-recovery fast path.
    pub fn clean_shutdown(&self) -> DbResult<()> {
        self.core.clean_shutdown()
    }

    /// Scan all visible rows in ascending key-byte order.
    pub fn iter(&self) -> SegIter<'_, K, T, C> {
        self.scan(SegRange::all())
    }
    /// Scan the half-open byte interval `[start, end)`.
    pub fn range(&self, start: &K, end: &K) -> SegIter<'_, K, T, C> {
        self.range_bounds(Bound::Included(start), Bound::Excluded(end))
    }
    /// Scan explicitly included, excluded or unbounded endpoints.
    pub fn range_bounds(&self, start: Bound<&K>, end: Bound<&K>) -> SegIter<'_, K, T, C> {
        self.scan(SegRange::range(start, end))
    }
    /// Scan keys beginning with `prefix`. An overlong prefix is empty.
    pub fn prefix_iter(&self, prefix: &[u8]) -> SegIter<'_, K, T, C> {
        self.scan(SegRange::prefix(prefix))
    }
    /// Scan an owned query. Time hints prune layers and trust the caller's claim.
    ///
    /// Rows are weakly consistent and returned from owned bounded batches. An idle
    /// iterator retains no generation or segment. An error is yielded once, then EOF.
    pub fn scan(&self, query: SegRange<K>) -> SegIter<'_, K, T, C> {
        SegIter {
            raw: self.core.ordered_iter(query, true, true),
            codec: &self.codec,
            ended: false,
            _value: PhantomData,
        }
    }
    /// Scan only keys, without reading journal values or decoding any values.
    pub fn scan_keys(&self, query: SegRange<K>) -> SegKeyIter<'_, K> {
        SegKeyIter {
            raw: self.core.ordered_iter(query, false, true),
        }
    }
    /// The first visible row in ascending byte order, preserving read/decode errors.
    pub fn first(&self) -> DbResult<Option<(K, T)>> {
        let mut iter = self.iter();
        iter.raw.limit_rows(1);
        iter.next().transpose()
    }
    /// The last visible row in ascending byte order, preserving read/decode errors.
    pub fn last(&self) -> DbResult<Option<(K, T)>> {
        let mut iter = self.scan(SegRange::all().rev());
        iter.raw.limit_rows(1);
        iter.next().transpose()
    }
    /// Stateless page within the query, strictly after the cursor in its direction.
    /// A full page sets `next` even at true EOF; a zero limit is empty.
    pub fn page(
        &self,
        query: SegRange<K>,
        after: Option<&K>,
        limit: usize,
    ) -> DbResult<Page<K, T>> {
        let mut iter = self.scan(query.after(after));
        iter.raw.limit_rows(limit);
        let items: Vec<_> = iter.take(limit).collect::<DbResult<_>>()?;
        let next = if limit != 0 && items.len() == limit {
            items.last().map(|r| r.0)
        } else {
            None
        };
        Ok(Page { items, next })
    }
    /// Stateless keys-only page, with the same cursor and limit rules as [`Self::page`].
    pub fn keys_page(
        &self,
        query: SegRange<K>,
        after: Option<&K>,
        limit: usize,
    ) -> DbResult<KeyPage<K>> {
        let mut iter = self.scan_keys(query.after(after));
        iter.raw.limit_rows(limit);
        let keys: Vec<_> = iter.take(limit).collect::<DbResult<_>>()?;
        let next = if limit != 0 && keys.len() == limit {
            keys.last().copied()
        } else {
            None
        };
        Ok(KeyPage { keys, next })
    }
    pub(super) fn check_own_migration_action(&self) -> DbResult<()> {
        if self.is_index_target() {
            Err(DbError::Config(index_target::KEEP_ONLY))
        } else {
            Ok(())
        }
    }

    /// Visit every visible row. With `decode`, each row is decoded and a row
    /// that does not decode is handed over as an error; without it, only
    /// the rows that fail to decode are handed over. A storage error ends
    /// the walk. The scan is weakly consistent: each row was the newest
    /// version of its key when its scan window was read. The callback may
    /// end the walk by returning `ControlFlow::Break(())`.
    pub(crate) fn walk_rows(
        &self,
        decode: bool,
        visit: &mut dyn FnMut(DbResult<(K, T)>) -> ControlFlow<()>,
    ) {
        self.core.scan(&mut |row| match row {
            Err(e) => {
                let _ = visit(Err(e));
                ControlFlow::Break(())
            }
            Ok((key, bytes)) => match self.codec.decode_from(&bytes) {
                Ok(value) if decode => visit(Ok((key, value))),
                Ok(_) => ControlFlow::Continue(()),
                Err(e) => {
                    tracing::warn!(collection = self.name(), error = %e, "a segmented row does not decode");
                    visit(Err(e))
                }
            },
        });
    }
}

impl<K, T, C> crate::projection::sealed::Sealed for SegTree<K, T, C, NoHook>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    T: SegTreeMeta + Send + Sync + 'static,
    C: Codec<T> + Send + Sync + 'static,
{
}

impl<K, T, C> crate::projection::ProjectableIndex for SegTree<K, T, C, NoHook>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    T: SegTreeMeta + PartialEq + Send + Sync + 'static,
    C: Codec<T> + Send + Sync + 'static,
{
    fn collection_name(&self) -> &'static str {
        self.name()
    }

    fn put_bytes(&self, key: &[u8], value: &[u8]) -> DbResult<()> {
        self.maintenance_write(key, Some(value))
    }

    fn delete_bytes(&self, key: &[u8]) -> DbResult<()> {
        self.maintenance_write(key, None)
    }

    fn values_equal(&self, a: &[u8], b: &[u8]) -> DbResult<bool> {
        if a == b {
            return Ok(true);
        }
        Ok(self.codec.decode_from(a)? == self.codec.decode_from(b)?)
    }

    fn for_each_bytes(&self, f: &mut dyn FnMut(&[u8], &[u8]) -> DbResult<()>) -> DbResult<()> {
        let mut failure = None;
        self.core.scan(
            &mut |row| match row.and_then(|(k, v)| f(k.as_bytes(), &v)) {
                Ok(()) => ControlFlow::Continue(()),
                Err(e) => {
                    failure = Some(e);
                    ControlFlow::Break(())
                }
            },
        );
        failure.map_or(Ok(()), Err)
    }

    fn durable_flush(&self) -> DbResult<()> {
        self.core.durable_flush()
    }

    /// The role this handle was opened with, not the type's declaration: a
    /// standalone `open` never takes the role, so its handle stays ordinary.
    fn target_kind(&self) -> crate::projection::TargetKind {
        crate::projection::TargetKind::Segmented {
            declared: self.is_index_target(),
        }
    }

    fn physical_entries(&self) -> Option<u64> {
        Some(self.core.physical_entries())
    }
}

impl<K, T, C> crate::projection::ProjectableIndexTx for SegTree<K, T, C, NoHook>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    T: SegTreeMeta + PartialEq + Send + Sync + 'static,
    C: Codec<T> + Send + Sync + 'static,
{
    fn as_tx_participant(self: Arc<Self>) -> Arc<dyn crate::txn::participant::TxParticipant> {
        self
    }
}

impl<K, T, C> crate::projection::IndexKeyed for SegTree<K, T, C, NoHook>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    T: SegTreeMeta + Clone + PartialEq + Send + Sync + 'static,
    C: Codec<T> + Send + Sync + 'static,
{
    type K = K;
    type V = T;

    fn encode_value(&self, v: &T) -> DbResult<Vec<u8>> {
        self.codec.encode(v)
    }
}

impl<K: Key + Hash + Eq + Send + Sync + 'static, T, C, H> Drop for SegTree<K, T, C, H> {
    fn drop(&mut self) {
        self.core.stop_worker();
    }
}

/// Strict typed iterator over owned batches; storage or decode errors end iteration.
/// Weak consistency applies to each batch. This iterator cannot be reversed in place.
pub struct SegIter<'a, K: Key + Hash + Eq + Send + Sync + 'static, T, C> {
    raw: RawOrderedIter<'a, K>,
    codec: &'a C,
    ended: bool,
    _value: PhantomData<fn() -> T>,
}
impl<K: Key + Hash + Eq + Send + Sync + 'static, T, C: Codec<T>> Iterator for SegIter<'_, K, T, C> {
    type Item = DbResult<(K, T)>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.ended {
            return None;
        }
        let row = self
            .raw
            .next()?
            .and_then(|(key, bytes)| self.codec.decode_from(&bytes).map(|value| (key, value)));
        if row.is_err() {
            self.ended = true;
        }
        Some(row)
    }
}
/// Strict keys-only iterator; values are never decoded.
pub struct SegKeyIter<'a, K: Key + Hash + Eq + Send + Sync + 'static> {
    raw: RawOrderedIter<'a, K>,
}
impl<K: Key + Hash + Eq + Send + Sync + 'static> Iterator for SegKeyIter<'_, K> {
    type Item = DbResult<K>;
    fn next(&mut self) -> Option<Self::Item> {
        self.raw.next().map(|row| row.map(|(key, _)| key))
    }
}

impl<K, T, C, H> crate::armour::collection::Collection for SegTree<K, T, C, H>
where
    K: Key + Hash + Eq + Send + Sync + 'static,
    T: Send + Sync,
    C: Codec<T>,
    H: TypedWriteHook<K, T>,
{
    fn reconcile_counters(&self) -> DbResult<u64> {
        SegTree::reconcile_counters(self)
    }
    fn counter_target_names(&self) -> Vec<&'static str> {
        SegTree::counter_target_names(self)
    }

    fn name(&self) -> &str {
        self.core.meta.name
    }

    /// An upper bound on the number of visible keys.
    fn len(&self) -> usize {
        self.core.len()
    }

    /// Nothing to compact: a segment is dropped as a whole. Seal and
    /// retention run on the collection's own worker, so the shared
    /// compaction thread never waits on them.
    fn compact(&self) -> DbResult<usize> {
        Ok(0)
    }

    fn flush(&self) -> DbResult<()> {
        self.core.flush()
    }

    fn periodic_flush(&self) -> DbResult<()> {
        self.core.durable_flush()
    }

    fn durable_flush(&self) -> DbResult<()> {
        self.core.durable_flush()
    }

    fn clean_shutdown(&self) -> DbResult<()> {
        self.core.clean_shutdown()
    }

    fn dirty_shards(&self) -> Option<usize> {
        Some(self.core.dirty_shards())
    }
}

#[cfg(test)]
#[cfg(feature = "segmented")]
mod managed_tests {
    use super::*;
    use crate::seg::testkit::{TestKey, TextCodec, meta, ordered_key};

    #[test]
    fn maintenance_write_needs_the_capability_for_its_collection() {
        use crate::index_maintenance::IndexMaintenance;
        let dir = tempfile::tempdir().unwrap();
        let tree = SegTree::<TestKey, String, TextCodec>::open_with(
            dir.path(),
            meta(),
            &[],
            SegConfig::test(),
            TextCodec,
            OpenOptions {
                worker: false,
                ..OpenOptions::production()
            },
        )
        .unwrap();
        let key = ordered_key(1);
        assert!(matches!(
            tree.maintenance_write(key.as_slice(), Some(b"v")),
            Err(DbError::Config(_))
        ));
        {
            let _other = IndexMaintenance::enter("another_collection");
            assert!(matches!(
                tree.maintenance_write(key.as_slice(), Some(b"v")),
                Err(DbError::Config(_))
            ));
        }
        assert_eq!(
            tree.try_get(&key).unwrap(),
            None,
            "refused writes apply nothing"
        );

        let _cap = IndexMaintenance::enter(tree.name());
        assert!(matches!(
            tree.maintenance_write(&key[1..], Some(b"v")),
            Err(DbError::CorruptedEntry { .. })
        ));
        assert!(
            matches!(
                tree.maintenance_write(key.as_slice(), Some(b"v")),
                Err(DbError::Config(_))
            ),
            "even a failed mutation spends its grant"
        );
        let _put = IndexMaintenance::enter(tree.name());
        tree.maintenance_write(key.as_slice(), Some(b"v")).unwrap();
        assert_eq!(tree.try_get(&key).unwrap().as_deref(), Some("v"));
        let _delete = IndexMaintenance::enter(tree.name());
        tree.maintenance_write(key.as_slice(), None).unwrap();
        assert_eq!(tree.try_get(&key).unwrap(), None);
    }

    #[test]
    fn migration_walk_does_not_pin_or_revisit_frozen_generations() {
        let dir = tempfile::tempdir().unwrap();
        let tree = SegTree::<TestKey, String, TextCodec>::open_with(
            dir.path(),
            meta(),
            &[],
            SegConfig {
                seal_max_keys: 10_000,
                max_frozen_generations: 8,
                ..SegConfig::test()
            },
            TextCodec,
            OpenOptions {
                worker: false,
                ..OpenOptions::production()
            },
        )
        .unwrap();
        for n in 0..1000 {
            tree.put(&ordered_key(n), &format!("old{n}")).unwrap();
        }
        let retired = Arc::downgrade(&tree.core.view().active);
        let mut seen = std::collections::BTreeSet::new();
        tree.walk_rows(true, &mut |row| {
            let (key, value) = row.unwrap();
            assert!(value.starts_with("old"));
            assert!(seen.insert(key));
            tree.core.put(&key, b"rewritten").unwrap();
            if seen.len() % 200 == 0 {
                tree.seal().unwrap();
                tree.core.seal_oldest().unwrap();
                assert!(
                    retired.upgrade().is_none(),
                    "callback must not pin the retired index"
                );
            }
            ControlFlow::Continue(())
        });
        assert_eq!(seen.len(), 1000);
        let mut visited = 0;
        tree.walk_rows(true, &mut |_| {
            visited += 1;
            ControlFlow::Break(())
        });
        assert_eq!(visited, 1, "full scans preserve early-stop callbacks");
    }
}