acyclic-fs 0.1.5

Rust SDK for versioned workspaces and embedded native mounts
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
//! Shared immutable path-copy mechanics for authenticated B+tree formats.

use super::allocation::{AllocationError, AllocationLedger, VisitedObjectSet};
use super::codec::DecodedPageShape;
use super::persistent_io::{self, OwnedPage};
use super::{CanonicalDecodeError, DecodeLimits};
use crate::cancellation::CancellationToken;
use crate::performance::{OperationFailure, WorkBudget, WorkCounters, WorkError};
use crate::storage::{
    OBJECT_DIGEST_ENVELOPE_BYTES, ObjectId, ObjectKind, ObjectStoreError, object_digest,
};
use bytes::Bytes;
use std::marker::PhantomData;
use std::ops::Range;
use thiserror::Error;

pub(crate) trait Format: Send + Sync + 'static {
    type Key: Clone + Eq + Ord + Send + Sync + 'static;
    type Value: Clone + Eq + Send + Sync + 'static;

    fn kind() -> ObjectKind;
    fn key(value: &Self::Value) -> &Self::Key;
    fn decode(bytes: &[u8], limits: DecodeLimits) -> Result<Page<Self>, CanonicalDecodeError>
    where
        Self: Sized;
    fn decode_shape(
        bytes: &[u8],
        limits: DecodeLimits,
    ) -> Result<DecodedPageShape, CanonicalDecodeError>;
    fn encode(
        page: &PageRef<'_, Self>,
        maximum_items: u32,
    ) -> Result<Vec<u8>, CanonicalDecodeError>
    where
        Self: Sized;
    fn page_encoded_length(
        page: &PageRef<'_, Self>,
        maximum_items: u32,
    ) -> Result<usize, CanonicalDecodeError>
    where
        Self: Sized;
    fn leaf_item_encoded_length(value: &Self::Value) -> Result<usize, CanonicalDecodeError>;
    fn internal_item_encoded_length(key: &Self::Key) -> Result<usize, CanonicalDecodeError>;
    fn key_nested_bytes(key: &Self::Key) -> u64;
    fn value_nested_bytes(value: &Self::Value) -> u64;
    fn try_clone_key(
        key: &Self::Key,
        maximum_bytes: u32,
    ) -> Result<Self::Key, CanonicalDecodeError>;
    fn try_clone_value(
        value: &Self::Value,
        maximum_bytes: u32,
    ) -> Result<Self::Value, CanonicalDecodeError>;
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Child<K> {
    pub(crate) first: K,
    pub(crate) page: ObjectId,
}

#[derive(Debug, Eq, PartialEq)]
pub(crate) enum Page<F: Format> {
    Leaf(Vec<F::Value>),
    Internal(Vec<Child<F::Key>>),
}

impl<F: Format> Clone for Page<F> {
    fn clone(&self) -> Self {
        match self {
            Self::Leaf(values) => Self::Leaf(values.clone()),
            Self::Internal(children) => Self::Internal(children.clone()),
        }
    }
}

pub(crate) enum PageRef<'a, F: Format> {
    Leaf(&'a [F::Value]),
    Internal(&'a [Child<F::Key>]),
}

pub(crate) trait Mutation<F: Format>: Clone {
    type Error: std::error::Error;

    fn key(&self) -> &F::Key;
    fn changes_cardinality(&self) -> bool;
    fn apply_current(&self, current: &mut Option<F::Value>) -> Result<(), Self::Error>;
}

#[derive(Clone)]
struct IndexedMutation<M> {
    ordinal: usize,
    mutation: M,
}

impl<F, M> Mutation<F> for IndexedMutation<M>
where
    F: Format,
    M: Mutation<F>,
{
    type Error = M::Error;

    fn key(&self) -> &F::Key {
        self.mutation.key()
    }

    fn changes_cardinality(&self) -> bool {
        self.mutation.changes_cardinality()
    }

    fn apply_current(&self, current: &mut Option<F::Value>) -> Result<(), Self::Error> {
        self.mutation.apply_current(current)
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Receipt {
    pub(crate) root: ObjectId,
    pub(crate) work: WorkCounters,
}

#[derive(Debug, Error)]
pub(crate) enum Error<E: std::error::Error> {
    #[error("persistent B+tree mutation batch is empty")]
    Empty,
    #[error("persistent B+tree mutation count exceeds its bound")]
    TooManyMutations,
    #[error("persistent B+tree root has the wrong object kind")]
    WrongRootKind,
    #[error("persistent B+tree limits are invalid")]
    InvalidLimits,
    #[error("one persistent B+tree item cannot fit in an admitted page")]
    PageItemTooLarge,
    #[error("persistent B+tree exceeds its height bound")]
    HeightExceeded,
    #[error("persistent B+tree contains a cycle or alias")]
    CycleOrAlias,
    #[error("persistent B+tree child bounds mismatch")]
    ChildBoundsMismatch,
    #[error("persistent B+tree mutation violated its physical-plan contract")]
    MutationContract,
    #[error("persistent B+tree scratch allocation failed")]
    AllocationFailed,
    #[error(transparent)]
    Allocation(#[from] AllocationError),
    #[error("persistent B+tree semantic mutation failed: {0}")]
    Semantic(E),
    #[error(transparent)]
    Storage(#[from] ObjectStoreError),
    #[error(transparent)]
    Decode(#[from] CanonicalDecodeError),
    #[error(transparent)]
    Work(#[from] WorkError),
}

type Summary<K> = Child<K>;

struct OwnedValues<F: Format> {
    values: Vec<F::Value>,
    logical_bytes: u64,
}

struct NodeRequest<K> {
    page: ObjectId,
    lower: Option<K>,
    upper: Option<K>,
    mutations: Range<usize>,
    height: u16,
}

struct InternalFrame<F: Format> {
    original: ObjectId,
    children: Vec<Child<F::Key>>,
    inherited_upper: Option<F::Key>,
    next_child: usize,
    mutation_cursor: usize,
    mutation_end: usize,
    height: u16,
    rewritten: Vec<Summary<F::Key>>,
    logical_bytes: u64,
}

enum EnteredNode<F: Format> {
    Complete(Vec<Summary<F::Key>>),
    Internal(InternalFrame<F>),
}

struct Context<'a, S, F, M>
where
    F: Format,
    M: Mutation<F>,
{
    store: &'a S,
    limits: DecodeLimits,
    budget: WorkBudget,
    work: WorkCounters,
    allocations: AllocationLedger,
    visited: VisitedObjectSet,
    maximum_seen_height: u16,
    cancellation: &'a CancellationToken,
    marker: PhantomData<(F, M)>,
}

pub(crate) fn apply<S, F, M>(
    store: &S,
    root: ObjectId,
    mutations: Vec<M>,
    maximum_mutations: u32,
    limits: DecodeLimits,
    budget: WorkBudget,
) -> Result<Receipt, OperationFailure<Error<M::Error>>>
where
    S: crate::ImmediateObjectStore,
    F: Format,
    M: Mutation<F>,
{
    let cancellation = CancellationToken::new();
    crate::async_storage::poll_immediate(apply_async::<S, F, M>(
        store,
        root,
        mutations,
        maximum_mutations,
        limits,
        budget,
        &cancellation,
    ))
}

pub(crate) async fn apply_async<S, F, M>(
    store: &S,
    root: ObjectId,
    mutations: Vec<M>,
    maximum_mutations: u32,
    limits: DecodeLimits,
    budget: WorkBudget,
    cancellation: &CancellationToken,
) -> Result<Receipt, OperationFailure<Error<M::Error>>>
where
    S: crate::AsyncObjectStore,
    F: Format,
    M: Mutation<F>,
{
    validate::<F, M>(root, &mutations, maximum_mutations, limits)?;
    let mut allocations = AllocationLedger::default();
    let mut initial_work = WorkCounters::default();
    let ordered_allocation = allocations
        .claim_elements::<IndexedMutation<M>>(mutations.len(), &mut initial_work, budget)
        .map_err(|error| OperationFailure::new(Error::Allocation(error), initial_work))?;
    let mut ordered = Vec::new();
    if ordered.try_reserve_exact(mutations.len()).is_err() {
        return Err(OperationFailure::new(Error::AllocationFailed, initial_work));
    }
    ordered.extend(
        mutations
            .into_iter()
            .enumerate()
            .map(|(ordinal, mutation)| IndexedMutation { ordinal, mutation }),
    );
    sort_indexed::<F, M>(&mut ordered, &mut initial_work, budget)
        .map_err(|error| OperationFailure::new(Error::Work(error), initial_work))?;
    let maximum_visited = ordered
        .len()
        .checked_mul(usize::from(limits.maximum_page_height))
        .and_then(|value| value.checked_add(1))
        .ok_or_else(|| OperationFailure::before_work(Error::InvalidLimits))?
        .min(
            usize::try_from(limits.maximum_visited_pages)
                .map_err(|_| OperationFailure::before_work(Error::InvalidLimits))?,
        );
    let visited =
        VisitedObjectSet::new(maximum_visited, &mut allocations, &mut initial_work, budget)
            .map_err(|error| OperationFailure::new(Error::Allocation(error), initial_work))?;
    let mut context = Context::<S, F, IndexedMutation<M>> {
        store,
        limits,
        budget,
        work: initial_work,
        allocations,
        visited,
        maximum_seen_height: 0,
        cancellation,
        marker: PhantomData,
    };
    let summaries = context
        .rewrite(root, &ordered)
        .await
        .map_err(|error| OperationFailure::new(error, context.work))?;
    let new_root = context
        .finish_root(summaries)
        .await
        .map_err(|error| OperationFailure::new(error, context.work))?;
    context
        .visited
        .release(&mut context.allocations)
        .map_err(|error| OperationFailure::new(Error::Allocation(error), context.work))?;
    context
        .allocations
        .release(ordered_allocation)
        .map_err(|error| OperationFailure::new(Error::Allocation(error), context.work))?;
    Ok(Receipt {
        root: new_root,
        work: context.work,
    })
}

fn sort_indexed<F, M>(
    mutations: &mut [IndexedMutation<M>],
    work: &mut WorkCounters,
    budget: WorkBudget,
) -> Result<(), WorkError>
where
    F: Format,
    M: Mutation<F>,
{
    let count = mutations.len();
    if count < 2 {
        return Ok(());
    }
    let scan_bound = crate::foundation::usize_to_u64(count - 1);
    work.checked_add(WorkCounters {
        items_examined: scan_bound,
        ..WorkCounters::default()
    })?
    .verify(budget)?;
    let mut scan_comparisons = 0_u64;
    let mut ordered = true;
    for adjacent in mutations.windows(2) {
        scan_comparisons = scan_comparisons.checked_add(1).ok_or(WorkError::Overflow)?;
        if let [left, right] = adjacent
            && indexed_order::<F, M>(left, right).is_gt()
        {
            ordered = false;
            break;
        }
    }
    *work = work.checked_add(WorkCounters {
        items_examined: scan_comparisons,
        ..WorkCounters::default()
    })?;
    if ordered {
        return Ok(());
    }

    let levels = usize::BITS - count.leading_zeros();
    let maximum_comparisons = u64::try_from(count)
        .ok()
        .and_then(|value| value.checked_mul(u64::from(levels)))
        .and_then(|value| value.checked_mul(3))
        .ok_or(WorkError::Overflow)?;
    work.checked_add(WorkCounters {
        items_examined: maximum_comparisons,
        ..WorkCounters::default()
    })?
    .verify(budget)?;

    let mut comparisons = 0_u64;
    for start in (0..count / 2).rev() {
        sift_down::<F, M>(mutations, start, count, &mut comparisons)?;
    }
    for end in (1..count).rev() {
        mutations.swap(0, end);
        sift_down::<F, M>(mutations, 0, end, &mut comparisons)?;
    }
    *work = work.checked_add(WorkCounters {
        items_examined: comparisons,
        ..WorkCounters::default()
    })?;
    Ok(())
}

fn sift_down<F, M>(
    mutations: &mut [IndexedMutation<M>],
    mut root: usize,
    end: usize,
    comparisons: &mut u64,
) -> Result<(), WorkError>
where
    F: Format,
    M: Mutation<F>,
{
    loop {
        let left = root.checked_mul(2).and_then(|value| value.checked_add(1));
        let Some(left) = left.filter(|left| *left < end) else {
            return Ok(());
        };
        let right = left + 1;
        let mut greater = left;
        // `left < end` was just established by the `filter` above, and callers
        // maintain `end <= mutations.len()` (it is either the original slice
        // length or a shrinking heap boundary passed in by `sort_indexed`), so
        // `left < mutations.len()`. `right` is only indexed inside the
        // `right < end` guard, so it too is `< mutations.len()`.
        #[allow(
            clippy::indexing_slicing,
            reason = "left < end and (guarded) right < end, with end <= mutations.len() maintained by callers"
        )]
        if right < end {
            *comparisons = comparisons.checked_add(1).ok_or(WorkError::Overflow)?;
            if indexed_order::<F, M>(&mutations[left], &mutations[right]).is_lt() {
                greater = right;
            }
        }
        *comparisons = comparisons.checked_add(1).ok_or(WorkError::Overflow)?;
        // `root` is either the initial caller-supplied index (`< end` by
        // construction in `sort_indexed`) or a previous `greater`, and
        // `greater` is one of `left`/`right`, both shown `< end <=
        // mutations.len()` above.
        #[allow(
            clippy::indexing_slicing,
            reason = "root and greater are both < end <= mutations.len(), established above and by sort_indexed's callers"
        )]
        if !indexed_order::<F, M>(&mutations[root], &mutations[greater]).is_lt() {
            return Ok(());
        }
        mutations.swap(root, greater);
        root = greater;
    }
}

fn indexed_order<F, M>(left: &IndexedMutation<M>, right: &IndexedMutation<M>) -> std::cmp::Ordering
where
    F: Format,
    M: Mutation<F>,
{
    left.mutation
        .key()
        .cmp(right.mutation.key())
        .then_with(|| left.ordinal.cmp(&right.ordinal))
}

fn validate<F, M>(
    root: ObjectId,
    mutations: &[M],
    maximum_mutations: u32,
    limits: DecodeLimits,
) -> Result<(), OperationFailure<Error<M::Error>>>
where
    F: Format,
    M: Mutation<F>,
{
    let error = if root.kind != F::kind() {
        Some(Error::WrongRootKind)
    } else if mutations.is_empty() {
        Some(Error::Empty)
    } else if maximum_mutations == 0
        || u32::try_from(mutations.len()).unwrap_or(u32::MAX) > maximum_mutations
    {
        Some(Error::TooManyMutations)
    } else if !limits.page_limits_valid(2) {
        Some(Error::InvalidLimits)
    } else {
        None
    };
    match error {
        Some(error) => Err(OperationFailure::before_work(error)),
        None => Ok(()),
    }
}

impl<S, F, M> Context<'_, S, F, M>
where
    S: crate::AsyncObjectStore,
    F: Format,
    M: Mutation<F>,
{
    async fn rewrite(
        &mut self,
        root: ObjectId,
        mutations: &[M],
    ) -> Result<Vec<Summary<F::Key>>, Error<M::Error>> {
        let mut stack = Vec::new();
        let mut request = NodeRequest {
            page: root,
            lower: None,
            upper: None,
            mutations: 0..mutations.len(),
            height: 1,
        };
        'traverse: loop {
            let entered = self.enter_node(request, mutations).await?;
            let mut result = match entered {
                EnteredNode::Complete(result) => result,
                EnteredNode::Internal(mut frame) => {
                    if let Some(next) = self.advance_frame(&mut frame, mutations)? {
                        stack.push(frame);
                        request = next;
                        continue;
                    }
                    self.finish_frame(frame).await?
                }
            };
            loop {
                let Some(mut frame) = stack.pop() else {
                    return Ok(result);
                };
                frame.rewritten.extend(result);
                if let Some(next) = self.advance_frame(&mut frame, mutations)? {
                    stack.push(frame);
                    request = next;
                    continue 'traverse;
                }
                result = self.finish_frame(frame).await?;
            }
        }
    }

    async fn enter_node(
        &mut self,
        request: NodeRequest<F::Key>,
        mutations: &[M],
    ) -> Result<EnteredNode<F>, Error<M::Error>> {
        if request.height > self.limits.maximum_page_height {
            return Err(Error::HeightExceeded);
        }
        self.maximum_seen_height = self.maximum_seen_height.max(request.height);
        let visited = self.visited.insert(
            request.page,
            &mut self.allocations,
            &mut self.work,
            self.budget,
        )?;
        if !visited.inserted {
            return Err(Error::CycleOrAlias);
        }
        let decoded = self.read_page(request.page).await?;
        let (page, decoded_bytes) = decoded
            .into_owned(self.budget, &mut self.allocations, &mut self.work)
            .map_err(map_io)?;
        match page {
            Page::Leaf(entries) => {
                validate_leaf::<F, M>(&entries, request.lower.as_ref(), request.upper.as_ref())?;
                // `request.mutations` is a `Range<usize>` into this same
                // `mutations` slice, threaded unchanged through the whole
                // traversal (`rewrite` -> `enter_node`/`advance_frame`).
                // The root request starts at `0..mutations.len()` (see
                // `rewrite`), and every subsequent request is built in
                // `advance_frame` as `selected_start..frame.mutation_cursor`,
                // where `mutation_cursor` only ever advances while `<
                // frame.mutation_end`, itself inherited from a prior
                // request's (already valid) `.mutations.end`. So by
                // induction every `request.mutations` satisfies `start <=
                // end <= mutations.len()`.
                #[allow(
                    clippy::indexing_slicing,
                    reason = "request.mutations is bounded by mutations.len() by induction from rewrite's root request and advance_frame's mutation_cursor bookkeeping"
                )]
                let result = self
                    .rewrite_leaf(request.page, entries, &mutations[request.mutations])
                    .await;
                self.allocations.release(decoded_bytes)?;
                Ok(EnteredNode::Complete(result?))
            }
            Page::Internal(children) => {
                validate_children::<F, M>(
                    &children,
                    request.lower.as_ref(),
                    request.upper.as_ref(),
                )?;
                Ok(EnteredNode::Internal(InternalFrame {
                    original: request.page,
                    children,
                    inherited_upper: request.upper,
                    next_child: 0,
                    mutation_cursor: request.mutations.start,
                    mutation_end: request.mutations.end,
                    height: request.height,
                    rewritten: Vec::new(),
                    logical_bytes: decoded_bytes,
                }))
            }
        }
    }

    fn advance_frame(
        &mut self,
        frame: &mut InternalFrame<F>,
        mutations: &[M],
    ) -> Result<Option<NodeRequest<F::Key>>, Error<M::Error>> {
        while frame.next_child < frame.children.len() {
            let index = frame.next_child;
            frame.next_child += 1;
            // `index` was captured as `frame.next_child` before the
            // increment, while the loop guard above already established
            // `frame.next_child < frame.children.len()`.
            #[allow(
                clippy::indexing_slicing,
                reason = "index captured from frame.next_child while the loop guard above holds next_child < frame.children.len()"
            )]
            let child = &frame.children[index];
            let child_upper = frame
                .children
                .get(index + 1)
                .map(|next| next.first.clone())
                .or_else(|| frame.inherited_upper.clone());
            let selected_start = frame.mutation_cursor;
            if let Some(next) = frame.children.get(index + 1) {
                while frame.mutation_cursor < frame.mutation_end {
                    self.charge_items(1)?;
                    // The loop guard establishes `frame.mutation_cursor <
                    // frame.mutation_end`, and `frame.mutation_end` is
                    // inherited from a prior `NodeRequest.mutations.end`,
                    // which is bounded by `mutations.len()` (see the
                    // invariant documented at the `enter_node` leaf-rewrite
                    // call site).
                    #[allow(
                        clippy::indexing_slicing,
                        reason = "frame.mutation_cursor < frame.mutation_end <= mutations.len(), per the loop guard and the request.mutations invariant"
                    )]
                    if mutations[frame.mutation_cursor].key() >= &next.first {
                        break;
                    }
                    frame.mutation_cursor += 1;
                }
            } else {
                frame.mutation_cursor = frame.mutation_end;
            }
            self.charge_items(1)?;
            if selected_start == frame.mutation_cursor {
                frame.rewritten.push(Summary {
                    first: child.first.clone(),
                    page: child.page,
                });
                continue;
            }
            return Ok(Some(NodeRequest {
                page: child.page,
                lower: Some(child.first.clone()),
                upper: child_upper,
                mutations: selected_start..frame.mutation_cursor,
                height: frame.height.checked_add(1).ok_or(Error::HeightExceeded)?,
            }));
        }
        Ok(None)
    }

    async fn finish_frame(
        &mut self,
        frame: InternalFrame<F>,
    ) -> Result<Vec<Summary<F::Key>>, Error<M::Error>> {
        // This branch is only reached when `frame.rewritten` is non-empty
        // (the `is_empty()` branch above already handled that case), and
        // `unchanged` requires `rewritten.len() == children.len()`, so
        // `frame.children` is non-empty here too.
        #[allow(
            clippy::indexing_slicing,
            reason = "unchanged() requires children.len() == rewritten.len(), and rewritten is non-empty in this branch"
        )]
        let result = if frame.rewritten.is_empty() {
            Ok(Vec::new())
        } else if unchanged(&frame.rewritten, &frame.children) {
            Ok(vec![Summary {
                first: frame.children[0].first.clone(),
                page: frame.original,
            }])
        } else if frame.height == 1 && frame.rewritten.len() == 1 {
            Ok(frame.rewritten)
        } else {
            self.write_internal_chunks(&frame.rewritten).await
        };
        self.allocations.release(frame.logical_bytes)?;
        result
    }

    async fn rewrite_leaf(
        &mut self,
        original: ObjectId,
        mut entries: Vec<F::Value>,
        mutations: &[M],
    ) -> Result<Vec<Summary<F::Key>>, Error<M::Error>> {
        let mut structural_allocation = 0_u64;
        let changed = if mutations
            .iter()
            .all(|mutation| !mutation.changes_cardinality())
        {
            self.apply_point_mutations(&mut entries, mutations)?
        } else {
            let original = entries;
            let rewritten = self.apply_structural_mutations(&original, mutations)?;
            entries = rewritten.values;
            structural_allocation = rewritten.logical_bytes;
            entries != original
        };
        // Guarded by the `entries.is_empty()` branch above: this branch is
        // only reached when `entries` is non-empty.
        #[allow(
            clippy::indexing_slicing,
            reason = "guarded by the preceding entries.is_empty() branch of this same if-chain"
        )]
        let result = if entries.is_empty() {
            Ok(Vec::new())
        } else if !changed {
            Ok(vec![Summary {
                first: F::key(&entries[0]).clone(),
                page: original,
            }])
        } else {
            self.write_leaf_chunks(&entries).await
        };
        self.allocations.release(structural_allocation)?;
        result
    }

    fn apply_point_mutations(
        &mut self,
        entries: &mut [F::Value],
        mutations: &[M],
    ) -> Result<bool, Error<M::Error>> {
        let mut changed = false;
        for mutation in mutations {
            let (found, comparisons) = search::<F>(entries, mutation.key());
            self.charge_items(comparisons)?;
            let index = found.ok();
            // `search` only returns `Ok(middle)` when `entries[middle]`
            // compared equal to the key, where `middle` was proven `<
            // entries.len()` by that function's binary-search invariant.
            // `entries` is not resliced or shortened between here and the
            // indexing below.
            #[allow(
                clippy::indexing_slicing,
                reason = "index came from search()'s Ok(middle), which is always < entries.len() by its binary search invariant"
            )]
            let prior = index.map(|index| entries[index].clone());
            let mut current = prior.clone();
            mutation
                .apply_current(&mut current)
                .map_err(Error::Semantic)?;
            if prior.is_some() != current.is_some() {
                return Err(Error::MutationContract);
            }
            #[allow(
                clippy::indexing_slicing,
                reason = "same search()-derived index as above, still < entries.len()"
            )]
            if let (Some(index), Some(replacement)) = (index, current) {
                changed |= prior.as_ref() != Some(&replacement);
                entries[index] = replacement;
            }
        }
        Ok(changed)
    }

    fn apply_structural_mutations(
        &mut self,
        entries: &[F::Value],
        mutations: &[M],
    ) -> Result<OwnedValues<F>, Error<M::Error>> {
        let capacity = entries
            .len()
            .checked_add(mutations.len())
            .ok_or(Error::AllocationFailed)?;
        let logical_bytes =
            self.allocations
                .claim_elements::<F::Value>(capacity, &mut self.work, self.budget)?;
        let mut output = Vec::new();
        if output.try_reserve_exact(capacity).is_err() {
            self.allocations.release(logical_bytes)?;
            return Err(Error::AllocationFailed);
        }

        let mut entry_index = 0_usize;
        let mut mutation_index = 0_usize;
        while entry_index < entries.len() || mutation_index < mutations.len() {
            // The outer while guard failed on the `mutation_index ==
            // mutations.len()` disjunct being false only if this if is not
            // taken; when it IS taken, the outer guard was satisfied via its
            // other disjunct, `entry_index < entries.len()`.
            #[allow(
                clippy::indexing_slicing,
                reason = "when mutation_index == mutations.len(), the enclosing while guard's other disjunct entry_index < entries.len() must hold"
            )]
            if mutation_index == mutations.len() {
                self.charge_items(1)?;
                output.push(entries[entry_index].clone());
                entry_index += 1;
                continue;
            }
            // Falling through the `if` above means `mutation_index !=
            // mutations.len()`; `mutation_index` only ever increases and is
            // never set past `mutations.len()`, so it is `< mutations.len()`
            // here.
            #[allow(
                clippy::indexing_slicing,
                reason = "mutation_index != mutations.len() here (the branch above already handled equality), and it never exceeds mutations.len()"
            )]
            let mutation_key = mutations[mutation_index].key();
            let ordering = entries
                .get(entry_index)
                .map(|entry| F::key(entry).cmp(mutation_key));
            self.charge_items(u64::from(ordering.is_some()))?;
            // `ordering` is `Some(_)` only when `entries.get(entry_index)`
            // returned `Some`, i.e. `entry_index < entries.len()`.
            #[allow(
                clippy::indexing_slicing,
                reason = "matches!(ordering, Some(Less)) implies entries.get(entry_index) was Some, i.e. entry_index < entries.len()"
            )]
            if matches!(ordering, Some(std::cmp::Ordering::Less)) {
                output.push(entries[entry_index].clone());
                entry_index += 1;
                continue;
            }
            #[allow(
                clippy::indexing_slicing,
                reason = "matches!(ordering, Some(Equal)) implies entries.get(entry_index) was Some, i.e. entry_index < entries.len()"
            )]
            let mut current = if matches!(ordering, Some(std::cmp::Ordering::Equal)) {
                let value = entries[entry_index].clone();
                entry_index += 1;
                Some(value)
            } else {
                None
            };
            let key = mutation_key.clone();
            // `mutation_index < mutations.len()` is checked immediately to
            // the left of `&&` in this same condition (guaranteed
            // short-circuit evaluation order), and the loop body only runs
            // after that same condition succeeded, so the indexing in the
            // body is covered by the same check.
            #[allow(
                clippy::indexing_slicing,
                reason = "mutation_index < mutations.len() is checked by the left operand of && in this same while condition (short-circuit evaluation)"
            )]
            while mutation_index < mutations.len() && mutations[mutation_index].key() == &key {
                self.charge_items(1)?;
                mutations[mutation_index]
                    .apply_current(&mut current)
                    .map_err(Error::Semantic)?;
                mutation_index += 1;
            }
            if let Some(value) = current {
                output.push(value);
            }
        }
        Ok(OwnedValues {
            values: output,
            logical_bytes,
        })
    }

    fn charge_items(&mut self, count: u64) -> Result<(), Error<M::Error>> {
        let prospective = self.work.checked_add(WorkCounters {
            items_examined: count,
            ..WorkCounters::default()
        })?;
        prospective.verify(self.budget)?;
        self.work = prospective;
        Ok(())
    }

    async fn write_leaf_chunks(
        &mut self,
        entries: &[F::Value],
    ) -> Result<Vec<Summary<F::Key>>, Error<M::Error>> {
        let mut result = Vec::new();
        let mut start = 0_usize;
        while start < entries.len() {
            let (end, examined) =
                page_chunk_end(entries, start, self.limits, F::leaf_item_encoded_length)?;
            self.charge_items(examined)?;
            // `page_chunk_end` only returns `Ok((end, _))` with `start < end
            // <= entries.len()` (it errors with `PageItemTooLarge` instead
            // of returning `end == start`), so this slice is in bounds and
            // non-empty.
            #[allow(
                clippy::indexing_slicing,
                reason = "page_chunk_end guarantees start < end <= entries.len() on its Ok path"
            )]
            let chunk = &entries[start..end];
            #[allow(
                clippy::indexing_slicing,
                reason = "chunk is non-empty per page_chunk_end's Ok-path guarantee (start < end)"
            )]
            result.push(Summary {
                first: F::key(&chunk[0]).clone(),
                page: self.write_page(&PageRef::<F>::Leaf(chunk)).await?,
            });
            start = end;
        }
        Ok(result)
    }

    async fn write_internal_chunks(
        &mut self,
        children: &[Summary<F::Key>],
    ) -> Result<Vec<Summary<F::Key>>, Error<M::Error>> {
        let mut cursor = 0_usize;
        let mut chunks = 0_usize;
        while cursor < children.len() {
            let (end, examined) = page_chunk_end(children, cursor, self.limits, |child| {
                F::internal_item_encoded_length(&child.first)
            })?;
            self.charge_items(examined)?;
            chunks += 1;
            cursor = end;
        }
        if children.len() > 1 && chunks >= children.len() {
            return Err(Error::PageItemTooLarge);
        }
        let mut result = Vec::new();
        let mut start = 0_usize;
        while start < children.len() {
            let (end, examined) = page_chunk_end(children, start, self.limits, |child| {
                F::internal_item_encoded_length(&child.first)
            })?;
            self.charge_items(examined)?;
            // Same page_chunk_end guarantee as in write_leaf_chunks: `start
            // < end <= children.len()` on the Ok path.
            #[allow(
                clippy::indexing_slicing,
                reason = "page_chunk_end guarantees start < end <= children.len() on its Ok path"
            )]
            let chunk = &children[start..end];
            #[allow(
                clippy::indexing_slicing,
                reason = "chunk is non-empty per page_chunk_end's Ok-path guarantee (start < end)"
            )]
            result.push(Summary {
                first: chunk[0].first.clone(),
                page: self.write_page(&PageRef::<F>::Internal(chunk)).await?,
            });
            start = end;
        }
        Ok(result)
    }

    async fn finish_root(
        &mut self,
        mut summaries: Vec<Summary<F::Key>>,
    ) -> Result<ObjectId, Error<M::Error>> {
        if summaries.is_empty() {
            return self.write_page(&PageRef::<F>::Leaf(&[])).await;
        }
        let mut height = self.maximum_seen_height;
        while summaries.len() > 1 {
            height = height.checked_add(1).ok_or(Error::HeightExceeded)?;
            if height > self.limits.maximum_page_height {
                return Err(Error::HeightExceeded);
            }
            summaries = self.write_internal_chunks(&summaries).await?;
        }
        // The early `summaries.is_empty()` return above rules out an
        // initial empty vector, and each loop iteration calls
        // `write_internal_chunks` only while `summaries.len() > 1`
        // (i.e. non-empty input), which itself never returns an empty
        // result for non-empty input (its two internal chunking loops each
        // make at least one `page_chunk_end`-bounded step and push at
        // least one summary). So the loop can only terminate with
        // `summaries.len() == 1`.
        #[allow(
            clippy::indexing_slicing,
            reason = "the loop above only exits with summaries.len() == 1: write_internal_chunks never returns empty for non-empty input, and the pre-loop check ruled out an initially empty vector"
        )]
        Ok(summaries[0].page)
    }

    async fn read_page(&mut self, page: ObjectId) -> Result<OwnedPage<F>, Error<M::Error>> {
        persistent_io::read_page_mutable::<S, F>(
            self.store,
            page,
            self.limits,
            self.budget,
            self.cancellation,
            &mut self.allocations,
            &mut self.work,
        )
        .await
        .map_err(map_io)
    }

    async fn write_page(&mut self, page: &PageRef<'_, F>) -> Result<ObjectId, Error<M::Error>> {
        let encoded_length = F::page_encoded_length(page, self.limits.maximum_page_items)?;
        let encoded_bytes = crate::foundation::usize_to_u64(encoded_length);
        if encoded_bytes > self.limits.maximum_page_object_bytes() {
            return Err(Error::PageItemTooLarge);
        }
        let allocation =
            self.allocations
                .claim_elements::<u8>(encoded_length, &mut self.work, self.budget)?;
        let encoded_work = self.work.checked_add(WorkCounters {
            bytes_encoded: encoded_bytes,
            ..WorkCounters::default()
        })?;
        if let Err(error) = encoded_work.verify(self.budget) {
            self.allocations.release(allocation)?;
            return Err(Error::Work(error));
        }
        let encoded = F::encode(page, self.limits.maximum_page_items)?;
        self.work = encoded_work;
        if encoded.len() != encoded_length {
            self.allocations.release(allocation)?;
            return Err(Error::MutationContract);
        }
        let hashed_work = self.work.checked_add(WorkCounters {
            bytes_hashed: encoded_bytes
                .checked_add(OBJECT_DIGEST_ENVELOPE_BYTES)
                .ok_or(WorkError::Overflow)?,
            ..WorkCounters::default()
        })?;
        if let Err(error) = hashed_work.verify(self.budget) {
            self.allocations.release(allocation)?;
            return Err(Error::Work(error));
        }
        let object = ObjectId {
            kind: F::kind(),
            digest: object_digest(F::kind(), &encoded),
        };
        self.work = hashed_work;
        let prospective = self.work.checked_add(WorkCounters {
            page_writes: 1,
            ..WorkCounters::default()
        })?;
        let remaining = prospective.remaining(self.budget)?;
        let receipt = match crate::AsyncObjectStore::put(
            self.store,
            object,
            Bytes::from(encoded),
            remaining,
            self.cancellation,
        )
        .await
        {
            Ok(receipt) => receipt,
            Err(failure) => {
                self.allocations.release(allocation)?;
                return match prospective.checked_add(*failure.work) {
                    Ok(spent) => {
                        self.work = spent;
                        Err(Error::Storage(failure.error))
                    }
                    Err(error) => {
                        self.work = prospective;
                        Err(Error::Work(error))
                    }
                };
            }
        };
        self.work = prospective.checked_add(receipt.work)?;
        self.work.verify(self.budget)?;
        self.allocations.release(allocation)?;
        Ok(object)
    }
}

fn map_io<E: std::error::Error>(error: persistent_io::Error) -> Error<E> {
    match error {
        persistent_io::Error::AllocationFailed => Error::AllocationFailed,
        persistent_io::Error::Allocation(error) => Error::Allocation(error),
        persistent_io::Error::Storage(error) => Error::Storage(error),
        persistent_io::Error::Decode(error) => Error::Decode(error),
        persistent_io::Error::Work(error) => Error::Work(error),
    }
}

fn page_chunk_end<T, E: std::error::Error>(
    items: &[T],
    start: usize,
    limits: DecodeLimits,
    encoded_length: impl Fn(&T) -> Result<usize, CanonicalDecodeError>,
) -> Result<(usize, u64), Error<E>> {
    const PAGE_HEADER_BYTES: usize = 8 + 2 + 1 + 4;
    let maximum_items =
        usize::try_from(limits.maximum_page_items).map_err(|_| Error::InvalidLimits)?;
    let maximum_bytes =
        usize::try_from(limits.maximum_page_bytes).map_err(|_| Error::InvalidLimits)?;
    let mut end = start;
    let mut bytes = PAGE_HEADER_BYTES;
    let mut examined = 0_u64;
    while end < items.len() && end - start < maximum_items {
        examined = examined.saturating_add(1);
        // Guarded by the loop condition's `end < items.len()` conjunct.
        #[allow(
            clippy::indexing_slicing,
            reason = "the enclosing while condition already established end < items.len()"
        )]
        let item_bytes = encoded_length(&items[end])?;
        let next = bytes
            .checked_add(item_bytes)
            .ok_or(Error::PageItemTooLarge)?;
        if next > maximum_bytes {
            if end == start {
                return Err(Error::PageItemTooLarge);
            }
            break;
        }
        bytes = next;
        end += 1;
    }
    if end == start {
        return Err(Error::PageItemTooLarge);
    }
    Ok((end, examined))
}

fn search<F: Format>(entries: &[F::Value], key: &F::Key) -> (Result<usize, usize>, u64) {
    let mut left = 0;
    let mut right = entries.len();
    let mut comparisons = 0_u64;
    while left < right {
        comparisons = comparisons.saturating_add(1);
        let middle = left + (right - left) / 2;
        // Standard binary search invariant: the loop guard `left < right`
        // holds here, and `right <= entries.len()` is established at
        // initialization and only ever shrinks, so `middle` (strictly
        // between `left` and `right`) is always `< entries.len()`.
        #[allow(
            clippy::indexing_slicing,
            reason = "binary search invariant: left < middle_bound <= right <= entries.len()"
        )]
        match F::key(&entries[middle]).cmp(key) {
            std::cmp::Ordering::Less => left = middle + 1,
            std::cmp::Ordering::Greater => right = middle,
            std::cmp::Ordering::Equal => return (Ok(middle), comparisons),
        }
    }
    (Err(left), comparisons)
}

fn unchanged<K: Eq>(rewritten: &[Summary<K>], children: &[Child<K>]) -> bool {
    rewritten.len() == children.len()
        && rewritten
            .iter()
            .zip(children)
            .all(|(left, right)| left.first == right.first && left.page == right.page)
}

fn validate_leaf<F, M>(
    entries: &[F::Value],
    lower: Option<&F::Key>,
    upper: Option<&F::Key>,
) -> Result<(), Error<M::Error>>
where
    F: Format,
    M: Mutation<F>,
{
    if lower.is_some() && entries.first().map(F::key) != lower {
        return Err(Error::ChildBoundsMismatch);
    }
    if let Some(upper) = upper
        && entries.last().is_some_and(|entry| F::key(entry) >= upper)
    {
        return Err(Error::ChildBoundsMismatch);
    }
    Ok(())
}

fn validate_children<F, M>(
    children: &[Child<F::Key>],
    lower: Option<&F::Key>,
    upper: Option<&F::Key>,
) -> Result<(), Error<M::Error>>
where
    F: Format,
    M: Mutation<F>,
{
    if lower.is_some() && children.first().map(|child| &child.first) != lower {
        return Err(Error::ChildBoundsMismatch);
    }
    if let Some(upper) = upper
        && children.last().is_some_and(|child| &child.first >= upper)
    {
        return Err(Error::ChildBoundsMismatch);
    }
    Ok(())
}

#[cfg(test)]
#[path = "tests/persistent_btree.rs"]
mod tests;