tinystore 0.10.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
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
//! A search, in one snapshot of search.db: the index's statistics, its
//! words' keys, their lists from their pieces in each segment, the best of them,
//! the best of its vectors, the two summed, and the hits' values.
//!
//! The read lasts the whole search rather than fetching its bytes alone:
//! which block a search opens next depends on the scores of those it opened,
//! and the blocks' bounds skip most of them. A search's statements are
//! point and short range reads, and search-compact measured them at 14–16
//! ms at p99 over a million documents, so the read stays as short. A search
//! by a vector reads every code of the index in it, a scan whose work is the
//! fetch itself.

use std::collections::{HashMap, HashSet};
use std::ffi::CStr;
use std::ops::Range;
use std::sync::Arc;

use rusqlite::blob::Blob;
use rusqlite::{Connection, MAIN_DB, OptionalExtension};

use super::analyzer::{self, Word};
use super::clusters::{self, Phase, Probe};
use super::correct::Corrector;
use super::execute::{Fetch, List, best, best_of, held_by_all};
use super::filter::{self, Docs, Reader};
use super::hybrid::{self, HALF};
use super::kept::{Chunk, Gone, Kept, KeptPiece, Listed, Moment, NORMS};
use super::layouts;
use super::legacy;
use super::matches::{Ask, Sought};
use super::packed::{self, Directory};
use super::postings::Posting;
use super::score::{PREFIXED, Part, average, idf, score};
use super::segments::{self, Segment};
use super::settings::Settings;
use super::vectors::{self, Among, Question, Scan};
use crate::sqlite::sql_error;
use crate::sync::lock;
use crate::{Error, Memory, Result};

const READ_INDEX: &str =
    "select documents, normed, gone_version, words_version, lists_version from _tinystore_search_indexes where id = ?1";
const READ_PARTS: &str = "select part, tokens from _tinystore_search_parts where index_id = ?1";
const FIND_KEY: &str =
    "select id, documents from _tinystore_search_keys where index_id = ?1 and part = ?2 and term = ?3";
/// The words of a part that start with a prefix and are longer, between
/// `?3` and `?4`, the most held first: a range of the keys' index by term,
/// read to its end, since how many documents hold a word is no order that
/// index keeps. A word only segments not folded hold counts none in its
/// row, and comes after those whose rows count them.
const FIND_PREFIXED: &str = "select id, documents, term from _tinystore_search_keys as k
    where index_id = ?1 and part = ?2 and term > ?3 and term < ?4 and (documents > 0 or exists (select 1
        from _tinystore_search_segments as s join _tinystore_search_pieces as p on p.segment = s.id and p.key = k.id
        where s.index_id = ?1 and s.folded = 0))
    order by documents desc, term limit cast(?5 as integer)";
const BEGINS_A_WORD: &str = "select exists (select 1 from _tinystore_search_keys as k
    where index_id = ?1 and part = ?2 and term > ?3 and term < ?4 and (documents > 0 or exists (select 1
        from _tinystore_search_segments as s join _tinystore_search_pieces as p on p.segment = s.id and p.key = k.id
        where s.index_id = ?1 and s.folded = 0)))";
const RUNS: &CStr = c"_tinystore_search_runs";
const BLOCKS: &CStr = c"blocks";
const READ_HIT: &str = "select id, value from _tinystore_search_docs where index_id = ?1 and doc = ?2";

/// The words a prefix is read as in a field at most, those most documents
/// hold: each one's postings are read whole before the search scores.
const MOST_PREFIXED: usize = 64;
/// The letters a word needs before a `prefix` search reads it as the start
/// of others: one letter would read every word that starts with it.
const LEAST_PREFIX: usize = 2;
/// The words a search that reads every word as a prefix reads so at most:
/// each one reads the postings of up to 64 words in each field.
const MOST_PREFIXES: usize = 8;
/// A filter that passes no more than one document in this many of an
/// index's has them scored alone, rather than crossed out of a search of
/// every one; a search by a vector reads their codes by their numbers
/// rather than scanning every code. Over 100,000 documents, searches by
/// words took as long both ways at 1 in 32 and by a vector between 1 in 2
/// and 1 in 8 (`where_a_filter_is_scored_alone_takes` in `search::index`).
const NARROW_WORDS: u64 = 32;
const NARROW_VECTORS: u64 = 4;

/// A search's text as the analyzer normalized it, its words found in it,
/// its vector, how it combines the two if it says, and the hits it asks for.
#[derive(Clone, Debug)]
pub(crate) struct Query {
    pub(crate) normal: String,
    pub(crate) words: Vec<Word>,
    pub(crate) vector: Option<Question>,
    pub(crate) vector_weight: Option<f64>,
    pub(crate) rerank: bool,
    /// The least cosine a document's vector has for the search's vector to
    /// find it.
    pub(crate) min_similarity: Option<f64>,
    /// Which words the search asks read as the start of others too, as
    /// [`prefixes`] reads them.
    pub(crate) prefix: Prefix,
    /// What the search asks of its hits' matches, when it asks where they
    /// matched.
    pub(crate) matches: Option<Ask>,
    pub(crate) filter: Option<filter::Asked>,
    pub(crate) offset: usize,
    pub(crate) limit: usize,
}

/// Which of a search's words it reads as the start of others too.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Prefix {
    /// None: each word is whole.
    #[default]
    Whole,
    /// The last, while it may still be being typed.
    Last,
    /// Every word of two letters or more, the first eight, whatever follows
    /// it, as a reader who begins each word types: `лин алг`. A document
    /// that holds a word for each comes before one that does not.
    Every,
}

/// A query of an index, and what the index keeps for it.
#[derive(Debug)]
pub(crate) struct Asked<'a> {
    pub(crate) index: i64,
    pub(crate) settings: &'a Settings,
    pub(crate) kept: &'a Kept,
    pub(crate) memory: &'a Arc<Memory>,
    pub(crate) query: Query,
}

/// What a search found, and the search's text as it was read, when a word
/// was read as another.
#[derive(Debug)]
pub(crate) struct Answer {
    pub(crate) hits: Vec<Ranked>,
    pub(crate) corrected: Option<String>,
    /// The index's words changed since its dictionary was built.
    pub(crate) behind: bool,
    /// What the hits' matches are read against after the read, when the
    /// search asks where they matched and found them by its words.
    pub(crate) sought: Option<Sought>,
}

/// A document a search answers: its id, value as JSON and score, the score
/// its words gave it where they found it, and its vector's cosine with the
/// search's where both have one.
#[derive(Debug)]
pub(crate) struct Ranked {
    pub(crate) id: String,
    pub(crate) value: Vec<u8>,
    pub(crate) score: f64,
    pub(crate) text_score: Option<f64>,
    pub(crate) similarity: Option<f64>,
}

/// What each half of a search gave the documents it found.
#[derive(Default)]
struct Halves {
    words: HashMap<u32, f64>,
    cosines: HashMap<u32, f64>,
}

impl Halves {
    /// Keeps what the words found, and hands it on.
    fn words(&mut self, found: Vec<(f64, u32)>) -> Vec<(f64, u32)> {
        self.words.extend(found.iter().map(|(score, doc)| (*doc, *score)));
        found
    }

    /// Keeps what the vector found, and hands it on.
    fn vectors(&mut self, found: Vec<(f64, u32)>) -> Vec<(f64, u32)> {
        self.cosines.extend(found.iter().map(|(cosine, doc)| (*doc, *cosine)));
        found
    }
}

/// What the vector found, without the documents under the search's floor:
/// they add nothing to a sum rather than the least of its half's scale.
fn floored(found: Vec<(f64, u32)>, asked: &Asked<'_>) -> Vec<(f64, u32)> {
    match asked.query.min_similarity {
        Some(floor) => found.into_iter().filter(|(cosine, _)| *cosine >= floor).collect(),
        None => found,
    }
}

/// How a search makes its hits of its words and its vector.
#[derive(Clone, Copy, Debug)]
enum Mode {
    Words,
    Vector,
    /// Each half's scores scaled and summed, the vector's at this weight.
    Sum(f64),
    /// The words' hits ordered by their vectors.
    Rerank,
}

pub(crate) fn search(connection: &Connection, mut asked: Asked<'_>) -> Result<Answer> {
    let (moment, documents, words_version) = moment(connection, asked.index)?;
    let mode = mode(&asked)?;
    let mut behind = false;
    let swapped = layouts::swap(connection, &mut asked)?;
    let corrected = correct(connection, &mut asked, (words_version, &mut behind), swapped)?;
    let k = asked.query.offset + asked.query.limit;
    let both = k.max(HALF);
    let passing = passing(connection, &asked, moment)?;
    let held = Held { moment, documents, passing: passing.as_deref() };
    let mut halves = Halves::default();
    let ranked = match mode {
        Mode::Words => halves.words(by_words(connection, &asked, held, k)?),
        Mode::Vector => halves.vectors(floored(by_vector(connection, &asked, held, k)?, &asked)),
        Mode::Sum(weight) => {
            let words = halves.words(by_words(connection, &asked, held, both)?);
            let vectors = halves.vectors(floored(by_vector(connection, &asked, held, both)?, &asked));
            hybrid::fuse(&words, &vectors, weight)
        }
        Mode::Rerank => {
            let words = halves.words(by_words(connection, &asked, held, both)?);
            let docs: Vec<u32> = words.iter().map(|(_, doc)| *doc).collect();
            halves.cosines = vectors::cosines(connection, asked.index, question(&asked)?, &docs)?;
            hybrid::rerank(&words, &halves.cosines)
        }
    };
    let page: Vec<(f64, u32)> = ranked.into_iter().skip(asked.query.offset).take(asked.query.limit).collect();
    // a hit the words alone found, or a search whose weight left its vector
    // out, has its cosine read for the page alone
    if let (Mode::Sum(_) | Mode::Words, Some(question)) = (mode, &asked.query.vector) {
        let unread: Vec<u32> =
            page.iter().map(|(_, doc)| *doc).filter(|doc| !halves.cosines.contains_key(doc)).collect();
        halves.cosines.extend(vectors::cosines(connection, asked.index, question, &unread)?);
    }
    let hits = page.into_iter().map(|(score, doc)| hit(connection, asked.index, doc, score, &halves));
    let hits = hits.collect::<Result<_>>()?;
    let sought = match &asked.query.matches {
        Some(ask) if !matches!(mode, Mode::Vector) => Some(sought(connection, &asked, ask)?),
        _ => None,
    };
    Ok(Answer { hits, corrected, behind, sought })
}

/// The keys the search's words found documents by, each with the place of
/// its query word: every form of each word as [`lists`] reads it, and in
/// each field the words each prefix chose, as [`prefixed`] chooses them.
fn sought(connection: &Connection, asked: &Asked<'_>, ask: &Ask) -> Result<Sought> {
    let mut sought = Sought::new(ask.clone(), &asked.settings.fields);
    for (at, word) in asked.query.words.iter().enumerate() {
        for form in forms(std::slice::from_ref(word), asked.settings) {
            sought.key(form, at);
        }
    }
    for at in prefixes(&asked.query) {
        let word = &asked.query.words[at];
        let Some(past) = past(&word.text) else { continue };
        let typed = (at, word.text.chars().count());
        for field in &asked.settings.fields {
            let part = Part::written(field.number);
            for term in terms_starting(connection, asked.index, part, (&word.text, &past))? {
                sought.begun((part, term), typed);
            }
        }
    }
    Ok(sought)
}

/// How the search makes its hits, from what it gives and what its index
/// says unless it does.
fn mode(asked: &Asked<'_>) -> Result<Mode> {
    let query = &asked.query;
    let Some(question) = &query.vector else { return Ok(Mode::Words) };
    let Some(vectors) = asked.settings.vectors else {
        return Err(Error::invalid("a search by a vector of an index without vectors"));
    };
    if question.dimensions() != vectors.dimensions {
        return Err(Error::invalid(format!(
            "a vector of {} dimensions where the index holds {}",
            question.dimensions(),
            vectors.dimensions
        )));
    }
    if query.words.is_empty() && !query.rerank {
        return Ok(Mode::Vector);
    }
    let hybrid = asked.settings.hybrid;
    let weight = match query.vector_weight {
        Some(weight) => weight,
        None if query.min_similarity.is_some() && (query.rerank || hybrid.rerank) => {
            return Err(Error::invalid(
                "a similarity floor keeps what a vector finds, and a rerank finds nothing by it",
            ));
        }
        None if query.rerank || hybrid.rerank => return Ok(Mode::Rerank),
        None => hybrid.vector_weight,
    };
    // A weight of 0 is the words alone and of 1 the vector alone, each with
    // its own scores, rather than a sum whose other half adds documents at 0.
    Ok(match weight {
        0.0 => Mode::Words,
        1.0 => Mode::Vector,
        weight => Mode::Sum(weight),
    })
}

fn question<'a>(asked: &'a Asked<'_>) -> Result<&'a Question> {
    asked.query.vector.as_ref().ok_or_else(|| Error::internal("a search by its vector has none"))
}

/// What a snapshot holds of an index: the moment of its kept parts, how
/// many documents, and those the search's filter passes, if it has one.
#[derive(Clone, Copy)]
struct Held<'a> {
    moment: Moment,
    documents: u64,
    passing: Option<&'a [u32]>,
}

/// The documents the search's filter passes, in their order; none when it
/// has no filter or one that passes every document.
fn passing(connection: &Connection, asked: &Asked<'_>, moment: Moment) -> Result<Option<Vec<u32>>> {
    let Some(conditions) = &asked.query.filter else { return Ok(None) };
    let gone = asked.kept.gone(connection, moment)?;
    let reader = Reader { connection, index: asked.index, settings: asked.settings, gone: &gone.docs };
    Ok(match reader.passing(conditions)? {
        Docs::All => None,
        Docs::Only(docs) => Some(docs),
    })
}

/// Whether a filter that passes `passing` of `documents` passes few
/// enough, by `share`, to read them alone.
fn narrow(passing: usize, documents: u64, share: u64) -> bool {
    #[cfg(test)]
    if let Some(narrow) = NARROW.get() {
        return narrow;
    }
    (passing as u64).saturating_mul(share) <= documents
}

#[cfg(test)]
thread_local! {
    /// Every filter of this thread's searches on one path, for a timing.
    pub(crate) static NARROW: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

/// The best `k` by the search's words, with their scores.
fn by_words(connection: &Connection, asked: &Asked<'_>, held: Held<'_>, k: usize) -> Result<Vec<(f64, u32)>> {
    let Held { moment, documents, .. } = held;
    let stats = Stats {
        documents,
        tokens: tokens(connection, asked.index)?,
        gone: asked.kept.gone(connection, moment)?,
        segments: segments::of_index(connection, asked.index)?,
    };
    let mut source = Source::new(connection, asked, moment, &stats);
    let Lists { mut lists, words } = lists(connection, asked, &stats, &mut source)?;
    let found = match asked.query.prefix {
        Prefix::Every => holding_every_word_first((&mut lists, &words), &mut source, held, k)?,
        Prefix::Whole | Prefix::Last => ranked(&mut lists, &mut source, held, k)?,
    };
    #[cfg(test)]
    check(connection, asked, (&stats, held), (&found, k))?;
    Ok(found.into_iter().map(|(points, doc)| (score(points), doc)).collect())
}

/// The best `k` by the lists' points, of the documents a filter passes
/// scored alone when it passes few.
fn ranked(lists: &mut [List], source: &mut Source<'_>, held: Held<'_>, k: usize) -> Result<Vec<(u64, u32)>> {
    match held.passing {
        Some(docs) if narrow(docs.len(), held.documents, NARROW_WORDS) => best_of(lists, source, docs, k),
        passing => best(lists, source, k, passing),
    }
}

/// The best `k` of the documents that hold a word for each of the search's
/// words, then the best of the rest: the first with what every list adds at
/// most added to their points, which no document of the rest reaches, so
/// that the points still descend. A search of one word holds it in every
/// hit, and finds none of the rest.
///
/// ```text
/// лин алг  →  Линейная алгебра                       лин…, алг…   its points + above
///             Проектирование технологических линий   лин…         its points
///             Алгоритмизация и программирование      алг…         its points
/// ```
///
/// The best `k − m` of the rest, where `m < k` hold every word, are among
/// the best `k` of all, since at most `m` of the first come before them.
fn holding_every_word_first(
    (lists, words): (&mut [List], &[Vec<usize>]),
    source: &mut Source<'_>,
    held: Held<'_>,
    k: usize,
) -> Result<Vec<(u64, u32)>> {
    let above = lists.iter().fold(0_u64, |sum, list| sum.saturating_add(list.most()));
    let raised = |found: Vec<(u64, u32)>| found.into_iter().map(|(points, doc)| (points.saturating_add(above), doc));
    if words.len() < 2 {
        return Ok(raised(ranked(lists, source, held, k)?).collect());
    }
    let every = held_by_all(lists, words, source, held.passing)?;
    let holding = Held { passing: Some(&every), ..held };
    let mut first: Vec<(u64, u32)> = raised(ranked(&mut lists.to_vec(), source, holding, k)?).collect();
    if first.len() < k {
        let rest = ranked(lists, source, held, k)?.into_iter().filter(|(_, doc)| every.binary_search(doc).is_err());
        first.extend(rest.take(k - every.len()));
    }
    Ok(first)
}

/// The best `k` from the index's clusters, when it has a `recall` and its
/// clusters serve; none while they do not, and the search is exact.
fn by_clusters(
    connection: &Connection,
    asked: &Asked<'_>,
    held: Held<'_>,
    k: usize,
) -> Result<Option<Vec<(f64, u32)>>> {
    let Some(vectors) = asked.settings.vectors.filter(|vectors| vectors.recall.is_some()) else { return Ok(None) };
    let state = clusters::state(connection, asked.index)?;
    if state.phase != Phase::Serving || state.probes <= 0 {
        return Ok(None);
    }
    let at = (asked.index, state.version, vectors.dimensions);
    let kept = clusters::kept(&asked.kept.clusters, connection, at)?;
    let question = question(asked)?;
    let probe = Probe {
        index: asked.index,
        clusters: &kept,
        question,
        k,
        probes: state.probes as usize,
        rescored: state.rescored as usize,
        passing: held.passing,
    };
    clusters::best(connection, &probe).map(Some)
}

/// The best `k` by the search's vector, with their cosines.
fn by_vector(connection: &Connection, asked: &Asked<'_>, held: Held<'_>, k: usize) -> Result<Vec<(f64, u32)>> {
    let among = match held.passing {
        None => Among::Every,
        Some(docs) if narrow(docs.len(), held.documents, NARROW_VECTORS) => Among::Only(docs),
        Some(docs) => Among::Crossed(docs),
    };
    if !matches!(among, Among::Only(_))
        && let Some(found) = by_clusters(connection, asked, held, k)?
    {
        return Ok(found);
    }
    let scan = Scan { index: asked.index, question: question(asked)?, k, among };
    let found = vectors::best(connection, &scan)?;
    #[cfg(test)]
    if CHECKED.get() {
        let every = vectors::every(connection, &scan)?;
        if every != found {
            return Err(Error::internal(format!("found {found:?} where every vector gives {every:?}")));
        }
    }
    Ok(found)
}

/// The moment of the index this snapshot holds, its documents and how far
/// its words have changed.
fn moment(connection: &Connection, index: i64) -> Result<(Moment, u64, i64)> {
    let mut select = connection.prepare_cached(READ_INDEX).map_err(|error| sql_error("read an index", error))?;
    let row = select.query_row([index], |row| {
        let moment = Moment { index, normed: row.get(1)?, gone_version: row.get(2)?, lists_version: row.get(4)? };
        Ok((moment, row.get::<_, i64>(0)?.max(0) as u64, row.get(3)?))
    });
    row.map_err(|error| sql_error("read an index", error))
}

/// What scores a snapshot's postings: how many documents the index holds,
/// how many words each part has in all of them, the documents gone, and
/// the segments its keys' pieces are in.
struct Stats {
    documents: u64,
    tokens: HashMap<Part, u64>,
    gone: Arc<Gone>,
    segments: Vec<Segment>,
}

/// A search's lists, and for each of its words the places among them of
/// the lists that find it.
struct Lists {
    lists: Vec<List>,
    words: Vec<Vec<usize>>,
}

/// The lists of a search's keys, and in each field the list of the words
/// each word it reads as a prefix begins.
fn lists(connection: &Connection, asked: &Asked<'_>, stats: &Stats, source: &mut Source<'_>) -> Result<Lists> {
    let mut found = keyed_lists(connection, asked, (stats, &mut *source))?;
    let mut begun: HashMap<&str, Vec<usize>> = HashMap::new();
    for at in prefixes(&asked.query) {
        let text = asked.query.words[at].text.as_str();
        if !begun.contains_key(text) {
            let mut places = Vec::new();
            for field in &asked.settings.fields {
                let part = Part::written(field.number);
                if let Some(list) = prefixed(connection, asked, (stats, &mut *source), (part, text))? {
                    places.push(found.lists.len());
                    found.lists.push(list);
                }
            }
            begun.insert(text, places);
        }
        found.words[at].extend(&begun[text]);
    }
    Ok(found)
}

/// The lists of the keys a search's words are found by, each once, and
/// which find each word.
fn keyed_lists(
    connection: &Connection,
    asked: &Asked<'_>,
    (stats, source): (&Stats, &mut Source<'_>),
) -> Result<Lists> {
    let mut lists = Vec::new();
    let mut placed: HashMap<(Part, String), usize> = HashMap::new();
    for form in forms(&asked.query.words, asked.settings) {
        if let Some(list) = list(connection, asked, (stats, &mut *source), &form)? {
            placed.insert(form, lists.len());
            lists.push(list);
        }
    }
    let finding = |word: &Word| {
        forms(std::slice::from_ref(word), asked.settings).iter().filter_map(|form| placed.get(form).copied()).collect()
    };
    Ok(Lists { lists, words: asked.query.words.iter().map(finding).collect() })
}

/// The words a search reads as the start of others too, by their places
/// among its words: its last while it may still be being typed, or every
/// one long enough, the first eight.
pub(super) fn prefixes(query: &Query) -> Vec<usize> {
    let words = &query.words;
    match query.prefix {
        Prefix::Whole => Vec::new(),
        Prefix::Last => {
            words.len().checked_sub(1).filter(|last| halfway(&words[*last], &query.normal)).into_iter().collect()
        }
        Prefix::Every => (0..words.len()).filter(|at| long_enough(&words[*at])).take(MOST_PREFIXES).collect(),
    }
}

/// Whether a word of `normal` may be typed halfway: nothing follows it, not
/// a space nor a mark, and it is long enough to begin few words.
pub(super) fn halfway(word: &Word, normal: &str) -> bool {
    word.at.end == normal.len() && long_enough(word)
}

/// Whether a word is long enough to be read as the start of others.
pub(super) fn long_enough(word: &Word) -> bool {
    word.text.chars().count() >= LEAST_PREFIX
}

#[cfg(test)]
thread_local! {
    static CHECKED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Runs `run` with every search on this thread scoring every posting too, in
/// its own snapshot, and failing unless both answer alike.
#[cfg(test)]
pub(crate) fn checked<T>(run: impl FnOnce() -> T) -> T {
    CHECKED.set(true);
    let ran = run();
    CHECKED.set(false);
    ran
}

#[cfg(test)]
fn check(
    connection: &Connection,
    asked: &Asked<'_>,
    (stats, held): (&Stats, Held<'_>),
    (found, k): (&[(u64, u32)], usize),
) -> Result<()> {
    if !CHECKED.get() {
        return Ok(());
    }
    let mut source = Source::new(connection, asked, held.moment, stats);
    let Lists { mut lists, words } = lists(connection, asked, stats, &mut source)?;
    let every = match asked.query.prefix {
        Prefix::Every => every_by_words(&mut lists, &words, &mut source, (held.passing, k))?,
        Prefix::Whole | Prefix::Last => super::execute::every(&mut lists, &mut source, k, held.passing)?,
    };
    if every != found {
        return Err(Error::internal(format!("found {found:?} where every posting gives {every:?}")));
    }
    Ok(())
}

/// What [`holding_every_word_first`] must answer, scoring every posting: a
/// document that holds a word for each of the search's words has the most
/// every list adds added to its points.
#[cfg(test)]
fn every_by_words(
    lists: &mut [List],
    words: &[Vec<usize>],
    source: &mut Source<'_>,
    (passing, k): (Option<&[u32]>, usize),
) -> Result<Vec<(u64, u32)>> {
    let above = lists.iter().fold(0_u64, |sum, list| sum.saturating_add(list.most()));
    let mut holding: Option<HashSet<u32>> = None;
    for word in words {
        let mut docs = HashSet::new();
        for &at in word {
            docs.extend(lists[at].clone().into_postings(source)?.into_iter().map(|posting| posting.doc));
        }
        holding = Some(match holding {
            Some(held) => held.intersection(&docs).copied().collect(),
            None => docs,
        });
    }
    let holding = holding.unwrap_or_default();
    let mut every = super::execute::every(lists, source, usize::MAX, passing)?;
    for (points, doc) in &mut every {
        if holding.contains(doc) {
            *points = points.saturating_add(above);
        }
    }
    every.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
    every.truncate(k);
    Ok(every)
}

/// How many words each part has in every document.
fn tokens(connection: &Connection, index: i64) -> Result<HashMap<Part, u64>> {
    let failed = |error| sql_error("read an index's lengths", error);
    let mut select = connection.prepare_cached(READ_PARTS).map_err(failed)?;
    let rows = select.query_map([index], |row| Ok((Part(row.get(0)?), row.get::<_, i64>(1)?.max(0) as u64)));
    rows.and_then(Iterator::collect).map_err(failed)
}

/// The keys a search's words are found by, each once: a word as written
/// in every field, its stem among the stems, and its stem as written too.
pub(super) fn forms(words: &[Word], settings: &Settings) -> Vec<(Part, String)> {
    let mut forms: Vec<(Part, String)> = Vec::new();
    for word in words {
        let stem = word.stem.as_deref().unwrap_or(&word.text);
        for field in &settings.fields {
            let (written, stems) = (Part::written(field.number), Part::stems(field.number));
            forms.push((written, word.text.clone()));
            forms.push((stems, stem.to_owned()));
            if word.stem.is_some() {
                forms.push((written, stem.to_owned()));
            }
        }
    }
    let mut seen = HashSet::new();
    forms.retain(|form| seen.insert(form.clone()));
    forms
}

/// A key's id and how many documents its row counts.
fn find(connection: &Connection, index: i64, part: Part, term: &str) -> Result<Option<(i64, i64)>> {
    let mut select = connection.prepare_cached(FIND_KEY).map_err(|error| sql_error("find a key", error))?;
    let found = select.query_row((index, part.0, term), |row| Ok((row.get(0)?, row.get(1)?)));
    let found = found.optional();
    found.map_err(|error| sql_error("find a key", error))
}

/// How many documents hold `word`, a document counted once for each of its keys.
pub(super) fn held(connection: &Connection, asked: &Asked<'_>, word: &Word) -> Result<u64> {
    let segments = segments::of_index(connection, asked.index)?;
    let mut documents = 0;
    for (part, term) in forms(std::slice::from_ref(word), asked.settings) {
        if let Some((key, counted)) = find(connection, asked.index, part, &term)? {
            documents += segments::holding(connection, &segments, key, counted)?;
        }
    }
    Ok(documents)
}

/// Reads each word that matches nothing as its nearest the index holds,
/// and says the search's text as it was read when any was, or when a piece
/// of it was read in another layout, `swapped`.
fn correct(
    connection: &Connection,
    asked: &mut Asked<'_>,
    (version, behind): (i64, &mut bool),
    swapped: bool,
) -> Result<Option<String>> {
    if !asked.settings.typo_tolerance {
        return Ok(swapped.then(|| asked.query.normal.clone()));
    }
    let mut replaced = Vec::new();
    let prefixes = prefixes(&asked.query);
    for at in 0..asked.query.words.len() {
        let word = &asked.query.words[at];
        if word.text.chars().count() < 5 || held(connection, asked, word)? > 0 {
            continue;
        }
        // a word typed halfway is no typo while it begins one the index holds
        if prefixes.contains(&at) && begins_a_word(connection, asked, &word.text)? {
            continue;
        }
        let corrector = corrector(connection, asked, version, behind)?;
        let mut chosen: Option<(u64, Word)> = None;
        for candidate in corrector.candidates(&word.text) {
            let read = Word { stem: analyzer::stem(&candidate), text: candidate, at: word.at.clone() };
            let documents = held(connection, asked, &read)?;
            if documents > chosen.as_ref().map_or(0, |(most, _)| *most) {
                chosen = Some((documents, read));
            }
        }
        if let Some((_, read)) = chosen {
            replaced.push((read.at.clone(), read.text.clone()));
            asked.query.words[at] = read;
        }
    }
    if replaced.is_empty() && !swapped {
        return Ok(None);
    }
    Ok(Some(written(&asked.query.normal, replaced)))
}

/// The search's text with the words read otherwise written in, each over
/// its place, in order. Two pairs of an unspaced run share a grapheme, so
/// of two corrected pairs only the first is written: the second's place
/// overlaps it, and the search reads both all the same.
fn written(normal: &str, replaced: Vec<(Range<usize>, String)>) -> String {
    let mut apart: Vec<(Range<usize>, String)> = Vec::with_capacity(replaced.len());
    for (at, word) in replaced {
        if apart.last().is_none_or(|(last, _)| last.end <= at.start) {
            apart.push((at, word));
        }
    }
    let mut text = normal.to_owned();
    for (at, word) in apart.into_iter().rev() {
        text.replace_range(at, &word);
    }
    text
}

/// The dictionary of the index's words kept, built from this snapshot when
/// none is; `behind` says when the kept one is older than the snapshot.
fn corrector(connection: &Connection, asked: &Asked<'_>, version: i64, behind: &mut bool) -> Result<Arc<Corrector>> {
    if let Some(kept) = lock(&asked.kept.corrector).as_ref() {
        *behind = kept.version != version;
        return Ok(Arc::clone(kept));
    }
    let parts: Vec<Part> = asked.settings.fields.iter().map(|field| Part::written(field.number)).collect();
    let built = Arc::new(Corrector::build(connection, asked.index, version, &parts)?);
    *lock(&asked.kept.corrector) = Some(Arc::clone(&built));
    Ok(built)
}

/// A word's list in a part; nothing when no document holds it.
fn list(
    connection: &Connection,
    asked: &Asked<'_>,
    (stats, source): (&Stats, &mut Source<'_>),
    (part, term): &(Part, String),
) -> Result<Option<List>> {
    let Some(found) = find(connection, asked.index, *part, term)? else { return Ok(None) };
    keyed(connection, asked, (stats, source), (*part, found))
}

/// A key's list, its row counting `documents`: a list a release before
/// 0002 wrote and the head it kept, then its piece in each segment, its
/// blocks by their directory, which `source` keeps to read them by, or its
/// postings in hand; nothing when no document holds it.
fn keyed(
    connection: &Connection,
    asked: &Asked<'_>,
    (stats, source): (&Stats, &mut Source<'_>),
    (part, (key, documents)): (Part, (i64, i64)),
) -> Result<Option<List>> {
    let Some(weight) = asked.settings.weight(part.field()) else { return Ok(None) };
    let within = |error: Error| error.within(format!("key {key}"));
    let (released, listed, holding) =
        pieces(connection, asked, (stats, source.moment), (key, documents)).map_err(within)?;
    if holding == 0 {
        return Ok(None);
    }
    let tokens = stats.tokens.get(&part).copied().unwrap_or(0);
    let scale = part.weight(weight) * idf(stats.documents, holding);
    let mut list = List::new(key, part, scale, average(tokens, stats.documents), Vec::new());
    let gone = &stats.gone.docs;
    onto(&mut list, &released.value.1, source, gone);
    push_held(&mut list, legacy::head(connection, asked.index, key)?, gone);
    for piece in &listed {
        onto(&mut list, &piece.value.1, source, gone);
    }
    Ok((!list.is_empty()).then_some(list))
}

/// A list's or a piece's blocks onto a search's list of its key: by their
/// directory, which `source` keeps to read them by, or in hand.
fn onto(list: &mut List, listed: &Listed, source: &mut Source<'_>, gone: &HashSet<u32>) {
    match listed {
        Listed::Packed(directory, best) => {
            source.place(list.key, list.len(), directory);
            list.reserve(directory.blocks.len());
            for block in &directory.blocks {
                list.push(list.packed(block));
            }
            list.seed(best.iter().filter(|posting| !gone.contains(&posting.doc)));
        }
        Listed::Short(postings) => push_held(list, postings.clone(), gone),
        Listed::Legacy(legacy) => legacy.onto(list),
        Listed::Nothing => {}
    }
}

/// What a key's postings are read from: a list a release before 0002
/// wrote, and its pieces in the order of their documents; and how many
/// documents hold it, its row's `documents` and the counts of its pieces
/// not folded.
fn pieces(
    connection: &Connection,
    asked: &Asked<'_>,
    (stats, moment): (&Stats, Moment),
    (key, documents): (i64, i64),
) -> Result<(KeptPiece, Vec<KeptPiece>, u64)> {
    let kept = (asked.memory, moment);
    let released = asked.kept.legacy(connection, kept, key)?;
    let mut listed = Vec::new();
    let mut holding = documents;
    for segment in &stats.segments {
        if let Some(piece) = asked.kept.piece(connection, kept, segment, key)? {
            if !segment.folded {
                holding += piece.value.0;
            }
            listed.push(piece);
        }
    }
    Ok((released, listed, holding.max(0) as u64))
}

/// The words of `part` that start with `prefix` and are longer, read as one
/// word: the most held of them, their postings joined, a document's
/// frequency the sum of theirs, scored as [`PREFIXED`] of the field's
/// weight by how many documents hold any of them. Their postings are read
/// whole here, so a search skips none of their blocks.
///
/// ```text
/// crypt  →  cryptography 2, cryptanalysis 1, cryptographic 1   one list of the documents holding any
/// ```
fn prefixed(
    connection: &Connection,
    asked: &Asked<'_>,
    (stats, source): (&Stats, &mut Source<'_>),
    (part, prefix): (Part, &str),
) -> Result<Option<List>> {
    let Some(weight) = asked.settings.weight(part.field()) else { return Ok(None) };
    let Some(past) = past(prefix) else { return Ok(None) };
    let mut postings = Vec::new();
    for found in words_starting(connection, asked.index, part, (prefix, &past))? {
        if let Some(list) = keyed(connection, asked, (stats, &mut *source), (part, found))? {
            postings.extend(list.into_postings(source)?);
        }
    }
    let joined = joined(postings);
    if joined.is_empty() {
        return Ok(None);
    }
    let tokens = stats.tokens.get(&part).copied().unwrap_or(0);
    let scale = weight * PREFIXED * idf(stats.documents, joined.len() as u64);
    Ok(Some(List::joined(part, scale, average(tokens, stats.documents), joined)))
}

/// Postings of one part's words, a document once, its frequency the sum of
/// theirs; its length is the part's, the same in each.
fn joined(mut postings: Vec<Posting>) -> Vec<Posting> {
    postings.sort_unstable_by_key(|posting| posting.doc);
    let mut joined: Vec<Posting> = Vec::with_capacity(postings.len());
    for posting in postings {
        match joined.last_mut() {
            Some(last) if last.doc == posting.doc => last.tf = last.tf.saturating_add(posting.tf),
            _ => joined.push(posting),
        }
    }
    joined
}

/// The keys of the words of `part` that start with `prefix` and are longer,
/// those before `past`, with how many documents hold each.
fn words_starting(
    connection: &Connection,
    index: i64,
    part: Part,
    (prefix, past): (&str, &str),
) -> Result<Vec<(i64, i64)>> {
    let failed = |error| sql_error("find the words a prefix begins", error);
    let mut select = connection.prepare_cached(FIND_PREFIXED).map_err(failed)?;
    let most = MOST_PREFIXED as i64;
    let rows = select.query_map((index, part.0, prefix, past, most), |row| Ok((row.get(0)?, row.get(1)?)));
    rows.and_then(Iterator::collect).map_err(failed)
}

/// The words [`words_starting`] chooses, by their text.
fn terms_starting(
    connection: &Connection,
    index: i64,
    part: Part,
    (prefix, past): (&str, &str),
) -> Result<Vec<String>> {
    let failed = |error| sql_error("find the words a prefix begins", error);
    let mut select = connection.prepare_cached(FIND_PREFIXED).map_err(failed)?;
    let most = MOST_PREFIXED as i64;
    let rows = select.query_map((index, part.0, prefix, past, most), |row| row.get(2));
    rows.and_then(Iterator::collect).map_err(failed)
}

/// Whether a field holds a word that starts with `prefix` and is longer.
pub(super) fn begins_a_word(connection: &Connection, asked: &Asked<'_>, prefix: &str) -> Result<bool> {
    let Some(past) = past(prefix) else { return Ok(false) };
    let failed = |error| sql_error("find a word a prefix begins", error);
    let mut select = connection.prepare_cached(BEGINS_A_WORD).map_err(failed)?;
    for field in &asked.settings.fields {
        let part = Part::written(field.number);
        if select.query_row((asked.index, part.0, prefix, &past), |row| row.get(0)).map_err(failed)? {
            return Ok(true);
        }
    }
    Ok(false)
}

/// The least text past every one that starts with `prefix`: its last letter
/// that has a next, as that next, and nothing after it. UTF-8 orders as
/// code points do, and SQLite compares text by its bytes, so the range from
/// `prefix` to this is every word that starts with it. None when every
/// letter is the last there is, which no word holds.
///
/// ```text
/// crypt → crypu     a + U+10FFFF → b
/// ```
fn past(prefix: &str) -> Option<String> {
    let mut letters: Vec<char> = prefix.chars().collect();
    while let Some(last) = letters.pop() {
        if let Some(next) = (u32::from(last) + 1..=u32::from(char::MAX)).find_map(char::from_u32) {
            letters.push(next);
            return Some(letters.into_iter().collect());
        }
    }
    None
}

/// Postings in hand as a list's next block, those of documents gone left out.
fn push_held(list: &mut List, mut postings: Vec<Posting>, gone: &HashSet<u32>) {
    postings.retain(|posting| !gone.contains(&posting.doc));
    if !postings.is_empty() {
        let block = list.in_hand(postings);
        list.push(block);
    }
}

fn hit(connection: &Connection, index: i64, doc: u32, score: f64, halves: &Halves) -> Result<Ranked> {
    let failed = |error| sql_error(format!("read document {doc}"), error);
    let mut select = connection.prepare_cached(READ_HIT).map_err(failed)?;
    let found = select.query_row((index, doc), |row| Ok((row.get(0)?, row.get(1)?))).optional().map_err(failed)?;
    let (id, value) = found.ok_or_else(|| Error::corrupt(format!("document {doc} a search found is not kept")))?;
    let (text_score, similarity) = (halves.words.get(&doc).copied(), halves.cosines.get(&doc).copied());
    Ok(Ranked { id, value, score, text_score, similarity })
}

/// Where a search's blocks come from: a run's at its place through a blob
/// handle a list, or a list a release before 0002 wrote as `legacy.rs` reads
/// it; their lengths from the rows of lengths kept.
struct Source<'a> {
    connection: &'a Connection,
    asked: &'a Asked<'a>,
    moment: Moment,
    gone: &'a HashSet<u32>,
    chunks: HashMap<(Part, u32), Arc<Chunk>>,
    /// The row of lengths read last, which the next posting's length is
    /// nearly always in, found without a hash.
    last: Option<((Part, u32), Arc<Chunk>)>,
    /// The lists of pieces in runs, found by their key among a search's few
    /// lists by a walk rather than a hash, which a block took twice.
    keyed: Vec<Keyed<'a>>,
    bytes: Vec<u8>,
}

/// What a key's list reads its blocks in runs by: each piece's directory,
/// with the place of its first block among the list's, and the list's
/// handle with the run it is on.
struct Keyed<'a> {
    key: i64,
    placed: Vec<(usize, Arc<Directory>)>,
    handle: Option<(i64, Blob<'a>)>,
}

impl Fetch for Source<'_> {
    fn block(&mut self, list: &List, index: usize, out: &mut Vec<Posting>) -> Result<()> {
        let within =
            |error: Error| error.within(format!("key {}: block at document {}", list.key, list.first_of(index)));
        if let Some(placed) = self.placed_at(list.key, index) {
            return self.packed_block(placed, out).map_err(within);
        }
        let pairs = legacy::block(self.connection, list.key, list.first_of(index)).map_err(within)?;
        out.clear();
        out.extend(pairs.into_iter().map(|(doc, tf)| Posting { doc, tf, len: 0 }));
        self.leave_gone(out);
        Ok(())
    }

    fn lengths(&mut self, part: Part, mut postings: &mut [Posting]) -> Result<()> {
        while let Some(first) = postings.first() {
            let chunk = first.doc / NORMS;
            let lengths = self.chunk(part, chunk)?;
            let (these, rest) = postings.split_at_mut(postings.partition_point(|posting| posting.doc / NORMS == chunk));
            for posting in these {
                posting.len = lengths.length(posting.doc);
            }
            postings = rest;
        }
        Ok(())
    }
}

/// Where a block of a piece in runs is: its list's place among the keyed,
/// its piece's among the list's, and its own in the piece.
type Placed = (usize, usize, usize);

impl<'a> Source<'a> {
    fn new(connection: &'a Connection, asked: &'a Asked<'a>, moment: Moment, stats: &'a Stats) -> Source<'a> {
        Source {
            connection,
            asked,
            moment,
            gone: &stats.gone.docs,
            chunks: HashMap::new(),
            last: None,
            keyed: Vec::new(),
            bytes: Vec::new(),
        }
    }

    /// Keeps a piece's directory, its first block at `first` among its key's list's.
    fn place(&mut self, key: i64, first: usize, directory: &Arc<Directory>) {
        let at = match self.keyed.iter().position(|keyed| keyed.key == key) {
            Some(at) => at,
            None => {
                self.keyed.push(Keyed { key, placed: Vec::new(), handle: None });
                self.keyed.len() - 1
            }
        };
        self.keyed[at].placed.push((first, Arc::clone(directory)));
    }

    /// Where block `index` of a key's list is, when a piece in runs holds it.
    fn placed_at(&self, key: i64, index: usize) -> Option<Placed> {
        let at = self.keyed.iter().position(|keyed| keyed.key == key)?;
        let pieces = &self.keyed[at].placed;
        let piece = pieces.partition_point(|(first, _)| *first <= index).checked_sub(1)?;
        let (first, directory) = &pieces[piece];
        (index < first + directory.blocks.len()).then_some((at, piece, index - first))
    }

    /// A block of a run onto `out`, its bytes read at their place through its
    /// list's handle, which moves from run to run rather than a statement a
    /// block: search-fast measured 12 % of p99 so.
    fn packed_block(&mut self, (at, piece, index): Placed, out: &mut Vec<Posting>) -> Result<()> {
        let failed = |error| sql_error("read a run", error);
        let connection = self.connection;
        let keyed = &mut self.keyed[at];
        let directory = &keyed.placed[piece].1;
        let run = directory.runs[directory.run_of(index)].id;
        let handle = match keyed.handle.take() {
            Some((on, mut handle)) if on != run => {
                handle.reopen(run).map_err(failed)?;
                handle
            }
            Some((_, handle)) => handle,
            None => connection.blob_open(MAIN_DB, RUNS, BLOCKS, run, true).map_err(failed)?,
        };
        let handle = &keyed.handle.insert((run, handle)).1;
        let lying = directory.bytes_of(index, handle.len())?;
        self.bytes.resize(lying.len(), 0);
        handle.read_at_exact(&mut self.bytes, lying.start).map_err(failed)?;
        packed::unpack(&self.bytes, directory.blocks[index].first, out)?;
        self.leave_gone(out);
        Ok(())
    }

    /// Leaves out of a block's postings those of documents gone.
    fn leave_gone(&self, postings: &mut Vec<Posting>) {
        if !self.gone.is_empty() {
            postings.retain(|posting| !self.gone.contains(&posting.doc));
        }
    }

    /// The row of `part`'s lengths that holds `chunk`.
    fn chunk(&mut self, part: Part, chunk: u32) -> Result<&Chunk> {
        let last = match self.last.take() {
            Some(last) if last.0 == (part, chunk) => last,
            _ => ((part, chunk), self.read_chunk(part, chunk)?),
        };
        Ok(&self.last.insert(last).1)
    }

    fn read_chunk(&mut self, part: Part, chunk: u32) -> Result<Arc<Chunk>> {
        if let Some(read) = self.chunks.get(&(part, chunk)) {
            return Ok(Arc::clone(read));
        }
        let read = self.asked.kept.chunk(self.connection, self.asked.memory, self.moment, (part, chunk))?;
        self.chunks.insert((part, chunk), Arc::clone(&read));
        Ok(read)
    }
}

#[cfg(test)]
mod tests {
    use super::past;

    #[test]
    fn past_a_prefix_is_the_least_text_no_word_it_begins_reaches() {
        assert_eq!(past("crypt").as_deref(), Some("crypu"));
        assert_eq!(past("крипто").as_deref(), Some("криптп"));
        // a surrogate is no letter, and the last letter there is has no next
        assert_eq!(past("\u{d7ff}").as_deref(), Some("\u{e000}"));
        assert_eq!(past("a\u{10ffff}").as_deref(), Some("b"));
        assert_eq!(past("\u{10ffff}"), None);
        let begun = ["crypt", "cryptography", "crypt\u{10ffff}"];
        assert!(begun.iter().all(|word| *word < past("crypt").unwrap().as_str()));
    }
}