itzma-core 0.4.0

Vector search on object storage: an embedded library, no server, just your bucket
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
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! The k-way merge over a namespace's sources in id order.
//!
//! The sources are the live segments, oldest to newest, and the WAL tail as one
//! more. Each yields its documents and tombstones in id order, starting after
//! the cursor. For the smallest id across the sources, the newest source that
//! holds it decides: a document is the winner, a tombstone drops the id, and
//! every older copy is skipped. So shadowing costs nothing here, since the
//! merge sees every copy of an id side by side. The fronts are kept in
//! [`NewestWins`], so the smallest id costs `log(sources)`.
//!
//! A version 2 or 3 segment is read through `RangedSegment`, one 256-row block of
//! ids and attributes (and of tombstones) at a time, fetched when the merge
//! needs it, and the vector matrix is never read. A run of version 1 segments
//! has no blocks and is decoded whole.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::future::Future;
use std::ops::Range;
use std::sync::{Arc, Mutex};

use futures::future::try_join_all;
use futures::stream::{self, StreamExt, TryStreamExt};
use object_store::ObjectStore;
use serde_json::Value;

use crate::attr_index;
use crate::attrs::AttrSchema;
use crate::budget::ReadBudget;
use crate::columnar::{Bitmap, IdColumn};
use crate::decoded::DecodedRef;
use crate::error::Result;
use crate::fetch::FETCH_CONCURRENCY;
use crate::fetch::FetchPolicy;
use crate::layer::{Layer, NewestWins};
use crate::manifest::AttrIndexEntry;
use crate::predicate::{Passes, Predicate, Tri};
use crate::segment::BLOCK_ROWS;
use crate::segment::{RangedSegment, Stored, WindowAttrs};
use crate::sparse::SparseRows;
use crate::wal;

/// The most stored bytes of ids and attributes one forward source reads at a
/// time.
pub(crate) const SCAN_WINDOW_MAX: u64 = 1 << 20;

/// Bytes of ids and attributes each of `sources` forward sources reads at a
/// time under a `budget`: a quarter of it split between them, leaving room
/// for each source's document window and tombstone window together with the
/// slice of winners and vectors charged to the same budget, and at most
/// [`SCAN_WINDOW_MAX`]. A source always reads at least one block, whatever
/// this says. The fetch planner may round a window's reads up to its
/// alignment (`object_store()`: 64 KiB per section), which this does not
/// count.
pub(crate) fn window_bytes(budget: u64, sources: usize) -> u64 {
    let sources = u64::try_from(sources.max(1)).unwrap_or(u64::MAX);
    (budget / sources.saturating_mul(4)).min(SCAN_WINDOW_MAX)
}

/// How a segment source reads its blocks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mode {
    /// One block at a time, through the decoded cache when the handle has
    /// one, attributes parsed as read: a `filter` page.
    Page,
    /// Windows of about `window_bytes` of ids and attributes, nothing kept,
    /// attributes left as stored until a row wins: a scan.
    Forward { window_bytes: u64 },
}

/// A document's attributes, parsed or still as stored.
pub(crate) enum Attrs {
    Parsed(Option<Value>),
    /// As stored, a view of the fetched window: JSON or a row of a column
    /// block. Rebuilt only if the row wins.
    Stored(Stored),
}

/// What one source holds for one id.
pub(crate) enum Body {
    Doc(Attrs),
    Tombstone,
    /// A document this source holds, proven by [`attr_index::index_candidates`]'s
    /// superset guarantee not to match the predicate, without its
    /// attributes ever having been fetched. Occupies the id in the merge —
    /// so a newer source's real, current value still shadows an older
    /// source's stale match — but is never itself a winner.
    NonMatchingDoc,
}

pub(crate) struct Entry {
    pub(crate) id: String,
    pub(crate) body: Body,
    /// The row of a document in its version 2 or 3 segment, where its vector and
    /// sparse vector are; `None` for a tombstone or a layer's document.
    pub(crate) row: Option<u32>,
}

/// A live document the merge decided on: the newest copy of its id.
pub(crate) struct Winner {
    /// The source it came from, oldest first.
    pub(crate) source: usize,
    pub(crate) id: String,
    pub(crate) attrs: Attrs,
    /// Its row in that source's segment, if the source is one.
    pub(crate) row: Option<u32>,
}

/// What a merge reads, against one manifest.
pub(crate) struct Open<'a> {
    pub(crate) store: &'a dyn ObjectStore,
    pub(crate) namespace: &'a str,
    pub(crate) dim: usize,
    pub(crate) budget: &'a ReadBudget,
    pub(crate) policy: &'a FetchPolicy,
    /// Each segment's attribute index generation, by id, if the manifest
    /// names one.
    pub(crate) attr_indexes: &'a BTreeMap<String, AttrIndexEntry>,
    pub(crate) attrs: &'a AttrSchema,
    /// Parsed structures kept between queries, if the handle has a
    /// decoded cache.
    pub(crate) decoded: Option<&'a DecodedRef>,
    /// Only for attribute-index pruning; the merge never tests it itself.
    pub(crate) predicate: Option<&'a Predicate>,
    pub(crate) after: Option<&'a str>,
    /// The merge ends at the first id past this one, reading nothing for
    /// what lies beyond.
    pub(crate) until: Option<&'a str>,
    pub(crate) mode: Mode,
    /// Open each segment's `sparse.bin`, for a scan that returns sparse
    /// vectors.
    pub(crate) with_sparse: bool,
}

impl Open<'_> {
    /// The predicate, but only when it could possibly resolve through an
    /// attribute index (`attr_index::could_resolve`, checked from field
    /// names alone, no I/O) — the precheck that keeps a predicate touching
    /// no indexed field from ever paying for an attr-idx fetch and decode.
    fn resolvable_predicate(&self) -> Option<&Predicate> {
        let predicate = self.predicate?;
        let indexed: BTreeSet<&str> = self.attrs.indexed_field_names().collect();
        attr_index::could_resolve(predicate, &indexed).then_some(predicate)
    }
}

/// A source of entries in strictly ascending id order.
pub(crate) enum Source<'a> {
    /// A version 2 or 3 segment, read a block (or a window) at a time.
    Segment(Box<SegmentSource<'a>>),
    /// A version 1 run or the tail, in memory. The layer is kept for the
    /// winners' vectors and sparse vectors.
    Layer {
        layer: Arc<Layer>,
        entries: VecDeque<Entry>,
        /// The path errors about it name: the run's first segment's data
        /// object, or the WAL prefix for the tail.
        label: String,
    },
}

/// Where a winner's vector and sparse vector are read from.
pub(crate) enum Origin<'s, 'a> {
    /// A version 2 or 3 segment and its `sparse.bin`, if the scan opened one.
    Segment(&'s RangedSegment<'a>, Option<&'s SparseRows<'a>>),
    /// A version 1 run or the tail, and the path errors about it name.
    Layer(&'s Layer, &'s str),
}

/// One side of a segment (its documents, or its tombstones): the next block to
/// fetch and what is buffered from the last one.
pub(crate) struct Side {
    next_block: usize,
    blocks: usize,
    buffer: Buffer,
    /// The last id this side produced, to check the segment really is sorted.
    last: Option<String>,
}

impl Side {
    /// Its buffer is empty and it has a block left.
    fn ran_dry(&self) -> bool {
        self.buffer.is_empty() && self.next_block < self.blocks
    }
}

/// What one side holds from its last read.
enum Buffer {
    /// Entries one at a time: a page's block.
    Entries(VecDeque<Entry>),
    /// A forward window, held as read and turned into an entry only when it
    /// is popped, so a source holds its window's bytes and not an `Entry`
    /// per row.
    Window(Window),
}

/// A forward window and the next row of it to hand out.
struct Window {
    ids: IdColumn,
    /// The documents' attributes; `None` for a tombstone window.
    attrs: Option<WindowAttrs>,
    /// The segment row of the window's first row.
    first_row: u32,
    next: usize,
}

impl Buffer {
    fn is_empty(&self) -> bool {
        match self {
            Self::Entries(entries) => entries.is_empty(),
            Self::Window(w) => w.next >= w.ids.len(),
        }
    }

    fn front_id(&self) -> Option<&str> {
        match self {
            Self::Entries(entries) => entries.front().map(|e| e.id.as_str()),
            Self::Window(w) => (w.next < w.ids.len()).then(|| w.ids.get(w.next)),
        }
    }

    fn pop(&mut self) -> Option<Entry> {
        match self {
            Self::Entries(entries) => entries.pop_front(),
            Self::Window(w) => {
                let at = w.next;
                if at >= w.ids.len() {
                    return None;
                }
                w.next += 1;
                let id = w.ids.get(at).to_owned();
                Some(match &w.attrs {
                    Some(attrs) => Entry {
                        id,
                        body: Body::Doc(Attrs::Stored(attrs.get(at))),
                        row: Some(
                            w.first_row
                                .saturating_add(u32::try_from(at).unwrap_or(u32::MAX)),
                        ),
                    },
                    None => Entry {
                        id,
                        body: Body::Tombstone,
                        row: None,
                    },
                })
            }
        }
    }
}

pub(crate) struct SegmentSource<'a> {
    segment: RangedSegment<'a>,
    sparse: Option<SparseRows<'a>>,
    docs: Side,
    tombstones: Side,
    after: Option<String>,
    mode: Mode,
    /// The rows an attribute index says may match, ascending, on a page
    /// only. Every row still takes its place in the merge, so a newer copy
    /// of an id shadows an older source's stale match, but only these rows'
    /// attributes are read; the others are `NonMatchingDoc`.
    candidates: Option<Vec<u32>>,
    /// What the segment's zone maps say of the predicate for each block, on a
    /// page of a version 3 segment. A `Never` block is read for its ids only,
    /// like a row outside `candidates`.
    verdicts: Option<Vec<Tri>>,
    /// The predicate and the positions of the columns it reads, on a page of a
    /// version 3 segment: a `Maybe` block is evaluated on those columns
    /// alone and only the rows that match have their attributes read.
    evaluate: Option<Evaluate<'a>>,
}

/// What evaluating a `Maybe` block needs: the predicate, the positions of
/// the columns it reads, and the scan's one planner for its `And`.
struct Evaluate<'a> {
    predicate: &'a Predicate,
    fields: Vec<usize>,
    passes: Arc<Mutex<Passes>>,
}

impl Source<'_> {
    /// The next entry's id, without taking it.
    fn front_id(&self) -> Option<&str> {
        match self {
            Self::Layer { entries, .. } => entries.front().map(|e| e.id.as_str()),
            Self::Segment(s) => match (s.docs.buffer.front_id(), s.tombstones.buffer.front_id()) {
                (Some(d), Some(t)) => Some(d.min(t)),
                (d, t) => d.or(t),
            },
        }
    }

    fn pop(&mut self) -> Option<Entry> {
        match self {
            Self::Layer { entries, .. } => entries.pop_front(),
            Self::Segment(s) => {
                let doc_first = match (s.docs.buffer.front_id(), s.tombstones.buffer.front_id()) {
                    (Some(d), Some(t)) => d <= t,
                    (Some(_), None) => true,
                    (None, _) => false,
                };
                let side = if doc_first {
                    &mut s.docs
                } else {
                    &mut s.tombstones
                };
                side.buffer.pop()
            }
        }
    }

    /// Fetch the next block, or forward window, of any side that ran dry
    /// and still has blocks. Nothing is fetched ahead: a read the merge
    /// started and then stopped polling would hold its `GatedStore` permits
    /// while the batch waits on the same gate for its vectors.
    async fn fill(&mut self) -> Result<()> {
        let Self::Segment(s) = self else {
            return Ok(());
        };
        let after = s.after.clone();
        while s.docs.ran_dry() {
            match s.mode {
                Mode::Page => {
                    let block = s.docs.next_block;
                    s.docs.next_block += 1;
                    let verdict = s.verdicts.as_ref().and_then(|v| v.get(block)).copied();
                    let entries = match (&s.candidates, verdict, &s.evaluate) {
                        (_, Some(Tri::Never), _) => pruned_block(&s.segment, &[], block).await?,
                        (candidates, Some(Tri::Maybe), Some(evaluate)) => {
                            evaluated_block(&s.segment, evaluate, candidates.as_deref(), block)
                                .await?
                        }
                        (None, ..) => s
                            .segment
                            .doc_block(block)
                            .await?
                            .into_iter()
                            .zip(first_row(block)..)
                            .map(|((id, attrs), row)| Entry {
                                id,
                                body: Body::Doc(Attrs::Parsed(attrs)),
                                row: Some(row),
                            })
                            .collect::<Vec<_>>(),
                        (Some(candidates), ..) => {
                            pruned_block(&s.segment, candidates, block).await?
                        }
                    };
                    push_sorted(
                        &s.segment,
                        &mut s.docs,
                        entries.into_iter(),
                        after.as_deref(),
                    )?;
                }
                Mode::Forward { window_bytes } => {
                    let segment = &s.segment;
                    let blocks = window(&s.docs, window_bytes, |b| segment.id_attr_bytes(b));
                    s.docs.next_block = blocks.end;
                    let first = first_row(blocks.start);
                    let read = s.segment.id_attr_window(blocks).await?;
                    let window = Window {
                        ids: read.ids,
                        attrs: Some(read.attrs),
                        first_row: first,
                        next: 0,
                    };
                    push_window(&s.segment, &mut s.docs, window, after.as_deref())?;
                }
            }
        }
        while s.tombstones.ran_dry() {
            match s.mode {
                Mode::Page => {
                    let block = s.tombstones.next_block;
                    s.tombstones.next_block += 1;
                    let ids = s.segment.tombstone_block(block).await?;
                    let entries = ids.into_iter().map(|id| Entry {
                        id,
                        body: Body::Tombstone,
                        row: None,
                    });
                    push_sorted(&s.segment, &mut s.tombstones, entries, after.as_deref())?;
                }
                Mode::Forward { window_bytes } => {
                    let segment = &s.segment;
                    let blocks = window(&s.tombstones, window_bytes, |b| {
                        segment.tombstone_window_bytes(b)
                    });
                    s.tombstones.next_block = blocks.end;
                    let ids = s.segment.tombstone_column(blocks).await?;
                    let window = Window {
                        ids,
                        attrs: None,
                        first_row: 0,
                        next: 0,
                    };
                    push_window(&s.segment, &mut s.tombstones, window, after.as_deref())?;
                }
            }
        }
        Ok(())
    }

    /// Whether a side of a segment emptied its buffer and may have more to
    /// read: the only case [`fill`](Self::fill) has anything to do.
    fn ran_dry(&self) -> bool {
        match self {
            Self::Segment(s) => s.docs.ran_dry() || s.tombstones.ran_dry(),
            Self::Layer { .. } => false,
        }
    }

    /// The path errors about this source name.
    fn label(&self) -> String {
        match self {
            Self::Segment(s) => s.segment.label(),
            Self::Layer { label, .. } => label.clone(),
        }
    }
}

/// The row number of the first row of id block `block`.
fn first_row(block: usize) -> u32 {
    u32::try_from(block.saturating_mul(BLOCK_ROWS)).unwrap_or(u32::MAX)
}

/// The blocks of `side`'s next window: from its next block, as many as fit in
/// `window_bytes` by `cost`, and always at least one.
fn window(side: &Side, window_bytes: u64, cost: impl Fn(usize) -> u64) -> Range<usize> {
    let start = side.next_block;
    let mut end = start + 1;
    let mut bytes = cost(start);
    while end < side.blocks && bytes.saturating_add(cost(end)) <= window_bytes {
        bytes += cost(end);
        end += 1;
    }
    start..end
}

/// Buffer `entries` (one block, in order) that come after the cursor, checking
/// that ids only go up. The ranged reads trust the directory, and the whole
/// decoder that would catch an unsorted segment is not on this path.
fn push_sorted(
    segment: &RangedSegment<'_>,
    side: &mut Side,
    entries: impl Iterator<Item = Entry>,
    after: Option<&str>,
) -> Result<()> {
    for entry in entries {
        if side
            .last
            .as_deref()
            .is_some_and(|last| entry.id.as_str() <= last)
        {
            return Err(segment.corrupt("ids are not in ascending order"));
        }
        side.last = Some(entry.id.clone());
        if after.is_none_or(|after| entry.id.as_str() > after) {
            let Buffer::Entries(entries) = &mut side.buffer else {
                return Err(segment.corrupt("a page read into a forward buffer"));
            };
            entries.push_back(entry);
        }
    }
    Ok(())
}

/// Buffer a forward `window` (strictly ascending, which the window's read
/// checked), after checking it continues past the side's last id and
/// skipping its ids at or below the cursor: `push_sorted`'s rules, once per
/// window instead of once per entry.
fn push_window(
    segment: &RangedSegment<'_>,
    side: &mut Side,
    mut window: Window,
    after: Option<&str>,
) -> Result<()> {
    let len = window.ids.len();
    if len == 0 {
        side.buffer = Buffer::Window(window);
        return Ok(());
    }
    if side
        .last
        .as_deref()
        .is_some_and(|last| window.ids.get(0) <= last)
    {
        return Err(segment.corrupt("ids are not in ascending order"));
    }
    side.last = Some(window.ids.get(len - 1).to_owned());
    if let Some(after) = after {
        window.next = window.ids.partition_point(|id| id <= after);
    }
    side.buffer = Buffer::Window(window);
    Ok(())
}

/// The sources of one namespace, merged in id order.
pub(crate) struct Merge<'a> {
    sources: Vec<Source<'a>>,
    heads: NewestWins<String>,
    until: Option<String>,
}

impl<'a> Merge<'a> {
    /// Open every live segment in `ids` and the tail as sources and fill each
    /// one's first block. The tail is read alongside the segment opens.
    ///
    /// # Errors
    ///
    /// The errors of reading segments and the tail (a missing segment, or a
    /// fenced WAL object, is what the caller reloads the manifest for), and
    /// [`ItzmaError::ReadBudgetExceeded`](crate::ItzmaError::ReadBudgetExceeded).
    pub(crate) async fn open(
        open: &Open<'a>,
        ids: &'a [String],
        tail: impl Future<Output = Result<Arc<Layer>>>,
    ) -> Result<Self> {
        let (mut sources, tail) = futures::try_join!(open_sources(open, ids), tail)?;
        if !tail.is_empty() {
            let entries = layer_entries(&tail, open.after);
            sources.push(Source::Layer {
                layer: tail,
                entries,
                label: wal::wal_prefix(open.namespace).to_string(),
            });
        }
        // Every source's first block or window is read at the same time.
        try_join_all(sources.iter_mut().map(Source::fill)).await?;
        let mut merge = Self {
            heads: NewestWins::with_capacity(sources.len()),
            sources,
            until: open.until.map(str::to_owned),
        };
        merge.push_heads();
        Ok(merge)
    }

    /// A merge over sources already filled.
    #[cfg(test)]
    pub(crate) fn from_sources(sources: Vec<Source<'a>>) -> Self {
        let mut merge = Self {
            heads: NewestWins::with_capacity(sources.len()),
            sources,
            until: None,
        };
        merge.push_heads();
        merge
    }

    /// A merge over one in-memory layer, its errors naming `label`.
    #[cfg(test)]
    pub(crate) fn of_layer(layer: Layer, label: &str) -> Self {
        let entries = layer_entries(&layer, None);
        Self::from_sources(vec![Source::Layer {
            layer: Arc::new(layer),
            entries,
            label: label.to_string(),
        }])
    }

    fn push_heads(&mut self) {
        if self.sources.len() == 1 {
            return;
        }
        for (at, source) in self.sources.iter().enumerate() {
            if let Some(front) = source.front_id() {
                self.heads.push(at, front.to_owned());
            }
        }
    }

    /// The next live document in id order, after shadowing and tombstones.
    /// The caller tests any predicate.
    ///
    /// # Errors
    ///
    /// As for [`open`](Self::open), for the blocks read on the way.
    pub(crate) async fn next(&mut self) -> Result<Option<Winner>> {
        if self.sources.len() == 1 {
            return self.next_alone().await;
        }
        loop {
            let Some((id, winner)) = self.heads.pop() else {
                return Ok(None);
            };
            if self.past_until(&id) {
                return Ok(None);
            }
            let entry = self.take(winner).await?;
            while let Some(older) = self.heads.pop_older(&id) {
                self.take(older).await?;
            }
            if let Some(Entry {
                id,
                body: Body::Doc(attrs),
                row,
            }) = entry
            {
                return Ok(Some(Winner {
                    source: winner,
                    id,
                    attrs,
                    row,
                }));
            }
        }
    }

    /// [`next`](Self::next) over a single source, which has nothing to
    /// shadow: its entries in order, without the heap. A one-segment
    /// namespace with no tail is common, and the heap's push, pop and id
    /// clone per row are most of what the merge costs there.
    async fn next_alone(&mut self) -> Result<Option<Winner>> {
        loop {
            if self.sources[0]
                .front_id()
                .is_none_or(|id| self.past_until(id))
            {
                return Ok(None);
            }
            let Some(entry) = self.sources[0].pop() else {
                return Ok(None);
            };
            if self.sources[0].ran_dry() {
                self.sources[0].fill().await?;
            }
            match entry.body {
                Body::Doc(attrs) => {
                    return Ok(Some(Winner {
                        source: 0,
                        id: entry.id,
                        attrs,
                        row: entry.row,
                    }));
                }
                Body::NonMatchingDoc | Body::Tombstone => {}
            }
        }
    }

    fn past_until(&self, id: &str) -> bool {
        self.until.as_deref().is_some_and(|until| id > until)
    }

    /// Where source `at`'s winners' vectors and sparse vectors are.
    pub(crate) fn origin(&self, at: usize) -> Origin<'_, 'a> {
        match &self.sources[at] {
            Source::Segment(s) => Origin::Segment(&s.segment, s.sparse.as_ref()),
            Source::Layer { layer, label, .. } => Origin::Layer(layer, label),
        }
    }

    /// Each source's label, by source number, for errors about stored
    /// attributes parsed off the merge.
    pub(crate) fn labels(&self) -> Vec<String> {
        self.sources.iter().map(Source::label).collect()
    }

    /// A winner's attributes, parsed if they were left as stored.
    ///
    /// # Errors
    ///
    /// [`ItzmaError::CorruptSegment`](crate::ItzmaError::CorruptSegment) for
    /// stored attributes that are not JSON.
    pub(crate) fn parse(&self, source: usize, attrs: Attrs) -> Result<Option<Value>> {
        match attrs {
            Attrs::Parsed(attrs) => Ok(attrs),
            Attrs::Stored(stored) => stored.value(&self.sources[source].label()),
        }
    }

    /// Take source `at`'s front, refill it, and push its new front. `None` only
    /// if the heap named a source with nothing buffered, which `from_sources`
    /// and this function never let happen; the caller skips it rather than add
    /// an error for an impossible state.
    async fn take(&mut self, at: usize) -> Result<Option<Entry>> {
        let entry = self.sources[at].pop();
        // Most pops leave the buffer non-empty: skip building a refill future
        // for those, which is most of the per-row cost of the merge.
        if self.sources[at].ran_dry() {
            self.sources[at].fill().await?;
        }
        if let Some(front) = self.sources[at].front_id() {
            self.heads.push(at, front.to_owned());
        }
        Ok(entry)
    }
}

/// Every live segment as a source, in order, opened in parallel.
async fn open_sources<'a>(open: &Open<'a>, ids: &'a [String]) -> Result<Vec<Source<'a>>> {
    // Indexed by position, not mapped over borrowed values: see
    // `query::open_sources` for why a closure whose parameter borrows is not
    // provably `Send`.
    let opened: Vec<Opened<'a>> = stream::iter(0..ids.len())
        .map(|at| open_one(open, &ids[at]))
        .buffered(FETCH_CONCURRENCY)
        .try_collect()
        .await?;

    // One planner for the whole scan, so every segment's blocks teach the
    // next block which conjunct rejects most.
    let passes = Arc::new(
        open.predicate
            .map_or_else(|| Mutex::new(Passes::new(0)), Predicate::passes),
    );
    let mut sources = Vec::with_capacity(opened.len() + 1);
    for (at, (segment, sparse)) in opened.into_iter().enumerate() {
        // Only a page prunes: pruning resolves the segment's candidate rows
        // up front, which a scan of the whole namespace has no use for, since
        // it tests the predicate on every winner anyway.
        let resolvable = match open.mode {
            Mode::Page => open.resolvable_predicate(),
            Mode::Forward { .. } => None,
        };
        let pruned = match (resolvable, open.attr_indexes.get(&ids[at])) {
            (Some(predicate), Some(entry)) => {
                let path = attr_index::attr_index_path(open.namespace, &ids[at], entry.generation);
                let index =
                    attr_index::open(open.store, open.budget, &path, segment.doc_count()).await?;
                attr_index::index_candidates(predicate, &index)
            }
            _ => None,
        };
        let candidates = pruned.map(|mut rows| {
            rows.sort_unstable();
            rows.dedup();
            rows
        });
        let verdicts = match (open.mode, open.predicate) {
            (Mode::Page, Some(predicate)) => segment.block_verdicts(predicate).await?,
            _ => None,
        };
        let evaluate = open
            .predicate
            .filter(|_| verdicts.is_some())
            .and_then(|predicate| {
                let mut names = BTreeSet::new();
                predicate.fields_into(&mut names);
                segment.field_positions(names).map(|fields| Evaluate {
                    predicate,
                    fields,
                    passes: Arc::clone(&passes),
                })
            });
        sources.push(segment_source(
            segment,
            sparse,
            open.after,
            open.until,
            open.mode,
            Pruning {
                candidates,
                verdicts,
                evaluate,
            },
        ));
    }
    Ok(sources)
}

/// A segment and, for a scan that returns sparse vectors, its
/// `sparse.bin`.
type Opened<'a> = (RangedSegment<'a>, Option<SparseRows<'a>>);

/// Segment `id` opened for ranged reads.
async fn open_one<'a>(open: &Open<'a>, id: &str) -> Result<Opened<'a>> {
    let segment = RangedSegment::open(
        open.store,
        open.namespace,
        id,
        open.dim,
        open.budget,
        open.policy,
        open.decoded,
    )
    .await?;
    let sparse = if open.with_sparse {
        SparseRows::open(
            open.store,
            open.namespace,
            id,
            segment.doc_count(),
            open.budget,
        )
        .await?
    } else {
        None
    };
    Ok((segment, sparse))
}

/// Document block `block` of a pruned segment: every row's id, so each row
/// keeps its place in the merge, and the attributes of the rows in
/// `candidates` (ascending) only; the other rows are `NonMatchingDoc`,
/// which an index's superset guarantee rules out. A block holding
/// no candidate costs its id block alone; one holding some sends
/// the id block and the attribute block together, as `doc_block` does.
pub(crate) async fn pruned_block(
    segment: &RangedSegment<'_>,
    candidates: &[u32],
    block: usize,
) -> Result<Vec<Entry>> {
    let first = first_row(block);
    let end = u32::try_from(segment.doc_count())
        .unwrap_or(u32::MAX)
        .min(first.saturating_add(u32::try_from(BLOCK_ROWS).unwrap_or(u32::MAX)));
    let wanted = &candidates
        [candidates.partition_point(|&r| r < first)..candidates.partition_point(|&r| r < end)];
    let (ids, attrs) = futures::try_join!(segment.id_block(block), async {
        if wanted.is_empty() {
            Ok(Vec::new())
        } else {
            segment.attrs_of(wanted).await
        }
    })?;
    Ok(entries_of(ids, first, wanted, attrs))
}

/// Every row of a block as an entry: the rows in `wanted` (ascending, with
/// their `attrs`) are documents, the others `NonMatchingDoc`.
fn entries_of(
    ids: Vec<String>,
    first: u32,
    wanted: &[u32],
    attrs: Vec<Option<Value>>,
) -> Vec<Entry> {
    let mut matched = wanted.iter().copied().zip(attrs).peekable();
    ids.into_iter()
        .zip(first..)
        .map(|(id, row)| {
            let body = match matched.next_if(|(r, _)| *r == row) {
                Some((_, attrs)) => Body::Doc(Attrs::Parsed(attrs)),
                None => Body::NonMatchingDoc,
            };
            Entry {
                id,
                body,
                row: Some(row),
            }
        })
        .collect()
}

/// Document block `block` of a version 3 segment whose zone maps could not
/// decide `predicate`: its ids
/// and only the columns the predicate reads are fetched, the rows of those
/// that match (among `candidates`, if an index narrowed them) get their
/// attributes read whole, and every other row is `NonMatchingDoc`. A block no
/// row of which matches costs its ids and those columns, not its attribute
/// block.
async fn evaluated_block(
    segment: &RangedSegment<'_>,
    evaluate: &Evaluate<'_>,
    candidates: Option<&[u32]>,
    block: usize,
) -> Result<Vec<Entry>> {
    let first = first_row(block);
    let (ids, columns) = futures::try_join!(
        segment.id_block(block),
        segment.columns_of(block, &evaluate.fields)
    )?;
    if ids.len() != columns.rows() {
        return Err(segment.corrupt("an id block and its attribute block differ in length"));
    }
    let within = match candidates {
        None => Bitmap::full(ids.len()),
        Some(candidates) => {
            let mut within = Bitmap::new(ids.len());
            let end = first.saturating_add(u32::try_from(ids.len()).unwrap_or(u32::MAX));
            candidates[candidates.partition_point(|&r| r < first)..]
                .iter()
                .take_while(|&&r| r < end)
                .for_each(|&r| within.set((r - first) as usize));
            within
        }
    };
    let hits = evaluate
        .predicate
        .on_columns_planned(&columns, &within, &evaluate.passes);
    let wanted: Vec<u32> = (0..ids.len())
        .filter(|&i| hits.get(i))
        .map(|i| first + i as u32)
        .collect();
    let attrs = if wanted.is_empty() {
        Vec::new()
    } else {
        segment.attrs_of(&wanted).await?
    };
    Ok(entries_of(ids, first, &wanted, attrs))
}

/// What narrows a page of one segment before its attributes are read.
struct Pruning<'a> {
    /// The rows an attribute index allows.
    candidates: Option<Vec<u32>>,
    /// The zone maps' verdict per block.
    verdicts: Option<Vec<Tri>>,
    /// The predicate and its columns, for evaluating a `Maybe` block.
    evaluate: Option<Evaluate<'a>>,
}

/// A version 2 or 3 segment read from its first block past `after` up to its
/// last block that can hold an id at or below `until`: a range scan never
/// reads, nor holds, a window of a segment its range does not reach.
fn segment_source<'a>(
    segment: RangedSegment<'a>,
    sparse: Option<SparseRows<'a>>,
    after: Option<&str>,
    until: Option<&str>,
    mode: Mode,
    pruning: Pruning<'a>,
) -> Source<'a> {
    let Pruning {
        candidates,
        verdicts,
        evaluate,
    } = pruning;
    let (doc_start, tombstone_start) = match after {
        Some(after) => (
            segment.first_doc_block_after(after),
            segment.first_tombstone_block_after(after),
        ),
        None => (0, 0),
    };
    let (doc_end, tombstone_end) = match until {
        Some(until) => (
            segment.doc_blocks_through(until),
            segment.tombstone_blocks_through(until),
        ),
        None => (segment.doc_block_count(), segment.tombstone_block_count()),
    };
    let buffer = || match mode {
        Mode::Page => Buffer::Entries(VecDeque::new()),
        Mode::Forward { .. } => Buffer::Window(Window {
            ids: IdColumn::default(),
            attrs: None,
            first_row: 0,
            next: 0,
        }),
    };
    let docs = Side {
        next_block: doc_start,
        blocks: doc_end,
        buffer: buffer(),
        last: None,
    };
    let tombstones = Side {
        next_block: tombstone_start,
        blocks: tombstone_end,
        buffer: buffer(),
        last: None,
    };
    Source::Segment(Box::new(SegmentSource {
        segment,
        sparse,
        docs,
        tombstones,
        after: after.map(str::to_owned),
        mode,
        candidates,
        verdicts,
        evaluate,
    }))
}

/// A layer's documents and tombstones after the cursor, merged in id order.
fn layer_entries(layer: &Layer, after: Option<&str>) -> VecDeque<Entry> {
    let past = |id: &str| after.is_none_or(|after| id > after);
    let mut docs = layer
        .sorted_docs()
        .into_iter()
        .filter(|d| past(&d.id))
        .peekable();
    let mut tombstones = layer
        .sorted_tombstones()
        .into_iter()
        .filter(|id| past(id))
        .peekable();
    let mut entries = VecDeque::new();
    loop {
        let take_doc = match (docs.peek(), tombstones.peek()) {
            (Some(d), Some(t)) => d.id.as_str() <= *t,
            (Some(_), None) => true,
            (None, Some(_)) => false,
            (None, None) => break,
        };
        if take_doc {
            if let Some(d) = docs.next() {
                entries.push_back(Entry {
                    id: d.id.clone(),
                    body: Body::Doc(Attrs::Parsed(d.attrs.clone())),
                    row: None,
                });
            }
        } else if let Some(id) = tombstones.next() {
            entries.push_back(Entry {
                id: id.to_owned(),
                body: Body::Tombstone,
                row: None,
            });
        }
    }
    entries
}

#[cfg(test)]
mod tests {
    use object_store::ObjectStoreExt;
    use object_store::memory::InMemory;

    use super::*;
    use crate::document::{Document, WalOp};
    use crate::segment;

    /// The linear merge `filter::run` used before the heap, kept as the
    /// reference: the smallest front id, the newest holder decides, every
    /// older copy is dropped.
    fn reference_merge(mut sources: Vec<VecDeque<Entry>>) -> Vec<String> {
        let mut out = Vec::new();
        loop {
            let Some(smallest) = sources
                .iter()
                .filter_map(VecDeque::front)
                .map(|e| e.id.clone())
                .min()
            else {
                return out;
            };
            let mut decided = false;
            for at in (0..sources.len()).rev() {
                if sources[at].front().is_none_or(|e| e.id != smallest) {
                    continue;
                }
                let Some(entry) = sources[at].pop_front() else {
                    continue;
                };
                if decided {
                    continue;
                }
                decided = true;
                if matches!(entry.body, Body::Doc(_)) {
                    out.push(entry.id);
                }
            }
        }
    }

    fn random_sources(seed: u64) -> Vec<VecDeque<Entry>> {
        let mut x = seed;
        let mut next = move |n: u64| {
            x = x
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            (x >> 33) % n
        };
        (0..1 + next(6))
            .map(|_| {
                let mut ids: Vec<u64> = (0..next(40)).map(|_| next(60)).collect();
                ids.sort_unstable();
                ids.dedup();
                ids.into_iter()
                    .map(|n| Entry {
                        row: None,
                        id: format!("k{n:03}"),
                        body: match next(4) {
                            0 => Body::Tombstone,
                            1 => Body::NonMatchingDoc,
                            _ => Body::Doc(Attrs::Parsed(Some(serde_json::json!({ "n": n })))),
                        },
                    })
                    .collect()
            })
            .collect()
    }

    fn copy(entries: &VecDeque<Entry>) -> VecDeque<Entry> {
        entries
            .iter()
            .map(|e| Entry {
                row: e.row,
                id: e.id.clone(),
                body: match &e.body {
                    Body::Doc(Attrs::Parsed(attrs)) => Body::Doc(Attrs::Parsed(attrs.clone())),
                    Body::Doc(Attrs::Stored(stored)) => Body::Doc(Attrs::Stored(stored.clone())),
                    Body::Tombstone => Body::Tombstone,
                    Body::NonMatchingDoc => Body::NonMatchingDoc,
                },
            })
            .collect()
    }

    #[tokio::test]
    async fn the_heap_merge_equals_the_linear_merge() {
        for seed in 0..500 {
            let sources = random_sources(seed);
            let want = reference_merge(sources.iter().map(copy).collect());
            let mut merge = Merge::from_sources(
                sources
                    .into_iter()
                    .map(|entries| Source::Layer {
                        layer: Arc::new(Layer::new()),
                        entries,
                        label: String::new(),
                    })
                    .collect(),
            );
            let mut got = Vec::new();
            while let Some(winner) = merge.next().await.expect("next") {
                got.push(winner.id);
            }
            assert_eq!(got, want, "seed {seed}");
        }
    }

    fn forward_layer(docs: usize, tombstones: usize) -> Layer {
        let mut layer = Layer::new();
        for i in 0..docs {
            layer.apply(WalOp::Upsert(Document {
                id: format!("d{i:05}"),
                vector: vec![i as f32, 1.0],
                attrs: (i % 3 != 0).then(|| serde_json::json!({ "n": i })),
                sparse: None,
            }));
        }
        for i in 0..tombstones {
            layer.apply(WalOp::Delete(format!("d{:05}", i * 7 + docs)));
        }
        layer
    }

    /// Every winner of a merge over one stored segment, attributes parsed.
    async fn winners(
        store: &InMemory,
        mode: Mode,
        after: Option<&str>,
    ) -> Vec<(String, Option<Value>)> {
        let budget = ReadBudget::unlimited();
        let policy = FetchPolicy::local();
        let attr_indexes = BTreeMap::new();
        let attrs = AttrSchema::new();
        let open = Open {
            store,
            namespace: "ns",
            dim: 2,
            budget: &budget,
            policy: &policy,
            attr_indexes: &attr_indexes,
            attrs: &attrs,
            decoded: None,
            predicate: None,
            after,
            until: None,
            mode,
            with_sparse: false,
        };
        let ids = vec!["seg".to_string()];
        let mut merge = Merge::open(&open, &ids, async { Ok(Arc::new(Layer::new())) })
            .await
            .expect("open");
        let mut out = Vec::new();
        while let Some(winner) = merge.next().await.expect("next") {
            let attrs = merge.parse(winner.source, winner.attrs).expect("attrs");
            out.push((winner.id, attrs));
        }
        out
    }

    #[tokio::test]
    async fn forward_windows_read_what_page_blocks_read() {
        let store = InMemory::new();
        let bytes = segment::encode_as(&forward_layer(1000, 50), 2, 2).expect("encode");
        store
            .put(&segment::segment_path("ns", "seg"), bytes.into())
            .await
            .expect("put");
        for after in [None, Some("d00600"), Some("d00999"), Some("e")] {
            let page = winners(&store, Mode::Page, after).await;
            for window_bytes in [0, 1, 4_000, SCAN_WINDOW_MAX] {
                let forward = winners(&store, Mode::Forward { window_bytes }, after).await;
                assert_eq!(forward, page, "after {after:?}, window {window_bytes}");
            }
        }
    }

    #[test]
    fn window_bytes_clamps() {
        assert_eq!(window_bytes(1 << 30, 1), SCAN_WINDOW_MAX);
        assert_eq!(window_bytes(4_000, 10), 100);
        assert_eq!(window_bytes(0, 0), 0);
    }
}