tinystore 0.11.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
//! Counts: how many events a read finds, the most frequent values of a key,
//! and rows of counts and of what fields' numbers add up to, a row a span of
//! time and a value of the keys asked; and what a store holds, its streams.
//!
//! ```text
//! api.list().since(DAY).count()                                   → 42
//! api.list().since(HOUR).top("route")                             → "/notes" 12, "/login" 7, …
//! api.list().since(DAY).aggregate(&Aggregate::new().every(HOUR).by(["level"]))
//!                                                                 → 13:00 error 3, 13:00 warn 41, …
//! ```
//!
//! Each walks every event the read finds, a page at a time, so that what it
//! holds is its answer and never the events.

use std::cmp::{Ordering, Reverse};
use std::collections::{BTreeMap, BinaryHeap, HashMap, HashSet};
use std::time::{Duration, SystemTime};

use rusqlite::params;
use serde_json::Value;

use super::engine::{Records, nanos};
use super::event::{Event, Fields};
use super::events::AllEvents;
use super::read::{EVENT_HELD, List};
use crate::calendar::{Calendar, LocalDate, Zoned};
use crate::limits::{AGGREGATE_ROWS, COUNT_BYTES, Limit};
use crate::sqlite::sql_error;
use crate::{Error, Reservation, Result, unix_nanos};

/// The values `top` and the events `largest` give unless its read's limit
/// says, and at most.
const TOP: usize = 10;
const MOST_TOP: usize = 1000;
/// The rows `aggregate` gives at most.
const MOST_ROWS: usize = AGGREGATE_ROWS.bound as usize;
/// What the different values a count holds may weigh at most: of the key
/// `top` counts, or of every field `distinct` names in every row, each its
/// JSON and what its map spends on it.
const MOST_HELD: usize = COUNT_BYTES.bound as usize;
const HELD_EACH: usize = 64;

/// A value of a key and how many events hold it.
#[derive(Clone, Debug, PartialEq)]
pub struct Top {
    pub value: Value,
    pub count: u64,
}

/// A number a field holds: an integer exactly, however large a sum of them
/// grows, or a float.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Number {
    Integer(i128),
    Float(f64),
}

impl Number {
    pub fn as_f64(self) -> f64 {
        match self {
            Number::Integer(integer) => integer as f64,
            Number::Float(float) => float,
        }
    }
}

/// What a row says of the numbers a field holds; a field with no number in
/// a row has none there.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Stats {
    /// The row's events whose value there is a number, which `avg` divides
    /// `sum` by.
    pub samples: u64,
    pub sum: Number,
    pub min: Number,
    pub max: Number,
    pub avg: f64,
}

/// A row of `aggregate`: a span of time and a value of each key `by` named.
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
    /// Where the span begins, counted from 1970 in UTC.
    pub at: SystemTime,
    pub count: u64,
    /// Each key `by` named, as it was written, with its value; null for
    /// events without it.
    pub by: BTreeMap<String, Value>,
    pub stats: BTreeMap<String, Stats>,
    /// How many different values each field `distinct` named has.
    pub distinct: BTreeMap<String, u64>,
    /// The local date a calendar's span begins on, `2026-11-19`: a week's
    /// Monday, a month's first; none without a calendar.
    pub date: Option<LocalDate>,
}

/// What `aggregate` makes rows of: spans of `every` or of a calendar, the
/// values of the keys in `by`, and of the fields in `stats` and `distinct`.
#[derive(Clone, Debug, Default)]
pub struct Aggregate {
    every: Option<Duration>,
    calendar: Option<(Calendar, String)>,
    by: Vec<String>,
    stats: Vec<String>,
    distinct: Vec<String>,
    fill: bool,
}

impl Aggregate {
    pub fn new() -> Aggregate {
        Aggregate::default()
    }

    /// A row a span this long, each beginning at a whole number of them
    /// since 1970; the whole range is one span without it.
    pub fn every(mut self, span: Duration) -> Self {
        self.every = Some(span);
        self
    }

    /// A row a span of the calendar of a time zone, its IANA name:
    /// `calendar(Calendar::Day, "Europe/Moscow")` begins each at a local
    /// midnight, a day 23 or 25 hours long when the clock moves; a row's `at`
    /// is the instant its span begins.
    pub fn calendar(mut self, unit: Calendar, zone: &str) -> Self {
        self.calendar = Some((unit, zone.to_owned()));
        self
    }

    /// A row a value of each key: a field's, or `stream`, `name`, `level` or
    /// `message`, which are the event's own before a field of that name.
    pub fn by<S: Into<String>>(mut self, keys: impl IntoIterator<Item = S>) -> Self {
        self.by.extend(keys.into_iter().map(Into::into));
        self
    }

    /// The count, sum, least, most and mean of each field's numbers.
    pub fn stats<S: Into<String>>(mut self, keys: impl IntoIterator<Item = S>) -> Self {
        self.stats.extend(keys.into_iter().map(Into::into));
        self
    }

    /// How many different values each field has.
    pub fn distinct<S: Into<String>>(mut self, keys: impl IntoIterator<Item = S>) -> Self {
        self.distinct.extend(keys.into_iter().map(Into::into));
        self
    }

    /// A row for every span of the range the stream keeps, of each value of
    /// `by` the answer has, an empty one counting 0: the read needs a start,
    /// `since` or `from`, and the rows, filled ones too, are 10,000 at most.
    pub fn fill(mut self) -> Self {
        self.fill = true;
        self
    }
}

/// What a store holds of a stream.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StreamInfo {
    pub name: String,
    /// How long it keeps its events.
    pub keep: Duration,
    /// Where what it keeps begins: its oldest event's time, or where its
    /// `keep` begins while it holds events from before, which no read finds.
    pub retained_from: SystemTime,
    pub newest: SystemTime,
}

impl List {
    /// How many events the read finds.
    pub fn count(&self) -> Result<u64> {
        let mut found = 0;
        for event in self.walk("count")? {
            event?;
            found += 1;
        }
        Ok(found)
    }

    /// The most frequent values of `key` and how many events hold each, the
    /// most first and those as frequent in the order of their JSON: ten
    /// unless the read's limit says, 1000 at most. The key is a field's or a
    /// context's, or `stream`, `name`, `level` or `message`.
    pub fn top(&self, key: &str) -> Result<Vec<Top>> {
        let limit = self.given_limit().unwrap_or(TOP);
        if !(1..=MOST_TOP).contains(&limit) {
            return Err(Error::invalid(format!("top {limit} values: it gives 1 to {MOST_TOP}")));
        }
        let (mut counts, mut held): (HashMap<String, Top>, Held) = (HashMap::new(), Held::default());
        for event in self.walk("top")? {
            let Some(value) = value_of(&event?, key) else { continue };
            let json = value.to_string();
            held.add(&json, !counts.contains_key(&json)).map_err(|error| error.within(key))?;
            counts.entry(json).or_insert(Top { value, count: 0 }).count += 1;
        }
        let mut top: Vec<Top> = counts.into_values().collect();
        top.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.value.to_string().cmp(&b.value.to_string())));
        top.truncate(limit);
        Ok(top)
    }

    /// The events whose value at `key` is a JSON number, the largest first:
    /// what sorting every event the read finds by that number would give
    /// first, ten unless the read's limit says, 1000 at most. The key is a
    /// field's, else a context's; an event without a number there is passed
    /// over, and events of one number come in the read's order. It walks
    /// the read as `count` does and holds the events it gives, of the
    /// store's memory: past it the answer is `limit`, never a shorter list.
    pub fn largest(&self, key: &str) -> Result<Vec<Event>> {
        let limit = self.given_limit().unwrap_or(TOP);
        if !(1..=MOST_TOP).contains(&limit) {
            return Err(Error::invalid(format!("largest {limit} events: it gives 1 to {MOST_TOP}")));
        }
        let mut largest = Largest { kept: BinaryHeap::new(), limit, held: self.nothing_held(), bytes: 0 };
        for (place, event) in self.walk("largest")?.enumerate() {
            let event = event?;
            if let Some(number) = value_of(&event, key).as_ref().and_then(number) {
                largest.offer(Ranked { number, place, event }).map_err(|error| error.within(key))?;
            }
        }
        Ok(largest.kept.into_sorted_vec().into_iter().map(|Reverse(ranked)| ranked.event).collect())
    }

    /// A row for each span and each value of the keys `by` names, in the
    /// order of their spans: an answer whole, or an error of kind `limit`
    /// past 10,000 rows.
    pub fn aggregate(&self, aggregate: &Aggregate) -> Result<Vec<Row>> {
        let spans = Spans::of(aggregate)?;
        let (first, _) = self.span()?;
        let filled =
            if aggregate.fill { self.kept_span()?.map(|kept| spans.within(kept, first)).transpose()? } else { None };
        let mut rows = Rows { asked: aggregate, rows: HashMap::new(), held: Held::default() };
        for event in self.walk("aggregate")? {
            let event = event?;
            rows.add(spans.start(unix_nanos(event.at), first), &event)?;
        }
        if let Some(starts) = filled {
            rows.fill(&starts)?;
        }
        Ok(rows.finish(&spans))
    }
}

/// What an aggregate's rows span, in nanoseconds since 1970.
enum Spans {
    /// The whole range, one row.
    Range,
    /// A width counted from 1970 in UTC.
    Every(i64),
    /// A span of a calendar in a time zone.
    Calendar(Zoned),
}

impl Spans {
    fn of(aggregate: &Aggregate) -> Result<Spans> {
        match (aggregate.every, &aggregate.calendar) {
            (Some(_), Some(_)) => Err(Error::invalid("an aggregate's rows are `every` or `calendar`, not both")),
            (Some(span), None) if span.is_zero() => Err(Error::invalid("every: a span longer than none")),
            (Some(span), None) => Ok(Spans::Every(nanos(span))),
            (None, Some((unit, zone))) => Ok(Spans::Calendar(Zoned::of(*unit, zone)?)),
            (None, None) => Ok(Spans::Range),
        }
    }

    /// Where the row of an event at `at` begins; `first`, the range's start,
    /// when the range is one row.
    fn start(&self, at: i64, first: i64) -> i64 {
        match self {
            Spans::Range => first,
            Spans::Every(every) => at.div_euclid(*every) * every,
            Spans::Calendar(zoned) => zoned.start_nanos(at),
        }
    }

    /// Where every span of the range from `kept`'s first to its last begins,
    /// the spans that cut it included: refused before a read once they are
    /// more than an aggregate's rows. `first` is the one row's start.
    fn within(&self, (from, to): (i64, i64), first: i64) -> Result<Vec<i64>> {
        let mut starts = Vec::new();
        let mut at = self.start(from, first);
        while at <= to {
            if starts.len() == MOST_ROWS {
                return Err(past_rows());
            }
            starts.push(at);
            at = match self {
                Spans::Range => break,
                Spans::Every(every) => at.saturating_add(*every),
                Spans::Calendar(zoned) => zoned.end_nanos(at),
            };
        }
        Ok(starts)
    }

    /// The local date a calendar's span that begins at `start` begins on.
    fn date(&self, start: i64) -> Option<LocalDate> {
        match self {
            Spans::Calendar(zoned) => zoned.date_nanos(start),
            Spans::Range | Spans::Every(_) => None,
        }
    }
}

/// An aggregate's answer past the rows it gives, which no smaller answer
/// stands for.
fn past_rows() -> Error {
    let refused = format!("past the {MOST_ROWS} rows an aggregate gives: ask a shorter range or a wider every");
    AGGREGATE_ROWS.refuse(MOST_ROWS as u64 + 1, refused)
}

impl AllEvents {
    /// Every stream with events, by name: what it keeps, where what it keeps
    /// begins, and its newest event's time.
    pub fn streams(&self) -> Result<Vec<StreamInfo>> {
        self.records.streams_held()
    }
}

/// The times of a stream's rows that reach past `?2`: of a segment a delete
/// left holes in, its blocks', which hold its events alone, since its own
/// span keeps the times of its holes for keep.
const TIMES_HELD: &str = "select min(first_at), max(last_at) from
    (select first_at, last_at from heads where stream = ?1 and last_at >= ?2
     union all select first_at, last_at from segments as s where stream = ?1 and holder is null and last_at >= ?2
        and not exists (select 1 from segments as p where (p.id = s.id or p.holder = s.id) and p.erased > 0)
     union all select b.first_at, b.last_at from blocks as b where b.segment in
        (select s.id from segments as s where stream = ?1 and holder is null and last_at >= ?2
            and exists (select 1 from segments as p where (p.id = s.id or p.holder = s.id) and p.erased > 0)))";
/// The events of a stream's rows that `TIMES_HELD` reads, and what the head
/// rows' bodies, the segments' with their blocks' and the events' ids weigh.
/// A merge's places hold none of either: their holder counts and keeps them,
/// less the holes a delete left among their slots.
#[cfg(feature = "client")]
const EVENTS_HELD: &str = "select coalesce(sum(events), 0), coalesce(sum(bytes), 0) from
    (select count as events, size as bytes from heads where stream = ?1 and last_at >= ?2
     union all select s.held - (select sum(p.erased) from segments as p where p.id = s.id or p.holder = s.id),
        length(s.body) + (select coalesce(sum(b.size), 0) from blocks as b where b.segment = s.id)
        from segments as s where s.stream = ?1 and s.holder is null and s.last_at >= ?2
     union all select 0, coalesce(sum(octet_length(id)), 0) from event_ids where stream = ?1)";

impl Records {
    fn streams_held(&self) -> Result<Vec<StreamInfo>> {
        let now = self.now();
        let mut held = Vec::new();
        for stream in self.every_stream() {
            let cutoff = now.saturating_sub(nanos(stream.keeps()));
            if let Some((oldest, newest)) = self.times_held(stream.id, cutoff)? {
                let time = crate::clock::from_unix_nanos;
                let info = StreamInfo {
                    name: stream.name.to_string(),
                    keep: stream.keeps(),
                    retained_from: time(oldest.max(cutoff)),
                    newest: time(newest),
                };
                held.push(info);
            }
        }
        held.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(held)
    }

    /// What each stream with events holds of what it keeps, as `streams`
    /// finds them: its events and what they weigh, a stream a read, so that
    /// a big store keeps no reader open for long.
    #[cfg(feature = "client")]
    pub(crate) fn held(&self) -> Result<Vec<crate::engine::Held>> {
        let now = self.now();
        let mut held = Vec::new();
        for stream in self.every_stream() {
            let cutoff = now.saturating_sub(nanos(stream.keeps()));
            let (count, bytes): (i64, i64) = self
                .file
                .read(|connection| {
                    let select = connection.prepare_cached(EVENTS_HELD);
                    let row = select.and_then(|mut select| {
                        select.query_row(params![stream.id, cutoff], |row| Ok((row.get(0)?, row.get(1)?)))
                    });
                    row.map_err(|error| sql_error("read what a stream holds", error))
                })
                .map_err(|error| error.within(format!("stream {}", stream.name)))?;
            if count > 0 {
                let name = stream.name.to_string();
                held.push(crate::engine::Held { name, count: count.unsigned_abs(), bytes: bytes.unsigned_abs() });
            }
        }
        held.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(held)
    }

    /// The times of a stream's oldest and newest rows that reach past
    /// `cutoff`; none when it has none.
    fn times_held(&self, stream: i64, cutoff: i64) -> Result<Option<(i64, i64)>> {
        let failed = |error| sql_error("read the times a stream holds", error);
        self.file.read(|connection| {
            let held = connection.prepare_cached(TIMES_HELD).and_then(|mut select| {
                select.query_row(params![stream, cutoff], |row| Ok((row.get::<_, Option<i64>>(0)?, row.get(1)?)))
            });
            let (oldest, newest) = held.map_err(failed)?;
            Ok(oldest.zip(newest))
        })
    }
}

/// The events `largest` keeps while it walks, the least of them on top.
struct Largest {
    kept: BinaryHeap<Reverse<Ranked>>,
    limit: usize,
    held: Reservation,
    /// What each event kept weighs, together.
    bytes: u64,
}

impl Largest {
    /// Keeps an event among the largest, letting the least go past the limit.
    fn offer(&mut self, ranked: Ranked) -> Result<()> {
        if self.kept.len() == self.limit && self.kept.peek().is_some_and(|Reverse(least)| ranked <= *least) {
            return Ok(());
        }
        let heavy = weight(&ranked.event);
        self.held.grow(heavy, "records: largest")?;
        self.bytes += heavy;
        self.kept.push(Reverse(ranked));
        if self.kept.len() > self.limit
            && let Some(Reverse(least)) = self.kept.pop()
        {
            self.bytes -= weight(&least.event);
            self.held.shrink(self.bytes);
        }
        Ok(())
    }
}

/// What an event kept in memory weighs, about: its text and what holds it.
fn weight(event: &Event) -> u64 {
    let fields = |fields: &Fields| fields.iter().map(|(key, json)| key.len() + json.len()).sum::<usize>();
    let text = event.message.as_ref().map_or(0, String::len) + event.name.len() + event.stream.len();
    (EVENT_HELD as usize + text + fields(&event.fields) + fields(&event.context)) as u64
}

/// An event by its number, and of one number the earlier in the read the
/// greater, so that it is kept and comes first.
struct Ranked {
    number: Number,
    place: usize,
    event: Event,
}

impl Ord for Ranked {
    fn cmp(&self, other: &Ranked) -> Ordering {
        compare(self.number, other.number).then_with(|| other.place.cmp(&self.place))
    }
}

impl PartialOrd for Ranked {
    fn partial_cmp(&self, other: &Ranked) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Ranked {
    fn eq(&self, other: &Ranked) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Ranked {}

/// Two numbers in their order, an integer against a float exactly: no
/// integer is rounded to a float to be compared, past 2⁵³ included.
fn compare(a: Number, b: Number) -> Ordering {
    match (a, b) {
        (Number::Integer(a), Number::Integer(b)) => a.cmp(&b),
        (Number::Float(a), Number::Float(b)) => a.total_cmp(&b),
        (Number::Integer(a), Number::Float(b)) => integer_against(a, b),
        (Number::Float(a), Number::Integer(b)) => integer_against(b, a).reverse(),
    }
}

/// An integer against a float, by the float's whole part and then its
/// fraction.
fn integer_against(integer: i128, float: f64) -> Ordering {
    // 2¹²⁷, which no i128 reaches and every float at or past it passes
    const PAST: f64 = 1.701_411_834_604_692_3e38;
    if float.is_nan() || float >= PAST {
        return Ordering::Less;
    }
    if float < -PAST {
        return Ordering::Greater;
    }
    let whole = float.trunc();
    match integer.cmp(&(whole as i128)) {
        Ordering::Equal if float > whole => Ordering::Less,
        Ordering::Equal if float < whole => Ordering::Greater,
        order => order,
    }
}

/// What the different values a count holds weigh, and the most they may.
struct Held {
    bytes: usize,
    most: usize,
}

impl Default for Held {
    fn default() -> Held {
        Held { bytes: 0, most: MOST_HELD }
    }
}

impl Held {
    /// Counts a value's JSON in when it is a new one: past the most a count
    /// may hold, `limit`.
    fn add(&mut self, json: &str, new: bool) -> Result<()> {
        self.bytes += if new { json.len() + HELD_EACH } else { 0 };
        if self.bytes > self.most {
            let refused = format!("past the {} bytes of different values one count holds", self.most);
            return Err(Limit { bound: self.most as u64, ..COUNT_BYTES }.refuse(self.bytes as u64, refused));
        }
        Ok(())
    }
}

/// The value of a key an event holds: its stream's name, its name or its
/// level's, its message, or a field's, else its context's. An event without
/// a message gives a field's or a context's `message`, as a program that
/// kept its message in a field read it before.
fn value_of(event: &Event, key: &str) -> Option<Value> {
    let held = |key: &str| {
        event.fields.json(key).or_else(|| event.context.json(key)).and_then(|json| serde_json::from_str(json).ok())
    };
    match key {
        "stream" => Some(Value::String(event.stream.clone())),
        "name" => Some(Value::String(event.name.clone())),
        "level" => event.level.map(|level| Value::String(level.name().to_owned())),
        "message" => event.message.clone().map(Value::String).or_else(|| held(key)),
        key => held(key),
    }
}

/// The number a value is, an integer while it is one.
fn number(value: &Value) -> Option<Number> {
    let Value::Number(number) = value else { return None };
    match (number.as_i64(), number.as_u64()) {
        (Some(integer), _) => Some(Number::Integer(i128::from(integer))),
        (_, Some(integer)) => Some(Number::Integer(i128::from(integer))),
        _ => number.as_f64().map(Number::Float),
    }
}

/// The rows of an aggregate as they fill.
struct Rows<'a> {
    asked: &'a Aggregate,
    /// By the start of a row's span and its keys' values as JSON.
    rows: HashMap<(i64, String), Filling>,
    held: Held,
}

/// A row being filled.
struct Filling {
    by: Vec<Value>,
    count: u64,
    stats: Vec<Summing>,
    distinct: Vec<HashSet<String>>,
}

impl Filling {
    /// A row of no event yet, of the values `by` of its keys.
    fn empty(asked: &Aggregate, by: Vec<Value>) -> Filling {
        Filling {
            by,
            count: 0,
            stats: asked.stats.iter().map(|_| Summing::default()).collect(),
            distinct: asked.distinct.iter().map(|_| HashSet::new()).collect(),
        }
    }
}

/// A field's numbers in a row, summed as they come.
#[derive(Default)]
struct Summing {
    samples: u64,
    integers: i128,
    floats: f64,
    float: bool,
    least: Option<Number>,
    most: Option<Number>,
}

impl Rows<'_> {
    fn add(&mut self, at: i64, event: &Event) -> Result<()> {
        let by: Vec<Value> = self.asked.by.iter().map(|key| value_of(event, key).unwrap_or(Value::Null)).collect();
        let key = (at, Value::Array(by.clone()).to_string());
        if !self.rows.contains_key(&key) && self.rows.len() == MOST_ROWS {
            return Err(past_rows());
        }
        let asked = self.asked;
        let row = self.rows.entry(key).or_insert_with(|| Filling::empty(asked, by));
        row.count += 1;
        for (summing, key) in row.stats.iter_mut().zip(&asked.stats) {
            if let Some(number) = value_of(event, key).as_ref().and_then(number) {
                summing.add(number).map_err(|error| error.within(key.as_str()))?;
            }
        }
        for (values, key) in row.distinct.iter_mut().zip(&asked.distinct) {
            if let Some(value) = value_of(event, key) {
                let json = value.to_string();
                self.held.add(&json, !values.contains(&json)).map_err(|error| error.within(key.as_str()))?;
                values.insert(json);
            }
        }
        Ok(())
    }

    /// Gives every span that begins at one of `starts` a row of each value
    /// of `by` the rows hold, an empty one where none is: with no `by`, the
    /// one value of none.
    fn fill(&mut self, starts: &[i64]) -> Result<()> {
        let mut values: HashMap<String, Vec<Value>> =
            self.rows.iter().map(|((_, json), filling)| (json.clone(), filling.by.clone())).collect();
        if self.asked.by.is_empty() {
            values.entry(Value::Array(Vec::new()).to_string()).or_default();
        }
        for (json, by) in values {
            for at in starts {
                let key = (*at, json.clone());
                if !self.rows.contains_key(&key) {
                    if self.rows.len() == MOST_ROWS {
                        return Err(past_rows());
                    }
                    self.rows.insert(key, Filling::empty(self.asked, by.clone()));
                }
            }
        }
        Ok(())
    }

    fn finish(self, spans: &Spans) -> Vec<Row> {
        let asked = self.asked;
        let mut rows: Vec<((i64, String), Filling)> = self.rows.into_iter().collect();
        rows.sort_by(|(a, _), (b, _)| a.cmp(b));
        let row = |((at, _), filling): ((i64, String), Filling)| Row {
            at: crate::clock::from_unix_nanos(at),
            date: spans.date(at),
            count: filling.count,
            by: asked.by.iter().cloned().zip(filling.by).collect(),
            stats: asked
                .stats
                .iter()
                .cloned()
                .zip(filling.stats)
                .filter_map(|(key, summing)| Some((key, summing.stats()?)))
                .collect(),
            distinct: asked
                .distinct
                .iter()
                .cloned()
                .zip(filling.distinct.iter().map(|values| values.len() as u64))
                .collect(),
        };
        rows.into_iter().map(row).collect()
    }
}

impl Summing {
    /// Adds a number; a sum of integers past what 128 bits hold is `limit`,
    /// never one less exact.
    fn add(&mut self, number: Number) -> Result<()> {
        self.samples += 1;
        match number {
            Number::Integer(integer) => {
                let sum = self.integers.checked_add(integer);
                // named alone: its bound, 2¹²⁷, is no number a fact of a bound holds
                let past = || Error::limit("a sum of integers past what 128 bits hold").naming("limit", "sum range");
                self.integers = sum.ok_or_else(past)?;
            }
            Number::Float(float) => (self.floats, self.float) = (self.floats + float, true),
        }
        let less = |a: Number, b: Number| compare(a, b) == Ordering::Less;
        if self.least.is_none_or(|least| less(number, least)) {
            self.least = Some(number);
        }
        if self.most.is_none_or(|most| less(most, number)) {
            self.most = Some(number);
        }
        Ok(())
    }

    /// What the numbers add up to; none when there were none.
    fn stats(self) -> Option<Stats> {
        let (min, max) = (self.least?, self.most?);
        let sum =
            if self.float { Number::Float(self.integers as f64 + self.floats) } else { Number::Integer(self.integers) };
        Some(Stats { samples: self.samples, sum, min, max, avg: sum.as_f64() / self.samples as f64 })
    }
}

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