cnidarium/
future.rs

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
//! Concrete futures types used by the storage crate.

use anyhow::Result;
use futures::{
    future::{Either, Ready},
    stream::Peekable,
    Stream,
};
use parking_lot::RwLock;
use pin_project::pin_project;
use smallvec::SmallVec;
use std::{
    future::Future,
    ops::Bound,
    pin::Pin,
    sync::Arc,
    task::{ready, Context, Poll},
};

use crate::Cache;

/// Future representing a read from a state snapshot.
#[pin_project]
pub struct SnapshotFuture(#[pin] pub(crate) tokio::task::JoinHandle<Result<Option<Vec<u8>>>>);

impl Future for SnapshotFuture {
    type Output = Result<Option<Vec<u8>>>;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        match this.0.poll(cx) {
            Poll::Ready(result) => {
                Poll::Ready(result.expect("unrecoverable join error from tokio task"))
            }
            Poll::Pending => Poll::Pending,
        }
    }
}

/// Future representing a read from an in-memory cache over an underlying state.
#[pin_project]
pub struct CacheFuture<F> {
    #[pin]
    inner: Either<Ready<Result<Option<Vec<u8>>>>, F>,
}

impl<F> CacheFuture<F> {
    pub(crate) fn hit(value: Option<Vec<u8>>) -> Self {
        Self {
            inner: Either::Left(futures::future::ready(Ok(value))),
        }
    }

    pub(crate) fn miss(underlying: F) -> Self {
        Self {
            inner: Either::Right(underlying),
        }
    }
}

impl<F> Future for CacheFuture<F>
where
    F: Future<Output = Result<Option<Vec<u8>>>>,
{
    type Output = Result<Option<Vec<u8>>>;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        this.inner.poll(cx)
    }
}

#[pin_project]
pub struct StateDeltaNonconsensusPrefixRawStream<St>
where
    St: Stream<Item = Result<(Vec<u8>, Vec<u8>)>>,
{
    #[pin]
    pub(crate) underlying: Peekable<St>,
    pub(crate) layers: Vec<Arc<RwLock<Option<Cache>>>>,
    pub(crate) leaf_cache: Arc<RwLock<Option<Cache>>>,
    pub(crate) last_key: Option<Vec<u8>>,
    pub(crate) prefix: Vec<u8>,
}

impl<St> Stream for StateDeltaNonconsensusPrefixRawStream<St>
where
    St: Stream<Item = Result<(Vec<u8>, Vec<u8>)>>,
{
    type Item = Result<(Vec<u8>, Vec<u8>)>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // This implementation interleaves items from the underlying stream with
        // items in cache layers.  To do this, it tracks the last key it
        // returned, then, for each item in the underlying stream, searches for
        // cached keys that lie between the last-returned key and the item's key,
        // checking whether the cached key represents a deletion requiring further
        // scanning.  This process is illustrated as follows:
        //
        //         ◇ skip                 ◇ skip           ▲ yield          ▲ yield           ▲ yield
        //         │                      │                │                │                 │
        //         ░ pick ──────────────▶ ░ pick ────────▶ █ pick ────────▶ █ pick ─────────▶ █ pick
        //         ▲                      ▲                ▲                ▲                 ▲
        //      ▲  │                 ▲    │          ▲     │         ▲      │        ▲        │
        // write│  │                 │    │          │     │         │      │        │        │
        // layer│  │   █             │    │ █        │     │█        │      █        │      █ │
        //      │  │ ░               │    ░          │    ░│         │    ░          │    ░   │
        //      │  ░                 │  ░            │  ░  │         │  ░            │  ░     │
        //      │    █               │    █          │    █│         │    █          │    █   │
        //      │  █     █           │  █     █      │  █  │  █      │  █     █      │  █     █
        //      │     █              │     █         │     █         │     █         │     █
        //     ─┼(─────]────keys─▶  ─┼──(───]────▶  ─┼────(─]────▶  ─┼─────(]────▶  ─┼──────(──]─▶
        //      │   ▲  █  █          │      █  █     │      █  █     │      █  █     │      █  █
        //          │
        //          │search range of key-value pairs in cache layers that could
        //          │affect whether to yield the next item in the underlying stream

        // Optimization: ensure we have a peekable item in the underlying stream before continuing.
        let mut this = self.project();
        ready!(this.underlying.as_mut().poll_peek(cx));

        // Now that we're ready to interleave the next underlying item with any
        // cache layers, lock them all for the duration of the method, using a
        // SmallVec to (hopefully) store all the guards on the stack.
        let mut layer_guards = SmallVec::<[_; 8]>::new();
        for layer in this.layers.iter() {
            layer_guards.push(layer.read());
        }
        // Tacking the leaf cache onto the list is important to not miss any values.
        // It's stored separately so that the contents of the
        layer_guards.push(this.leaf_cache.read());

        loop {
            // Obtain a reference to the next key-value pair from the underlying stream.
            let peeked = match ready!(this.underlying.as_mut().poll_peek(cx)) {
                // If we get an underlying error, bubble it up immediately.
                Some(Err(_e)) => return this.underlying.poll_next(cx),
                // Otherwise, pass through the peeked value.
                Some(Ok(pair)) => Some(pair),
                None => None,
            };

            // To determine whether or not we should return the peeked value, we
            // need to search the cache layers for keys that are between the last
            // key we returned (exclusive, so we make forward progress on the
            // stream) and the peeked key (inclusive, because we need to find out
            // whether or not there was a covering deletion).
            let search_range = (
                this.last_key
                    .as_ref()
                    .map(Bound::Excluded)
                    .unwrap_or(Bound::Included(this.prefix)),
                peeked
                    .map(|(k, _)| Bound::Included(k))
                    .unwrap_or(Bound::Unbounded),
            );

            // It'd be slightly cleaner to initialize `leftmost_pair` with the
            // peeked contents, but that would taint `leftmost_pair` with a
            // `peeked` borrow, and we may need to mutate the underlying stream
            // later.  Instead, initialize it with `None` to only search the
            // cache layers, and compare at the end.
            let mut leftmost_pair = None;
            for layer in layer_guards.iter() {
                // Find this layer's leftmost key-value pair in the search range.
                let found_pair = layer
                    .as_ref()
                    .expect("layer must not have been applied")
                    .nonverifiable_changes
                    .range::<Vec<u8>, _>(search_range)
                    .take_while(|(k, _v)| k.starts_with(this.prefix))
                    .next();

                // Check whether the new pair, if any, is the new leftmost pair.
                match (leftmost_pair, found_pair) {
                    // We want to replace the pair even when the key is equal,
                    // so that we always prefer a newer value over an older value.
                    (Some((leftmost_k, _)), Some((k, v))) if k <= leftmost_k => {
                        leftmost_pair = Some((k, v));
                    }
                    (None, Some((k, v))) => {
                        leftmost_pair = Some((k, v));
                    }
                    _ => {}
                }
            }

            // Overwrite a Vec, attempting to reuse its existing allocation.
            let overwrite_in_place = |dst: &mut Option<Vec<u8>>, src: &[u8]| {
                if let Some(ref mut dst) = dst {
                    dst.clear();
                    dst.extend_from_slice(src);
                } else {
                    *dst = Some(src.to_vec());
                }
            };

            match (leftmost_pair, peeked) {
                (Some((k, v)), peeked) => {
                    // Since we searched for cached keys less than or equal to
                    // the peeked key, we know that the cached pair takes
                    // priority over the peeked pair.
                    //
                    // If the keys are exactly equal, we advance the underlying stream.
                    if peeked.map(|(kp, _)| kp) == Some(k) {
                        let _ = this.underlying.as_mut().poll_next(cx);
                    }
                    overwrite_in_place(this.last_key, k);
                    if let Some(v) = v {
                        // If the value is Some, we have a key-value pair to yield.
                        return Poll::Ready(Some(Ok((k.clone(), v.clone()))));
                    } else {
                        // If the value is None, this pair represents a deletion,
                        // so continue looping until we find a non-deleted pair.
                        continue;
                    }
                }
                (None, Some(_)) => {
                    // There's no cache hit before the peeked pair, so we want
                    // to extract and return it from the underlying stream.
                    let Poll::Ready(Some(Ok((k, v)))) = this.underlying.as_mut().poll_next(cx)
                    else {
                        unreachable!("peeked stream must yield peeked item");
                    };
                    overwrite_in_place(this.last_key, &k);
                    return Poll::Ready(Some(Ok((k, v))));
                }
                (None, None) => {
                    // Terminate the stream, no more items are available.
                    return Poll::Ready(None);
                }
            }
        }
    }
}

// This implementation is almost exactly the same as the one above, but with
// minor tweaks to work with string keys and to read different fields from the cache.
// Update them together.

#[pin_project]
pub struct StateDeltaPrefixRawStream<St>
where
    St: Stream<Item = Result<(String, Vec<u8>)>>,
{
    #[pin]
    pub(crate) underlying: Peekable<St>,
    pub(crate) layers: Vec<Arc<RwLock<Option<Cache>>>>,
    pub(crate) leaf_cache: Arc<RwLock<Option<Cache>>>,
    pub(crate) last_key: Option<String>,
    pub(crate) prefix: String,
}

impl<St> Stream for StateDeltaPrefixRawStream<St>
where
    St: Stream<Item = Result<(String, Vec<u8>)>>,
{
    type Item = Result<(String, Vec<u8>)>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // This implementation interleaves items from the underlying stream with
        // items in cache layers.  To do this, it tracks the last key it
        // returned, then, for each item in the underlying stream, searches for
        // cached keys that lie between the last-returned key and the item's key,
        // checking whether the cached key represents a deletion requiring further
        // scanning.  This process is illustrated as follows:
        //
        //         ◇ skip                 ◇ skip           ▲ yield          ▲ yield           ▲ yield
        //         │                      │                │                │                 │
        //         ░ pick ──────────────▶ ░ pick ────────▶ █ pick ────────▶ █ pick ─────────▶ █ pick
        //         ▲                      ▲                ▲                ▲                 ▲
        //      ▲  │                 ▲    │          ▲     │         ▲      │        ▲        │
        // write│  │                 │    │          │     │         │      │        │        │
        // layer│  │   █             │    │ █        │     │█        │      █        │      █ │
        //      │  │ ░               │    ░          │    ░│         │    ░          │    ░   │
        //      │  ░                 │  ░            │  ░  │         │  ░            │  ░     │
        //      │    █               │    █          │    █│         │    █          │    █   │
        //      │  █     █           │  █     █      │  █  │  █      │  █     █      │  █     █
        //      │     █              │     █         │     █         │     █         │     █
        //     ─┼(─────]────keys─▶  ─┼──(───]────▶  ─┼────(─]────▶  ─┼─────(]────▶  ─┼──────(──]─▶
        //      │   ▲  █  █          │      █  █     │      █  █     │      █  █     │      █  █
        //          │
        //          │search range of key-value pairs in cache layers that could
        //          │affect whether to yield the next item in the underlying stream

        // Optimization: ensure we have a peekable item in the underlying stream before continuing.
        let mut this = self.project();
        ready!(this.underlying.as_mut().poll_peek(cx));

        // Now that we're ready to interleave the next underlying item with any
        // cache layers, lock them all for the duration of the method, using a
        // SmallVec to (hopefully) store all the guards on the stack.
        let mut layer_guards = SmallVec::<[_; 8]>::new();
        for layer in this.layers.iter() {
            layer_guards.push(layer.read());
        }
        // Tacking the leaf cache onto the list is important to not miss any values.
        // It's stored separately so that the contents of the
        layer_guards.push(this.leaf_cache.read());

        loop {
            // Obtain a reference to the next key-value pair from the underlying stream.
            let peeked = match ready!(this.underlying.as_mut().poll_peek(cx)) {
                // If we get an underlying error, bubble it up immediately.
                Some(Err(_e)) => return this.underlying.poll_next(cx),
                // Otherwise, pass through the peeked value.
                Some(Ok(pair)) => Some(pair),
                None => None,
            };

            // To determine whether or not we should return the peeked value, we
            // need to search the cache layers for keys that are between the last
            // key we returned (exclusive, so we make forward progress on the
            // stream) and the peeked key (inclusive, because we need to find out
            // whether or not there was a covering deletion).
            let search_range = (
                this.last_key
                    .as_ref()
                    .map(Bound::Excluded)
                    .unwrap_or(Bound::Included(this.prefix)),
                peeked
                    .map(|(k, _)| Bound::Included(k))
                    .unwrap_or(Bound::Unbounded),
            );

            // It'd be slightly cleaner to initialize `leftmost_pair` with the
            // peeked contents, but that would taint `leftmost_pair` with a
            // `peeked` borrow, and we may need to mutate the underlying stream
            // later.  Instead, initialize it with `None` to only search the
            // cache layers, and compare at the end.
            let mut leftmost_pair = None;
            for layer in layer_guards.iter() {
                // Find this layer's leftmost key-value pair in the search range.
                let found_pair = layer
                    .as_ref()
                    .expect("layer must not have been applied")
                    .unwritten_changes
                    .range::<String, _>(search_range)
                    .take_while(|(k, _v)| k.starts_with(this.prefix.as_str()))
                    .next();

                // Check whether the new pair, if any, is the new leftmost pair.
                match (leftmost_pair, found_pair) {
                    // We want to replace the pair even when the key is equal,
                    // so that we always prefer a newer value over an older value.
                    (Some((leftmost_k, _)), Some((k, v))) if k <= leftmost_k => {
                        leftmost_pair = Some((k, v));
                    }
                    (None, Some((k, v))) => {
                        leftmost_pair = Some((k, v));
                    }
                    _ => {}
                }
            }

            // Overwrite a Vec, attempting to reuse its existing allocation.
            let overwrite_in_place = |dst: &mut Option<String>, src: &str| {
                if let Some(ref mut dst) = dst {
                    dst.clear();
                    dst.push_str(src);
                } else {
                    *dst = Some(src.to_owned());
                }
            };

            match (leftmost_pair, peeked) {
                (Some((k, v)), peeked) => {
                    // Since we searched for cached keys less than or equal to
                    // the peeked key, we know that the cached pair takes
                    // priority over the peeked pair.
                    //
                    // If the keys are exactly equal, we advance the underlying stream.
                    if peeked.map(|(kp, _)| kp) == Some(k) {
                        let _ = this.underlying.as_mut().poll_next(cx);
                    }
                    overwrite_in_place(this.last_key, k);
                    if let Some(v) = v {
                        // If the value is Some, we have a key-value pair to yield.
                        return Poll::Ready(Some(Ok((k.clone(), v.clone()))));
                    } else {
                        // If the value is None, this pair represents a deletion,
                        // so continue looping until we find a non-deleted pair.
                        continue;
                    }
                }
                (None, Some(_)) => {
                    // There's no cache hit before the peeked pair, so we want
                    // to extract and return it from the underlying stream.
                    let Poll::Ready(Some(Ok((k, v)))) = this.underlying.as_mut().poll_next(cx)
                    else {
                        unreachable!("peeked stream must yield peeked item");
                    };
                    overwrite_in_place(this.last_key, &k);
                    return Poll::Ready(Some(Ok((k, v))));
                }
                (None, None) => {
                    // Terminate the stream, no more items are available.
                    return Poll::Ready(None);
                }
            }
        }
    }
}

// This implementation is almost exactly the same as the one above, but with
// minor tweaks to work with string keys and to read different fields from the cache.
// Update them together.

#[pin_project]
pub struct StateDeltaPrefixKeysStream<St>
where
    St: Stream<Item = Result<String>>,
{
    #[pin]
    pub(crate) underlying: Peekable<St>,
    pub(crate) layers: Vec<Arc<RwLock<Option<Cache>>>>,
    pub(crate) leaf_cache: Arc<RwLock<Option<Cache>>>,
    pub(crate) last_key: Option<String>,
    pub(crate) prefix: String,
}

impl<St> Stream for StateDeltaPrefixKeysStream<St>
where
    St: Stream<Item = Result<String>>,
{
    type Item = Result<String>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // This implementation interleaves items from the underlying stream with
        // items in cache layers.  To do this, it tracks the last key it
        // returned, then, for each item in the underlying stream, searches for
        // cached keys that lie between the last-returned key and the item's key,
        // checking whether the cached key represents a deletion requiring further
        // scanning.  This process is illustrated as follows:
        //
        //         ◇ skip                 ◇ skip           ▲ yield          ▲ yield           ▲ yield
        //         │                      │                │                │                 │
        //         ░ pick ──────────────▶ ░ pick ────────▶ █ pick ────────▶ █ pick ─────────▶ █ pick
        //         ▲                      ▲                ▲                ▲                 ▲
        //      ▲  │                 ▲    │          ▲     │         ▲      │        ▲        │
        // write│  │                 │    │          │     │         │      │        │        │
        // layer│  │   █             │    │ █        │     │█        │      █        │      █ │
        //      │  │ ░               │    ░          │    ░│         │    ░          │    ░   │
        //      │  ░                 │  ░            │  ░  │         │  ░            │  ░     │
        //      │    █               │    █          │    █│         │    █          │    █   │
        //      │  █     █           │  █     █      │  █  │  █      │  █     █      │  █     █
        //      │     █              │     █         │     █         │     █         │     █
        //     ─┼(─────]────keys─▶  ─┼──(───]────▶  ─┼────(─]────▶  ─┼─────(]────▶  ─┼──────(──]─▶
        //      │   ▲  █  █          │      █  █     │      █  █     │      █  █     │      █  █
        //          │
        //          │search range of key-value pairs in cache layers that could
        //          │affect whether to yield the next item in the underlying stream

        // Optimization: ensure we have a peekable item in the underlying stream before continuing.
        let mut this = self.project();
        ready!(this.underlying.as_mut().poll_peek(cx));

        // Now that we're ready to interleave the next underlying item with any
        // cache layers, lock them all for the duration of the method, using a
        // SmallVec to (hopefully) store all the guards on the stack.
        let mut layer_guards = SmallVec::<[_; 8]>::new();
        for layer in this.layers.iter() {
            layer_guards.push(layer.read());
        }
        // Tacking the leaf cache onto the list is important to not miss any values.
        // It's stored separately so that the contents of the
        layer_guards.push(this.leaf_cache.read());

        loop {
            // Obtain a reference to the next key-value pair from the underlying stream.
            let peeked = match ready!(this.underlying.as_mut().poll_peek(cx)) {
                // If we get an underlying error, bubble it up immediately.
                Some(Err(_e)) => return this.underlying.poll_next(cx),
                // Otherwise, pass through the peeked value.
                Some(Ok(pair)) => Some(pair),
                None => None,
            };

            // To determine whether or not we should return the peeked value, we
            // need to search the cache layers for keys that are between the last
            // key we returned (exclusive, so we make forward progress on the
            // stream) and the peeked key (inclusive, because we need to find out
            // whether or not there was a covering deletion).
            let search_range = (
                this.last_key
                    .as_ref()
                    .map(Bound::Excluded)
                    .unwrap_or(Bound::Included(this.prefix)),
                peeked.map(Bound::Included).unwrap_or(Bound::Unbounded),
            );

            // It'd be slightly cleaner to initialize `leftmost_pair` with the
            // peeked contents, but that would taint `leftmost_pair` with a
            // `peeked` borrow, and we may need to mutate the underlying stream
            // later.  Instead, initialize it with `None` to only search the
            // cache layers, and compare at the end.
            let mut leftmost_pair = None;
            for layer in layer_guards.iter() {
                // Find this layer's leftmost key-value pair in the search range.
                let found_pair = layer
                    .as_ref()
                    .expect("layer must not have been applied")
                    .unwritten_changes
                    .range::<String, _>(search_range)
                    .take_while(|(k, _v)| k.starts_with(this.prefix.as_str()))
                    .next();

                // Check whether the new pair, if any, is the new leftmost pair.
                match (leftmost_pair, found_pair) {
                    // We want to replace the pair even when the key is equal,
                    // so that we always prefer a newer value over an older value.
                    (Some((leftmost_k, _)), Some((k, v))) if k <= leftmost_k => {
                        leftmost_pair = Some((k, v));
                    }
                    (None, Some((k, v))) => {
                        leftmost_pair = Some((k, v));
                    }
                    _ => {}
                }
            }

            // Overwrite a Vec, attempting to reuse its existing allocation.
            let overwrite_in_place = |dst: &mut Option<String>, src: &str| {
                if let Some(ref mut dst) = dst {
                    dst.clear();
                    dst.push_str(src);
                } else {
                    *dst = Some(src.to_owned());
                }
            };

            match (leftmost_pair, peeked) {
                (Some((k, v)), peeked) => {
                    // Since we searched for cached keys less than or equal to
                    // the peeked key, we know that the cached pair takes
                    // priority over the peeked pair.
                    //
                    // If the keys are exactly equal, we advance the underlying stream.
                    if peeked == Some(k) {
                        let _ = this.underlying.as_mut().poll_next(cx);
                    }
                    overwrite_in_place(this.last_key, k);
                    if v.is_some() {
                        // If the value is Some, we have a key-value pair to yield.
                        return Poll::Ready(Some(Ok(k.clone())));
                    } else {
                        // If the value is None, this pair represents a deletion,
                        // so continue looping until we find a non-deleted pair.
                        continue;
                    }
                }
                (None, Some(_)) => {
                    // There's no cache hit before the peeked pair, so we want
                    // to extract and return it from the underlying stream.
                    let Poll::Ready(Some(Ok(k))) = this.underlying.as_mut().poll_next(cx) else {
                        unreachable!("peeked stream must yield peeked item");
                    };
                    overwrite_in_place(this.last_key, &k);
                    return Poll::Ready(Some(Ok(k)));
                }
                (None, None) => {
                    // Terminate the stream, no more items are available.
                    return Poll::Ready(None);
                }
            }
        }
    }
}

#[pin_project]
/// A stream of key-value pairs that interleaves a nonverifiable storage and caching layers.
// This implementation differs from [`StateDeltaNonconsensusPrefixRawStream`] sin how
// it specifies the search space for the cache.
pub struct StateDeltaNonconsensusRangeRawStream<St>
where
    St: Stream<Item = Result<(Vec<u8>, Vec<u8>)>>,
{
    #[pin]
    pub(crate) underlying: Peekable<St>,
    pub(crate) layers: Vec<Arc<RwLock<Option<Cache>>>>,
    pub(crate) leaf_cache: Arc<RwLock<Option<Cache>>>,
    pub(crate) last_key: Option<Vec<u8>>,
    pub(crate) prefix: Option<Vec<u8>>,
    pub(crate) range: (Option<Vec<u8>>, Option<Vec<u8>>),
}

impl<St> Stream for StateDeltaNonconsensusRangeRawStream<St>
where
    St: Stream<Item = Result<(Vec<u8>, Vec<u8>)>>,
{
    type Item = Result<(Vec<u8>, Vec<u8>)>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // This implementation interleaves items from the underlying stream with
        // items in cache layers.  To do this, it tracks the last key it
        // returned, then, for each item in the underlying stream, searches for
        // cached keys that lie between the last-returned key and the item's key,
        // checking whether the cached key represents a deletion requiring further
        // scanning.  This process is illustrated as follows:
        //
        //         ◇ skip                 ◇ skip           ▲ yield          ▲ yield           ▲ yield
        //         │                      │                │                │                 │
        //         ░ pick ──────────────▶ ░ pick ────────▶ █ pick ────────▶ █ pick ─────────▶ █ pick
        //         ▲                      ▲                ▲                ▲                 ▲
        //      ▲  │                 ▲    │          ▲     │         ▲      │        ▲        │
        // write│  │                 │    │          │     │         │      │        │        │
        // layer│  │   █             │    │ █        │     │█        │      █        │      █ │
        //      │  │ ░               │    ░          │    ░│         │    ░          │    ░   │
        //      │  ░                 │  ░            │  ░  │         │  ░            │  ░     │
        //      │    █               │    █          │    █│         │    █          │    █   │
        //      │  █     █           │  █     █      │  █  │  █      │  █     █      │  █     █
        //      │     █              │     █         │     █         │     █         │     █
        //     ─┼(─────]────keys─▶  ─┼──(───]────▶  ─┼────(─]────▶  ─┼─────(]────▶  ─┼──────(──]─▶
        //      │   ▲  █  █          │      █  █     │      █  █     │      █  █     │      █  █
        //          │
        //          │search range of key-value pairs in cache layers that could
        //          │affect whether to yield the next item in the underlying stream

        // Optimization: ensure we have a peekable item in the underlying stream before continuing.
        let mut this = self.project();
        ready!(this.underlying.as_mut().poll_peek(cx));
        // Now that we're ready to interleave the next underlying item with any
        // cache layers, lock them all for the duration of the method, using a
        // SmallVec to (hopefully) store all the guards on the stack.
        let mut layer_guards = SmallVec::<[_; 8]>::new();
        for layer in this.layers.iter() {
            layer_guards.push(layer.read());
        }
        // Tacking the leaf cache onto the list is important to not miss any values.
        // It's stored separately so that the contents of the
        layer_guards.push(this.leaf_cache.read());

        let (binding_prefix, binding_start, binding_end) = (Vec::new(), Vec::new(), Vec::new());
        let prefix = this.prefix.as_ref().unwrap_or(&binding_prefix);
        let start = this.range.0.as_ref().unwrap_or(&binding_start);
        let end = this.range.1.as_ref().unwrap_or(&binding_end);

        let mut prefix_start = Vec::with_capacity(prefix.len() + start.len());
        let mut prefix_end = Vec::with_capacity(prefix.len() + end.len());

        prefix_start.extend(prefix);
        prefix_start.extend(start);
        prefix_end.extend(prefix);
        prefix_end.extend(end);

        loop {
            // Obtain a reference to the next key-value pair from the underlying stream.
            let peeked = match ready!(this.underlying.as_mut().poll_peek(cx)) {
                // If we get an underlying error, bubble it up immediately.
                Some(Err(_e)) => return this.underlying.poll_next(cx),
                // Otherwise, pass through the peeked value.
                Some(Ok(pair)) => Some(pair),
                None => None,
            };

            // We want to decide which key to return next, so we have to inspect the cache layers.
            // To do this, we have to define a search space so that we cover updates and new insertions
            // that could affect the next key to return.
            let lower_bound = match this.last_key.as_ref() {
                Some(k) => Bound::Excluded(k),
                None => Bound::Included(prefix_start.as_ref()),
            };

            let upper_bound = match peeked {
                Some((k, _v)) => Bound::Included(k),
                None => this
                    .range
                    .1
                    .as_ref()
                    .map_or(Bound::Unbounded, |_| Bound::Excluded(prefix_end.as_ref())),
            };

            let search_range = (lower_bound, upper_bound);

            tracing::debug!(
                "searching cache layers for key-value pairs in range {:?}",
                search_range
            );

            // It'd be slightly cleaner to initialize `leftmost_pair` with the
            // peeked contents, but that would taint `leftmost_pair` with a
            // `peeked` borrow, and we may need to mutate the underlying stream
            // later.  Instead, initialize it with `None` to only search the
            // cache layers, and compare at the end.
            let mut leftmost_pair = None;
            for layer in layer_guards.iter() {
                // Find this layer's leftmost key-value pair in the search range.
                let found_pair = layer
                    .as_ref()
                    .expect("layer must not have been applied")
                    .nonverifiable_changes
                    .range::<Vec<u8>, _>(search_range)
                    .take_while(|(k, v)| {
                        tracing::debug!(?v, ?k, "found key-value pair in cache layer");
                        match peeked {
                            Some((peeked_k, _)) => {
                                k.starts_with(prefix.as_slice()) && k <= &peeked_k
                            }
                            None => k.starts_with(prefix.as_slice()),
                        }
                    })
                    .next();

                // Check whether the new pair, if any, is the new leftmost pair.
                match (leftmost_pair, found_pair) {
                    // We want to replace the pair even when the key is equal,
                    // so that we always prefer a newer value over an older value.
                    (Some((leftmost_k, _)), Some((k, v))) if k <= leftmost_k => {
                        leftmost_pair = Some((k, v));
                    }
                    (None, Some((k, v))) => {
                        leftmost_pair = Some((k, v));
                    }
                    _ => {}
                }
            }

            // Overwrite a Vec, attempting to reuse its existing allocation.
            let overwrite_in_place = |dst: &mut Option<Vec<u8>>, src: &[u8]| {
                if let Some(ref mut dst) = dst {
                    dst.clear();
                    dst.extend_from_slice(src);
                } else {
                    *dst = Some(src.to_vec());
                }
            };

            match (leftmost_pair, peeked) {
                (Some((k, v)), peeked) => {
                    // Since we searched for cached keys less than or equal to
                    // the peeked key, we know that the cached pair takes
                    // priority over the peeked pair.
                    //
                    // If the keys are exactly equal, we advance the underlying stream.
                    if peeked.map(|(kp, _)| kp) == Some(k) {
                        let _ = this.underlying.as_mut().poll_next(cx);
                    }
                    overwrite_in_place(this.last_key, k);
                    if let Some(v) = v {
                        // If the value is Some, we have a key-value pair to yield.
                        return Poll::Ready(Some(Ok((k.clone(), v.clone()))));
                    } else {
                        // If the value is None, this pair represents a deletion,
                        // so continue looping until we find a non-deleted pair.
                        continue;
                    }
                }
                (None, Some(_)) => {
                    // There's no cache hit before the peeked pair, so we want
                    // to extract and return it from the underlying stream.
                    let Poll::Ready(Some(Ok((k, v)))) = this.underlying.as_mut().poll_next(cx)
                    else {
                        unreachable!("peeked stream must yield peeked item");
                    };
                    overwrite_in_place(this.last_key, &k);
                    return Poll::Ready(Some(Ok((k, v))));
                }
                (None, None) => {
                    // Terminate the stream, no more items are available.
                    return Poll::Ready(None);
                }
            }
        }
    }
}