tinystore 0.12.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
//! Reads: the events of a range that meet every condition given, a page at a
//! time, in the order of their times.
//!
//! ```text
//! pick rows by their times ─► fetch their bodies ─► parse ─► keep what matches ─► order ─► cut a window
//! └────────── one read of the file ──────────┘   └────────────────── after it ──────────────────┘
//! ```
//!
//! An event is in a head row until its stream is packed and in a block after
//! it, and a read picks among both by the same rule. A block whose segment
//! lacks a name or a key the read asks for, or whose filters say it holds
//! no trace or id it asks for, is passed without its body being fetched; a
//! block fetched has the columns the read asks about read first, and its
//! others only when an event in it may be kept.
//!
//! A window is what one read of the file fetches: rows up to a page's events
//! or one read's rows and bytes, and of them the events that match, which
//! may be none, as one user's events behind every other user's. A page reads
//! windows on until it holds its limit of events that match or the range
//! ends. A page, `all` and the counts read several windows at once while
//! they come back holding fewer events than they want, as a search for a
//! rare word does: see `ahead`.

use std::collections::hash_map::Entry;
use std::collections::{BTreeSet, HashMap};
use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use super::block::{self, Wanted};
use super::bloom::may_hold;
use super::condition::{Condition, Matching};
use super::engine::{Records, Stream, nanos};
use super::event::{Event, Fields, Kept, Level, TraceId};
use super::head::{self, Codec};
use super::pack::{CONTEXT_KEY, FIELD_KEY, NAME_KEY};
use super::repair::Part;
use super::segment::Schema;
use super::tail::Tail;
use crate::limits::Limit;
use crate::sqlite::sql_error;
use crate::{Error, Result, unix_nanos};
use rusqlite::{Connection, OptionalExtension, Rows, ToSql, params};

/// The events of a page unless its `limit` says.
pub const PAGE_EVENTS: usize = 1000;
/// The events a page holds at most.
const MOST_EVENTS: usize = 10_000;
/// The rows and the bytes one window fetches before it ends early.
const FETCH_ROWS: usize = 1024;
const FETCH_BYTES: usize = 16 << 20;
/// What a read reserves for each event its rows hold, beside their bytes.
pub(super) const EVENT_HELD: u64 = 1 << 10;
use crate::memory::PATIENCE;

/// One page of an answer. `next` is the page after it, for `after`; the last
/// page has none.
#[derive(Clone, Debug, PartialEq)]
pub struct Page {
    pub events: Vec<Event>,
    pub next: Option<String>,
}

/// What a read looks for.
#[derive(Clone, Debug, Default)]
pub(super) struct Query {
    since: Option<Duration>,
    from: Option<SystemTime>,
    to: Option<SystemTime>,
    streams: Vec<String>,
    names: Vec<String>,
    min_level: Option<Level>,
    trace_id: Option<TraceId>,
    /// Each a key and what its value must be.
    filters: Vec<(String, Matching)>,
    /// In lower case.
    search: Option<String>,
    newest: bool,
    limit: Option<usize>,
    after: Option<String>,
    /// A condition that could not be taken, for the read that refuses it.
    refused: Option<String>,
}

impl Query {
    /// Whether an event meets every condition but the range.
    pub(super) fn keeps(&self, event: &Kept) -> bool {
        let named = self.names.is_empty() || self.names.contains(&event.name);
        let grave = self.min_level.is_none_or(|least| event.level.is_some_and(|level| level >= least));
        let traced = self.trace_id.is_none_or(|trace| event.trace_id == Some(trace));
        let holds = |(key, matching): &(String, Matching)| matching.finds(key, &event.fields, &event.context);
        let said = self.search.as_ref().is_none_or(|text| says(event, text));
        named && grave && traced && self.filters.iter().all(holds) && said
    }

    /// The same read over the range `after` writes, as a page's `next` does.
    pub(super) fn over(&self, after: String) -> Query {
        Query { after: Some(after), ..self.clone() }
    }

    /// The events a page holds.
    pub(super) fn page_events(&self) -> usize {
        self.limit.unwrap_or(PAGE_EVENTS)
    }

    /// Refuses what a delete cannot take: a read with no `where`, which would
    /// delete every event of its range, as SQL-09 refuses a delete with no
    /// condition; a phrase, too loose for what cannot be undone; and an
    /// order, a page's limit or its `next`, which a delete of every event the
    /// read finds has no use for.
    pub(super) fn deletes(&self) -> Result<()> {
        if let Some(refused) = &self.refused {
            return Err(Error::invalid(refused.clone()));
        }
        if self.filters.is_empty() {
            return Err(Error::invalid("a delete without a where, which would delete every event of its range"));
        }
        if self.search.is_some() {
            return Err(Error::invalid("a delete takes no search: a phrase may find more than a person's events"));
        }
        if self.newest || self.limit.is_some() || self.after.is_some() {
            return Err(Error::invalid("a delete takes no newest, limit or after: it deletes every event it finds"));
        }
        Ok(())
    }
}

/// Whether an event holds `text`, which is in lower case: in its message, in
/// its name, or in a value of its fields or its context.
fn says(event: &Kept, text: &str) -> bool {
    let within = |words: &str| words.to_lowercase().contains(text);
    let values = |fields: &Fields| fields.iter().any(|(_, json)| value_says(json, text));
    event.message.as_deref().is_some_and(within)
        || within(&event.name)
        || values(&event.fields)
        || values(&event.context)
}

/// Whether a JSON value holds `text` at any depth: a string as it reads, any
/// other value as it is written. A key is not looked at.
fn value_says(json: &str, text: &str) -> bool {
    match json.as_bytes().first() {
        Some(b'"') => serde_json::from_str::<String>(json).is_ok_and(|read| read.to_lowercase().contains(text)),
        Some(b'[') => serde_json::from_str::<Vec<&serde_json::value::RawValue>>(json)
            .is_ok_and(|items| items.iter().any(|item| value_says(item.get(), text))),
        Some(b'{') => Fields::read(json).is_ok_and(|inner| inner.iter().any(|(_, value)| value_says(value, text))),
        _ => json.to_lowercase().contains(text),
    }
}

/// A read being asked: every condition narrows it, and `page` or `all` runs
/// it.
#[derive(Clone)]
pub struct List {
    records: Arc<Records>,
    /// The stream read; every stream without one.
    stream: Option<Stream>,
    query: Query,
}

impl fmt::Debug for List {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let stream = self.stream.as_ref().map(|stream| &stream.name);
        f.debug_struct("List").field("stream", &stream).field("query", &self.query).finish()
    }
}

impl List {
    pub(super) fn of(records: Arc<Records>, stream: Option<Stream>) -> List {
        List { records, stream, query: Query::default() }
    }

    /// The span before now the range covers; or `from` and `to`.
    pub fn since(mut self, span: Duration) -> Self {
        self.query.since = Some(span);
        self
    }

    /// The range's start, which is in it.
    pub fn from(mut self, at: SystemTime) -> Self {
        self.query.from = Some(at);
        self
    }

    /// The range's end, which is not in it.
    pub fn to(mut self, at: SystemTime) -> Self {
        self.query.to = Some(at);
        self
    }

    /// Any of these streams, for a read of every stream.
    pub fn streams<S: Into<String>>(mut self, streams: impl IntoIterator<Item = S>) -> Self {
        self.query.streams.extend(streams.into_iter().map(Into::into));
        self
    }

    /// Any of these names: `["log"]` is the lines.
    pub fn names<S: Into<String>>(mut self, names: impl IntoIterator<Item = S>) -> Self {
        self.query.names.extend(names.into_iter().map(Into::into));
        self
    }

    /// This level and worse. An event without a level is not found.
    pub fn min_level(mut self, level: Level) -> Self {
        self.query.min_level = Some(level);
        self
    }

    pub fn trace_id(mut self, trace_id: TraceId) -> Self {
        self.query.trace_id = Some(trace_id);
        self
    }

    /// `key` at the top of an event's fields or of its context with a value
    /// the condition takes: a value by the JSON it is written as, so that
    /// `&42` finds `42`, and neither `"42"` nor `42.0`; a list, one of its
    /// items, `&[7, 12, 31]`, and a list or an object as the value itself
    /// inside one, `&[["a", "b"]]`; [`Not`](crate::Not), none of them or no
    /// such key; [`Prefix`](crate::Prefix), a text that starts with it. A key
    /// written twice is found by its last value, the one [`Fields::get`]
    /// reads. An empty list or another object is refused, `invalid`.
    pub fn filter(mut self, key: &str, condition: impl Into<Condition>) -> Self {
        match condition.into().checked(key) {
            Ok(matching) => self.query.filters.push((key.to_owned(), matching)),
            Err(why) => self.query.refused = self.query.refused.take().or(Some(why)),
        }
        self
    }

    /// This text as a phrase, its case ignored: in an event's message, in
    /// its name, or in a value of its fields or its context at any depth.
    pub fn search(mut self, text: &str) -> Self {
        self.query.search = Some(text.to_lowercase());
        self
    }

    /// Newest first; oldest first without it.
    pub fn newest(mut self) -> Self {
        self.query.newest = true;
        self
    }

    /// Deletes every event the read finds, of those appended before the
    /// call, and what the store keeps only for them: a context of their
    /// own, their keys and counts, their values in a filter, the bytes they
    /// lay in. Says how many it deleted. It takes a `where`, and no search,
    /// newest, limit or after.
    ///
    /// A delete is a commit a segment it changes, and cannot be undone: a
    /// read meanwhile may still find what it has not reached, and a delete
    /// cut short by a crash or a cancel leaves what it reached deleted, so
    /// that running it again finishes it. No poll's cursor moves (REC-21),
    /// and an event's id stays held till the stream's keep passes its time.
    /// A backup taken before it, and another node's records.db, keep the
    /// events.
    ///
    /// ```no_run
    /// # fn main() -> tinystore::Result<()> {
    /// let store = tinystore::Store::open("data", Default::default())?;
    /// let events = store.all_events()?;
    /// let deleted = events.list().streams(["activity", "client-errors"]).filter("userId", &97516).delete()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn delete(&self) -> Result<u64> {
        self.records.delete(self.stream.as_ref(), &self.query).map_err(|error| self.within(error))
    }

    /// The events of a page: 1000, and 10,000 at most.
    pub fn limit(mut self, events: usize) -> Self {
        self.query.limit = Some(events);
        self
    }

    /// A page's `next`, with the rest of the read as it was: the page after
    /// it, in the range the first page had.
    pub fn after(mut self, next: &str) -> Self {
        self.query.after = Some(next.to_owned());
        self
    }

    /// One page: its limit of events that match, less those of a time the
    /// limit would split, or fewer on the last page, which has no `next`.
    /// It reads on past the events that match nothing, several windows at
    /// once as `all` does, each from a moment of the file of its own.
    pub fn page(&self) -> Result<Page> {
        self.records.page(self.stream.as_ref(), &self.query).map_err(|error| self.within(error))
    }

    /// The keys the events of the read's range hold, in their fields and
    /// their contexts, sorted: as many as its limit, 1000 unless it says. A
    /// packed segment that reaches into the range gives every key it holds,
    /// which the file keeps beside its events.
    pub fn field_names(&self) -> Result<Vec<String>> {
        self.field_names_prefix("")
    }

    /// The keys `field_names` gives that begin with `prefix`.
    pub fn field_names_prefix(&self, prefix: &str) -> Result<Vec<String>> {
        let named = self.records.field_names(self.stream.as_ref(), &self.query, prefix);
        named.map_err(|error| self.within(error))
    }

    /// Every event the read finds, ten thousand a page, for `what` to count:
    /// a count takes no newest first and no page after another, and only
    /// `top` and `largest` take a limit, of what they give.
    pub(super) fn walk(&self, what: &str) -> Result<All> {
        let takes_limit = what == "top" || what == "largest";
        if self.query.newest || self.query.after.is_some() || (!takes_limit && self.query.limit.is_some()) {
            let refused = if takes_limit { "newest or after" } else { "newest, limit or after" };
            return Err(self.within(Error::invalid(format!("{what} takes no {refused}"))));
        }
        let mut walk = self.clone();
        walk.query.limit = Some(MOST_EVENTS);
        Ok(walk.all())
    }

    /// The range the read asks for, both ends in it, in nanoseconds.
    pub(super) fn span(&self) -> Result<(i64, i64)> {
        range(&self.query, self.records.now()).map_err(|error| self.within(error))
    }

    /// The range an aggregate fills, both ends in it: from the read's start,
    /// cut to what its streams keep, to its end or to now without one; none
    /// when they keep nothing of it. A read without a start fills nothing,
    /// since a range from 1970 has no first span to fill, and is refused.
    pub(super) fn kept_span(&self) -> Result<Option<(i64, i64)>> {
        if self.query.since.is_none() && self.query.from.is_none() {
            return Err(self.within(Error::invalid("fill takes a range with a start: since or from")));
        }
        let asked = self.records.asked(self.stream.as_ref(), &self.query).map_err(|error| self.within(error))?;
        let now = self.records.now();
        let ended = |last: i64| if self.query.to.is_some() { last } else { last.min(now) };
        Ok(asked.map(|asked| (asked.first, ended(asked.last))).filter(|(first, last)| first <= last))
    }

    /// Nothing yet of the store's memory, for what a count holds to grow.
    pub(super) fn nothing_held(&self) -> crate::Reservation {
        self.records.memory.nothing()
    }

    /// The limit the read was given.
    pub(super) fn given_limit(&self) -> Option<usize> {
        self.query.limit
    }

    /// An error of this read, named by what it reads.
    fn within(&self, error: Error) -> Error {
        match &self.stream {
            Some(stream) => error.within(format!("events {}", stream.name)),
            None => error.within("events"),
        }
    }

    /// The events appended from now on that meet the read's conditions, a
    /// batch as they come: a tail takes no range, order, limit or after.
    pub fn tail(&self) -> Result<Tail> {
        let query = &self.query;
        let ranged = query.since.is_some() || query.from.is_some() || query.to.is_some();
        if ranged || query.newest || query.limit.is_some() || query.after.is_some() {
            return Err(self.within(Error::invalid("a tail takes no range, order, limit or after")));
        }
        if let Some(refused) = &query.refused {
            return Err(self.within(Error::invalid(refused.clone())));
        }
        let streams = match &self.stream {
            Some(_) if !query.streams.is_empty() => {
                let why = "streams, which a read of every stream takes: a stream reads its own";
                return Err(self.within(Error::invalid(why)));
            }
            Some(stream) => Some(vec![stream.name.to_string()]),
            None if query.streams.is_empty() => None,
            None => Some(query.streams.clone()),
        };
        let query = query.clone();
        Ok(Tail::open(&self.records, streams, Box::new(move |event: &Kept| query.keeps(event))))
    }

    /// Every event of the answer, a page at a time.
    pub fn all(self) -> All {
        All { list: self, page: Vec::new().into_iter(), more: true, wide: 1 }
    }

    /// The pages from where the read stands as `all` reads them, `wide`
    /// ranges at once to begin with.
    #[cfg(test)]
    pub(super) fn read_ahead(&self, wide: usize) -> Result<(Page, usize)> {
        let read = self.records.read_ahead(self.stream.as_ref(), &self.query, wide, self.query.page_events());
        read.map(|(window, wide)| (window.into_page(), wide))
    }
}

/// Every event of an answer, read a page at a time as it is walked, and
/// several windows at once while they hold fewer events than a page.
#[derive(Debug)]
pub struct All {
    list: List,
    page: std::vec::IntoIter<Event>,
    more: bool,
    /// The pages the next read begins with at once.
    wide: usize,
}

#[cfg(feature = "async")]
impl All {
    /// The events of the next page that holds any, as the iterator would give
    /// them one by one: the async API's stream takes a page's worth in one
    /// job of the store's pool. None once the answer has no more, and an
    /// error once, as the iterator gives it.
    pub(crate) fn page(&mut self) -> Option<Result<Vec<Event>>> {
        let first = match self.next()? {
            Ok(first) => first,
            Err(error) => return Some(Err(error)),
        };
        Some(Ok(std::iter::once(first).chain(self.page.by_ref()).collect()))
    }
}

impl Iterator for All {
    type Item = Result<Event>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(event) = self.page.next() {
                return Some(Ok(event));
            }
            if !self.more {
                return None;
            }
            let (list, wanted) = (&self.list, self.list.query.page_events());
            match list.records.read_ahead(list.stream.as_ref(), &list.query, self.wide, wanted) {
                Ok((window, wide)) => {
                    let page = window.into_page();
                    self.wide = wide;
                    self.more = page.next.is_some();
                    self.list.query.after = page.next;
                    self.page = page.events.into_iter();
                }
                Err(error) => {
                    self.more = false;
                    return Some(Err(self.list.within(error)));
                }
            }
        }
    }
}

/// A read with its range and its streams worked out.
#[derive(Clone)]
pub(super) struct Asked {
    /// The range in nanoseconds, both ends in it.
    first: i64,
    last: i64,
    limit: usize,
    newest: bool,
    /// The bits of the levels a row must have one of; none for any.
    levels: i64,
    /// The streams read, by id: each one's name, and the time before which
    /// it keeps nothing.
    pub(super) streams: HashMap<i64, (Arc<str>, i64)>,
    /// Their ids as SQLite takes a list, when they are not every stream.
    only: Option<String>,
}

impl Asked {
    /// The end of a row a read walks by: where it begins, oldest first, and
    /// where it ends, newest first.
    fn edge(&self, row: &Picked) -> i64 {
        if self.newest { row.last_at } else { row.first_at }
    }

    /// The end of the range a read begins at.
    pub(super) fn start(&self) -> i64 {
        if self.newest { self.last } else { self.first }
    }

    /// The same read over `first` to `last`, both in it.
    fn narrowed(&self, (first, last): (i64, i64)) -> Asked {
        Asked { first, last, ..self.clone() }
    }

    /// Whether a row reaches over the end of the range a read begins at, and
    /// so may hold the first event of the window.
    fn reaches_over(&self, row: &Picked) -> bool {
        !self.past(self.edge(row), self.start())
    }

    /// Whether a read walking its way meets the time `edge` after `start`.
    fn past(&self, edge: i64, start: i64) -> bool {
        if self.newest { edge < start } else { edge > start }
    }

    /// The range from `start` to the end of a read's own, both ends in it.
    pub(super) fn from(&self, start: i64) -> (i64, i64) {
        if self.newest { (self.first, start) } else { (start, self.last) }
    }

    /// The range from `start` to just before `bound`, both ends in it.
    pub(super) fn between(&self, start: i64, bound: i64) -> (i64, i64) {
        if self.newest { (bound + 1, start) } else { (start, bound - 1) }
    }

    /// The range from just past the time `edge` to the end of a read's own.
    fn beyond(&self, edge: i64) -> (i64, i64) {
        if self.newest { (self.first, edge - 1) } else { (edge + 1, self.last) }
    }
}

/// Whether the rows a window has taken are as many as it fetches: the
/// events it holds, or the rows or the bytes one read fetches.
fn full(events: u64, rows: usize, bytes: usize, limit: usize) -> bool {
    events >= limit as u64 || rows >= FETCH_ROWS || bytes >= FETCH_BYTES
}

/// Where a row of events is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Block,
    Head,
}

/// A row a read picked by what its index says, its body not read yet.
struct Picked {
    kind: Kind,
    id: i64,
    /// A block's segment, whose row says how to read it; none of a head row.
    segment: i64,
    stream: i64,
    first_at: i64,
    last_at: i64,
    events: u64,
    size: usize,
}

/// What a read fetched: its rows, each with its body, and the rows of the
/// segments its blocks are of, by their ids.
struct Fetched {
    rows: Vec<(Picked, Vec<u8>)>,
    segments: HashMap<i64, Vec<u8>>,
}

/// An event a read found, with what orders it: its time as the file keeps it,
/// to the nanosecond, which a window and a page are cut and go on by. Its
/// public time is a `SystemTime`, which keeps 100 ns on Windows.
pub(super) struct Found {
    at: i64,
    arrival: i64,
    stream: Arc<str>,
    event: Kept,
}

impl Found {
    fn into_event(self) -> Event {
        self.event.into_event(&self.stream)
    }
}

/// What one window found, or the windows that follow it a page or a read
/// ahead reads, in the read's order, and where the next window begins.
pub(super) struct Window {
    pub(super) found: Vec<Found>,
    pub(super) next: Option<String>,
}

impl Window {
    pub(super) const EMPTY: Window = Window { found: Vec::new(), next: None };

    fn into_page(self) -> Page {
        Page { events: self.found.into_iter().map(Found::into_event).collect(), next: self.next }
    }
}

/// The rows of a range that may hold what a read asks, from the range's
/// older end: the same statement over the heads and over the blocks.
macro_rules! rows_of {
    ($table:literal, $segment:literal, $order:literal) => {
        concat!(
            "select id, stream, first_at, last_at, count, size, ",
            $segment,
            " from ",
            $table,
            " where last_at >= ?1 and first_at <= ?2 and (?3 = 0 or levels & ?3 != 0)
               and (?4 is null or stream in (select value from json_each(?4))) order by ",
            $order
        )
    };
}

const HEADS_OLDEST: &str = rows_of!("heads", "0", "first_at, id");
const HEADS_NEWEST: &str = rows_of!("heads", "0", "last_at desc, id desc");
const BLOCKS_OLDEST: &str = rows_of!("blocks", "segment", "first_at, id");
const BLOCKS_NEWEST: &str = rows_of!("blocks", "segment", "last_at desc, id desc");
const HEAD_BODY: &str = "select body from heads where id = ?1";
const BLOCK_BODY: &str = "select body from blocks where id = ?1";
const SEGMENT_BODY: &str = "select body from segments where id = ?1";
/// The segments that reach into a range, and of each its keys of fields or
/// of contexts, kinds 1 and 2, from a prefix on in their order: a read takes
/// as many of each as its limit, rather than every key of every segment.
const SEGMENTS_WITHIN: &str = "select id from segments where holder is null and last_at >= ?1 and first_at <= ?2
    and (?3 is null or stream in (select value from json_each(?3)))";
/// A segment's blocks that reach into a range, as `rows_of!` picks them.
const HOLDER_BLOCKS: &str = "select id, stream, first_at, last_at, count, size, segment from blocks
    where segment = ?1 and last_at >= ?2 and first_at <= ?3 and (?4 = 0 or levels & ?4 != 0)";
const SEGMENT_KEYS: &str = "select key from segment_keys where segment = ?1 and kind = ?2 and key >= ?3 order by key";
const HEAD_BODIES: &str = "select id, stream, count, body from heads where last_at >= ?1 and first_at <= ?2
    and (?3 is null or stream in (select value from json_each(?3)))";
const HAS_KEY: &str = "select exists (select 1 from segment_keys where segment = ?1 and kind = ?2 and key = ?3)";
const TRACES_BLOOM: &str = "select bloom from block_traces where block = ?1";
const FIELD_BLOOM: &str = "select bloom from block_filters where block = ?1 and key = ?2";

impl Records {
    /// One page: work out the range → read windows on from where the read
    /// stands, several at once while they hold few, until they hold the
    /// page's events or the range ends → cut the page.
    ///
    /// The range is written into the read once, so that every window reads
    /// within the one `since` gave as the page began. A window that fails
    /// after others held events ends the page before it, as pages one after
    /// another would end, and the next page fails there.
    pub(super) fn page(&self, stream: Option<&Stream>, query: &Query) -> Result<Page> {
        let Some(asked) = self.asked(stream, query)? else { return Ok(Page { events: Vec::new(), next: None }) };
        let (mut events, mut wide) = (Vec::new(), 1);
        let mut from = query.over(written((asked.first, asked.last)));
        loop {
            let (window, widened) = match self.read_ahead(stream, &from, wide, asked.limit - events.len()) {
                Ok(read) => read,
                Err(error) if events.is_empty() => return Err(error),
                Err(_) => return Ok(Window { found: events, next: from.after }.into_page()),
            };
            events.extend(window.found);
            match window.next {
                Some(next) if events.len() < asked.limit => (from, wide) = (from.over(next), widened),
                next => return cut(events, &asked, next).map(Window::into_page),
            }
        }
    }

    /// One window: work out the range → pick and fetch its rows → parse and
    /// keep what matches → cut the window as a page is cut.
    pub(super) fn window(&self, stream: Option<&Stream>, query: &Query) -> Result<Window> {
        let Some(asked) = self.asked(stream, query)? else { return Ok(Window::EMPTY) };
        let (fetched, horizon) = self.fetch(&asked, query)?;
        let bytes: usize = fetched.rows.iter().map(|(picked, _)| picked.size).sum();
        let events: u64 = fetched.rows.iter().map(|(picked, _)| picked.events).sum();
        let _held = self.memory.reserve_for_read(bytes as u64 + events * EVENT_HELD, "records: a read", PATIENCE)?;
        let found = self.found(&asked, query, fetched, horizon)?;
        cut(found, &asked, horizon.map(|edge| written(asked.from(edge))))
    }

    /// Where each range after `start` would begin, `ranges` of them at most,
    /// read from the index of times alone: a range ends once its rows are
    /// what one window fetches, the blocks a filter would pass counted with
    /// the rest, so that a range read alone is a window, or a few.
    pub(super) fn bounds(&self, asked: &Asked, start: i64, ranges: usize) -> Result<Vec<i64>> {
        let asked = asked.narrowed(asked.from(start));
        self.file.read(|connection| {
            let (mut bounds, mut start) = (Vec::with_capacity(ranges), start);
            let (mut events, mut rows, mut bytes) = (0, 0, 0);
            walk_rows(connection, &asked, |row| {
                let edge = asked.edge(&row);
                if full(events, rows, bytes, asked.limit) && asked.past(edge, start) {
                    bounds.push(edge);
                    (start, events, rows, bytes) = (edge, 0, 0, 0);
                    if bounds.len() == ranges {
                        return Ok(false);
                    }
                }
                (events, rows, bytes) = (events + row.events, rows + 1, bytes + row.size);
                Ok(true)
            })
            .map(|()| bounds)
        })
    }

    /// The keys a read's range holds: its packed segments' beside them, and
    /// those of the events that wait, read from their rows after the file is,
    /// the rows and their events held of the store's memory as a page's are.
    fn field_names(&self, stream: Option<&Stream>, query: &Query, prefix: &str) -> Result<Vec<String>> {
        let Some(asked) = self.asked(stream, query)? else { return Ok(Vec::new()) };
        let failed = |error| sql_error("read the keys events hold", error);
        let mut keys = FirstKeys { keys: BTreeSet::new(), most: asked.limit };
        let heads = self.file.read(|connection| {
            segments_keys(connection, &asked, prefix, &mut keys)?;
            let mut heads = connection.prepare_cached(HEAD_BODIES).map_err(failed)?;
            let bodies = heads.query_map(params![asked.first, asked.last, asked.only], |row| {
                Ok((row.get(0)?, row.get(1)?, row.get::<_, i64>(2)?, row.get(3)?))
            });
            let bodies: Vec<(i64, i64, i64, Vec<u8>)> = bodies.and_then(Iterator::collect).map_err(failed)?;
            Ok(bodies)
        })?;
        let bytes: usize = heads.iter().map(|(_, _, _, body)| body.len()).sum();
        let events: u64 = heads.iter().map(|(_, _, events, _)| events.unsigned_abs()).sum();
        let _held =
            self.memory.reserve_for_read(bytes as u64 + events * EVENT_HELD, "records: field names", PATIENCE)?;
        let mut codec = Codec::default();
        for (id, stream, _, body) in heads {
            // A head row that no longer reads is damage, listed as a read over it lists it.
            let shown = asked.streams.get(&stream).map_or_else(|| stream.to_string(), |(name, _)| name.to_string());
            let events = head::parse(&body, &mut codec)
                .map_err(|error| self.met((Part::HeadRow, id), &shown, error))?
                .into_iter()
                .filter(|event| (asked.first..=asked.last).contains(&event.at));
            for event in events {
                for (key, _) in event.fields.iter().chain(event.context.iter()) {
                    if key.starts_with(prefix) {
                        keys.take(key);
                    }
                }
            }
        }
        Ok(keys.keys.into_iter().collect())
    }

    /// The range and the streams of a read; `None` when they hold nothing.
    pub(super) fn asked(&self, stream: Option<&Stream>, query: &Query) -> Result<Option<Asked>> {
        if let Some(refused) = &query.refused {
            return Err(Error::invalid(refused.clone()));
        }
        let limit = query.limit.unwrap_or(PAGE_EVENTS);
        if limit == 0 || limit > MOST_EVENTS {
            return Err(Error::invalid(format!("a page of {limit} events: it holds 1 to {MOST_EVENTS}")));
        }
        let now = self.now();
        let read: Vec<Stream> = match stream {
            Some(_) if !query.streams.is_empty() => {
                return Err(Error::invalid("streams, which a read of every stream takes: a stream reads its own"));
            }
            Some(stream) => self.stream(&stream.name).into_iter().collect(),
            None if query.streams.is_empty() => self.every_stream(),
            None => query.streams.iter().filter_map(|name| self.stream(name)).collect(),
        };
        let only = (stream.is_some() || !query.streams.is_empty())
            .then(|| format!("[{}]", read.iter().map(|stream| stream.id.to_string()).collect::<Vec<_>>().join(",")));
        let kept = |stream: &Stream| now.saturating_sub(nanos(stream.keeps()));
        let Some(oldest) = read.iter().map(kept).min() else { return Ok(None) };
        let (first, last) = range(query, now)?;
        let first = first.max(oldest);
        let streams = read.iter().map(|stream| (stream.id, (Arc::clone(&stream.name), kept(stream)))).collect();
        let (newest, levels) = (query.newest, query.min_level.map_or(0, Level::bits_from));
        Ok((first <= last).then_some(Asked { first, last, limit, newest, levels, streams, only }))
    }

    /// The rows of a range from the end a read begins at, picked by their
    /// index and then fetched, in one read of the file, with the edge of the
    /// rows left behind.
    ///
    /// A window is whole up to that edge and no further: a row left behind
    /// begins at it, oldest first, or ends at it, newest first, so every
    /// event on the near side of it is in a row fetched. A row that reaches
    /// over the range's own end is fetched whatever the window holds already,
    /// so that the edge lies inside the range and the next window begins past
    /// this one.
    fn fetch(&self, asked: &Asked, query: &Query) -> Result<(Fetched, Option<i64>)> {
        self.file.read(|connection| {
            let mut passing = Passing { query, connection, segments: HashMap::new() };
            let (mut taken, mut events, mut bytes) = (Vec::new(), 0, 0);
            let mut horizon = None;
            walk_rows(connection, asked, |row| {
                if full(events, taken.len(), bytes, asked.limit) && !asked.reaches_over(&row) {
                    horizon = Some(asked.edge(&row));
                    return Ok(false);
                }
                if row.kind == Kind::Head || passing.may_find(&row)? {
                    (events, bytes) = (events + row.events, bytes + row.size);
                    taken.push(row);
                }
                Ok(true)
            })?;
            let mut segments = HashMap::new();
            for row in taken.iter().filter(|row| row.kind == Kind::Block) {
                if let Entry::Vacant(unread) = segments.entry(row.segment) {
                    unread.insert(body_by(connection, SEGMENT_BODY, row.segment)?);
                }
            }
            let rows = taken.into_iter().map(|row| {
                let sql = if row.kind == Kind::Block { BLOCK_BODY } else { HEAD_BODY };
                body_by(connection, sql, row.id).map(|body| (row, body))
            });
            Ok((Fetched { rows: rows.collect::<Result<_>>()?, segments }, horizon))
        })
    }
}

/// What a read asks that tells it to pass a block without fetching it.
struct Passing<'q> {
    query: &'q Query,
    connection: &'q Connection,
    /// Whether each segment met holds a name and every key the read asks
    /// for, by its id.
    segments: HashMap<i64, bool>,
}

impl Passing<'_> {
    /// Whether a block may hold an event the read asks for: its segment
    /// holds one of the names asked and every key a filter names, in a field
    /// or a context; its traces may hold the trace asked; and the values of
    /// a field that look like ids may hold the one a filter names, unless a
    /// context holds the key.
    fn may_find(&mut self, block: &Picked) -> Result<bool> {
        let query = self.query;
        if query.names.is_empty() && query.trace_id.is_none() && query.filters.is_empty() {
            return Ok(true);
        }
        let holds = match self.segments.get(&block.segment) {
            Some(holds) => *holds,
            None => {
                let holds = self.segment_holds(block.segment)?;
                *self.segments.entry(block.segment).or_insert(holds)
            }
        };
        if !holds {
            return Ok(false);
        }
        if let Some(trace) = query.trace_id
            && !self.bloom(TRACES_BLOOM, params![block.id])?.is_some_and(|bloom| may_hold(&bloom, &trace.0))
        {
            return Ok(false);
        }
        for (key, values) in query.filters.iter().filter_map(|(key, matching)| Some((key, matching.one_of()?))) {
            let bloom = self.bloom(FIELD_BLOOM, params![block.id, key])?;
            let passed = |bloom: Vec<u8>| !values.iter().any(|json| may_hold(&bloom, json.as_bytes()));
            if bloom.is_some_and(passed) && !self.has(block.segment, CONTEXT_KEY, key)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    fn segment_holds(&self, segment: i64) -> Result<bool> {
        let mut named = self.query.names.is_empty();
        for name in &self.query.names {
            named = named || self.has(segment, NAME_KEY, name)?;
        }
        if !named {
            return Ok(false);
        }
        for (key, _) in self.query.filters.iter().filter(|(_, matching)| matching.needs_key()) {
            if !self.has(segment, FIELD_KEY, key)? && !self.has(segment, CONTEXT_KEY, key)? {
                return Ok(false);
            }
        }
        Ok(true)
    }

    fn has(&self, segment: i64, kind: u8, key: &str) -> Result<bool> {
        let found = self
            .connection
            .prepare_cached(HAS_KEY)
            .and_then(|mut select| select.query_row(params![segment, kind, key], |row| row.get(0)));
        found.map_err(|error| sql_error("look up what a segment holds", error))
    }

    fn bloom(&self, sql: &str, key: impl rusqlite::Params) -> Result<Option<Vec<u8>>> {
        let found = self
            .connection
            .prepare_cached(sql)
            .and_then(|mut select| select.query_row(key, |row| row.get(0)).optional());
        found.map_err(|error| sql_error("read a block's filter", error))
    }
}

impl Records {
    /// The segments of a delete's streams whose events may meet `query` in
    /// `first` to `last`, as a read passes blocks: by the keys a segment
    /// holds, then by its blocks' times, levels and filters. A segment of
    /// holes alone has no block, and none is found.
    pub(super) fn holders_matching(&self, asked: &Asked, query: &Query, (first, last): (i64, i64)) -> Result<Vec<i64>> {
        let failed = |error| sql_error("find the segments a delete reaches", error);
        self.file.read(|connection| {
            let mut within = connection.prepare_cached(SEGMENTS_WITHIN).map_err(failed)?;
            let holders = within.query_map(params![first, last, asked.only], |row| row.get::<_, i64>(0));
            let holders: Vec<i64> = holders.and_then(Iterator::collect).map_err(failed)?;
            let mut passing = Passing { query, connection, segments: HashMap::new() };
            let mut blocks = connection.prepare_cached(HOLDER_BLOCKS).map_err(failed)?;
            let mut found = Vec::new();
            for holder in holders {
                let mut rows = blocks.query(params![holder, first, last, asked.levels]).map_err(failed)?;
                while let Some(block) = picked(&mut rows, Kind::Block)? {
                    if passing.may_find(&block)? {
                        found.push(holder);
                        break;
                    }
                }
            }
            Ok(found)
        })
    }
}

/// Walks the rows of a read's range by their index alone, from the end the
/// read begins at, the heads' and the blocks' merged by that end, while
/// `each` says to go on.
fn walk_rows(connection: &Connection, asked: &Asked, mut each: impl FnMut(Picked) -> Result<bool>) -> Result<()> {
    let failed = |error| sql_error("pick the rows of a read", error);
    let (heads, blocks) = if asked.newest { (HEADS_NEWEST, BLOCKS_NEWEST) } else { (HEADS_OLDEST, BLOCKS_OLDEST) };
    let (mut heads, mut blocks) =
        (connection.prepare_cached(heads).map_err(failed)?, connection.prepare_cached(blocks).map_err(failed)?);
    let range: [&dyn ToSql; 4] = [&asked.first, &asked.last, &asked.levels, &asked.only];
    let mut heads = heads.query(range).map_err(failed)?;
    let mut blocks = blocks.query(range).map_err(failed)?;
    let mut waiting = [picked(&mut blocks, Kind::Block)?, picked(&mut heads, Kind::Head)?];
    loop {
        // of the two rows that wait, the one a read walking its way meets first; of one time, the block
        let nearer = match (&waiting[0], &waiting[1]) {
            (None, None) => return Ok(()),
            (Some(_), None) => 0,
            (None, Some(_)) => 1,
            (Some(block), Some(head)) => usize::from(asked.past(asked.edge(block), asked.edge(head))),
        };
        let Some(row) = waiting[nearer].take() else { return Ok(()) };
        waiting[nearer] = match row.kind {
            Kind::Block => picked(&mut blocks, Kind::Block)?,
            Kind::Head => picked(&mut heads, Kind::Head)?,
        };
        if !each(row)? {
            return Ok(());
        }
    }
}

/// The next row a statement picked, if it has one.
fn picked(rows: &mut Rows<'_>, kind: Kind) -> Result<Option<Picked>> {
    let failed = |error| sql_error("pick the rows of a read", error);
    let Some(row) = rows.next().map_err(failed)? else { return Ok(None) };
    let read: rusqlite::Result<Picked> = (|| {
        let (events, size): (i64, i64) = (row.get(4)?, row.get(5)?);
        let (events, size) = (events.max(0) as u64, size.max(0) as usize);
        Ok(Picked {
            kind,
            id: row.get(0)?,
            segment: row.get(6)?,
            stream: row.get(1)?,
            first_at: row.get(2)?,
            last_at: row.get(3)?,
            events,
            size,
        })
    })();
    read.map(Some).map_err(failed)
}

/// The body of the row `id`, by the statement that reads its table's.
fn body_by(connection: &Connection, sql: &str, id: i64) -> Result<Vec<u8>> {
    let body = connection.prepare_cached(sql).and_then(|mut select| select.query_row([id], |found| found.get(0)));
    body.map_err(|error| sql_error("fetch a row of a read", error))
}

/// The range a read asks for, both ends in it: a page's `next`, or the
/// query's own span.
pub(super) fn range(query: &Query, now: i64) -> Result<(i64, i64)> {
    if let Some(after) = &query.after {
        let ends = after.split_once('~').and_then(|(first, last)| Some((first.parse().ok()?, last.parse().ok()?)));
        return ends.ok_or_else(|| Error::invalid(format!("after {after:?}, which is no page's next")));
    }
    if query.since.is_some() && (query.from.is_some() || query.to.is_some()) {
        return Err(Error::invalid("since beside from or to: a range is one or the other"));
    }
    let first = match (query.since, query.from) {
        (Some(span), _) => now.saturating_sub(nanos(span)),
        (None, Some(from)) => unix_nanos(from),
        (None, None) => i64::MIN,
    };
    Ok((first, query.to.map_or(i64::MAX, |to| unix_nanos(to).saturating_sub(1))))
}

/// A range as a page's `next` writes it, and `range` reads it back.
pub(super) fn written((first, last): (i64, i64)) -> String {
    format!("{first}~{last}")
}

impl Records {
    /// The events of the fetched rows that the read keeps, in its order: by
    /// their times, those of one time by their arrivals, or all of it
    /// backwards. A row that no longer reads fails the read, named as a drop
    /// names it.
    fn found(&self, asked: &Asked, query: &Query, fetched: Fetched, horizon: Option<i64>) -> Result<Vec<Found>> {
        let mut codec = Codec::default();
        let mut schemas: HashMap<i64, Schema> = HashMap::new();
        let owners: HashMap<i64, i64> = fetched.rows.iter().map(|(row, _)| (row.segment, row.stream)).collect();
        for (id, row) in &fetched.segments {
            let stream = owners.get(id).and_then(|stream| asked.streams.get(stream)).map_or("", |(name, _)| &**name);
            let schema =
                Schema::parse(row, &mut codec).map_err(|error| self.met((Part::Segment, *id), stream, error))?;
            schemas.insert(*id, schema);
        }
        let wanted = Wanted {
            first: asked.first,
            last: asked.last,
            names: &query.names,
            min_level: query.min_level,
            trace: query.trace_id,
            filters: &query.filters,
        };
        let mut found = Vec::new();
        for (row, body) in fetched.rows {
            let Some((stream, kept)) = asked.streams.get(&row.stream) else { continue };
            let parsed = match (row.kind, schemas.get(&row.segment)) {
                (Kind::Head, _) => head::parse(&body, &mut codec)
                    .map(|events| {
                        let arrived = events.into_iter().enumerate();
                        arrived.map(|(place, event)| (head::arrival(row.id, place), event)).collect()
                    })
                    .map_err(|error| self.met((Part::HeadRow, row.id), stream, error)),
                (Kind::Block, Some(schema)) => block::parse_wanted(schema, (row.id, &body), &mut codec, &wanted)
                    .map_err(|error| {
                        self.met((Part::Segment, row.segment), stream, error.within(format!("block {}", row.id)))
                    }),
                (Kind::Block, None) => Err(Error::internal(format!("records: block {} has no segment", row.id))),
            };
            for (arrival, event) in parsed? {
                let at = event.at;
                let in_range = at >= asked.first.max(*kept) && at <= asked.last;
                let whole = horizon.is_none_or(|edge| if asked.newest { at > edge } else { at < edge });
                if in_range && whole && query.keeps(&event) {
                    found.push(Found { at, arrival, stream: Arc::clone(stream), event });
                }
            }
        }
        found.sort_by_key(|found| (found.at, found.arrival));
        if asked.newest {
            found.reverse();
        }
        Ok(found)
    }
}

/// A window, or a page of the windows it read, of what was found: the
/// limit's worth, less the events of a time the limit would split, and where
/// the next begins; `next` when they are no more than the limit.
fn cut(mut found: Vec<Found>, asked: &Asked, next: Option<String>) -> Result<Window> {
    let Some(whole) = whole(&found, asked.limit, |found| found.at)? else { return Ok(Window { found, next }) };
    let next = written(asked.beyond(found[whole - 1].at));
    found.truncate(whole);
    Ok(Window { found, next: Some(next) })
}

/// How many of the events found, in a read's order, a page of `limit` holds
/// when they are more than it: the limit's worth, less the events of a time
/// the limit would split; none when they are no more than the limit.
fn whole<T>(found: &[T], limit: usize, at: impl Fn(&T) -> i64) -> Result<Option<usize>> {
    if found.len() <= limit {
        return Ok(None);
    }
    let mut whole = limit;
    while whole > 0 && at(&found[whole]) == at(&found[whole - 1]) {
        whole -= 1;
    }
    if whole == 0 {
        let at_once = found.iter().take_while(|event| at(event) == at(&found[0])).count();
        let page = Limit { name: "page events", bound: limit as u64 };
        let refused = format!("more events at one time than a page of {limit} holds");
        return Err(page.refuse(at_once as u64, refused));
    }
    Ok(Some(whole))
}

/// The first keys in their order of those taken, as many as a read's limit.
struct FirstKeys {
    keys: BTreeSet<String>,
    most: usize,
}

impl FirstKeys {
    /// Takes `key` among the first; false when it is past every key kept,
    /// which are as many as the limit already.
    fn take(&mut self, key: &str) -> bool {
        if self.keys.len() == self.most && self.keys.last().is_some_and(|last| key >= last.as_str()) {
            return false;
        }
        self.keys.insert(key.to_owned());
        if self.keys.len() > self.most {
            self.keys.pop_last();
        }
        true
    }
}

/// Takes the keys of fields and of contexts that begin with `prefix` of each
/// segment that reaches into a read's range, each kind's in their order until
/// one does not begin with it or is past the first ones kept.
fn segments_keys(connection: &Connection, asked: &Asked, prefix: &str, keys: &mut FirstKeys) -> Result<()> {
    let failed = |error| sql_error("read the keys events hold", error);
    let mut within = connection.prepare_cached(SEGMENTS_WITHIN).map_err(failed)?;
    let segments = within.query_map(params![asked.first, asked.last, asked.only], |row| row.get::<_, i64>(0));
    let segments: Vec<i64> = segments.and_then(Iterator::collect).map_err(failed)?;
    let mut select = connection.prepare_cached(SEGMENT_KEYS).map_err(failed)?;
    for segment in segments {
        for kind in [FIELD_KEY, CONTEXT_KEY] {
            let mut rows = select.query(params![segment, kind, prefix]).map_err(failed)?;
            while let Some(row) = rows.next().map_err(failed)? {
                let key: String = row.get(0).map_err(failed)?;
                if !key.starts_with(prefix) || !keys.take(&key) {
                    break;
                }
            }
        }
    }
    Ok(())
}

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