tinystore 0.6.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
use std::time::{Duration, SystemTime};

use serde_json::json;

use super::super::fixture::{Fixture, SECOND, fixture, names};
use super::*;
use crate::ErrorKind;
use crate::records::{Events, NewEvent, SpanId, maintain};

/// `count` events a second apart, named by their place, the last one now.
fn timeline(fixture: &Fixture, events: &Events, count: u32) {
    let start = fixture.now() - SECOND * (count - 1);
    events.append_all((0..count).map(|n| NewEvent::new(&n.to_string()).at(start + SECOND * n))).unwrap();
}

/// Every page of a read in turn, as the names of its events.
fn pages(list: &List) -> Vec<Vec<String>> {
    let mut pages = Vec::new();
    let mut next = None;
    loop {
        let asked = next.as_deref().map_or(list.clone(), |next| list.clone().after(next));
        let page = asked.page().unwrap();
        assert!(pages.len() < 50, "the pages do not end");
        pages.push(page.events.iter().map(|event| event.name.clone()).collect());
        match page.next {
            Some(after) => next = Some(after),
            None => return pages,
        }
    }
}

// contract: REC-04
#[test]
fn events_come_in_the_order_of_their_times_and_those_of_one_time_as_they_were_written() {
    let fixture = fixture();
    let api = fixture.events("api");
    let now = fixture.now();
    let at = |name: &str, seconds: u64| NewEvent::new(name).at(now - Duration::from_secs(seconds));
    api.append_all([at("c", 1), at("a", 3), at("b1", 2)]).unwrap();
    api.append_all([at("b2", 2), at("d", 0)]).unwrap();
    assert_eq!(names(&api.list().page().unwrap().events), ["a", "b1", "b2", "c", "d"]);
    assert_eq!(names(&api.list().newest().page().unwrap().events), ["d", "c", "b2", "b1", "a"]);
}

/// The names of one stream's events among a read's of every stream, in their order.
fn of_stream<'e>(events: &'e [Event], stream: &str) -> Vec<&'e str> {
    events.iter().filter(|event| event.stream == stream).map(|event| event.name.as_str()).collect()
}

// contract: REC-04
#[test]
fn a_streams_events_of_one_time_come_as_appended_while_late_ones_and_other_streams_pack_and_merge_beside() {
    let fixture = fixture();
    let (api, web) = (fixture.events("api"), fixture.events("web"));
    let at = fixture.now();
    // a minute behind the on-time event appended just before each, so each of them is late
    let behind = at - Duration::from_mins(1);
    // api's events with their times, as they were appended
    let (mut appended, mut webs): (Vec<(SystemTime, String)>, Vec<String>) = (Vec::new(), Vec::new());
    let read = |appended: &[(SystemTime, String)], webs: &[String], when: &str| {
        let mut whole = appended.to_vec();
        // stable, so that those of one time stay as they were appended
        whole.sort_by_key(|(time, _)| *time);
        let whole: Vec<String> = whole.into_iter().map(|(_, name)| name).collect();
        let backwards: Vec<String> = whole.iter().rev().cloned().collect();
        assert_eq!(names(&api.list().page().unwrap().events), whole, "{when}");
        assert_eq!(names(&api.list().newest().page().unwrap().events), backwards, "{when}");
        assert_eq!(pages(&api.list().limit(13)).concat(), whole, "pages, {when}");
        let walked: Vec<String> = api.list().limit(13).all().map(|event| event.unwrap().name).collect();
        assert_eq!(walked, whole, "all, {when}");
        let every = fixture.store.all_events().unwrap().list().page().unwrap().events;
        assert_eq!(of_stream(&every, "api"), whole, "every stream, {when}");
        assert_eq!(of_stream(&every, "web"), webs, "every stream, {when}");
    };
    let late_rows = || fixture.rows("heads where late = 1");
    let mut merged = 0;
    // rounds forty minutes apart, so that a read finds events packed, merged and waiting
    for round in 0..12 {
        let [on, other, behind_it] = ["on", "web", "late"].map(|kind| format!("{kind}-{round}"));
        let mut on_time = vec![(at, on)];
        // once, one five seconds earlier: its segment, packed after others,
        // begins before theirs and ends at their time
        if round == 6 {
            on_time.insert(0, (at - SECOND * 5, "early".to_owned()));
        }
        let late = late_rows();
        api.append_all(on_time.iter().map(|(time, name)| NewEvent::new(name).at(*time))).unwrap();
        web.append_all([NewEvent::new(&other).at(at)]).unwrap();
        assert_eq!(late_rows(), late, "round {round}'s on-time events came late");
        api.append_all([NewEvent::new(&behind_it).at(behind)]).unwrap();
        assert_eq!(late_rows(), late + 1, "{behind_it} came on time");
        appended.extend(on_time);
        appended.push((behind, behind_it));
        webs.push(other);
        read(&appended, &webs, &format!("round {round}"));
        fixture.pass(Duration::from_mins(40));
        merged += maintain(&fixture.store).unwrap().merged;
    }
    fixture.pass(Duration::from_hours(1));
    merged += maintain(&fixture.store).unwrap().merged;
    assert_eq!((fixture.rows("heads"), merged > 0), (0, true), "{merged} merged");
    read(&appended, &webs, "every event packed");
}

/// Each event as `stream/name`.
fn shown(events: &[Event]) -> Vec<String> {
    events.iter().map(|event| format!("{}/{}", event.stream, event.name)).collect()
}

/// What every way of reading gives, each event as `stream/name`: a page of
/// every stream from either end, `all`, pages read ahead at once, and each
/// stream's own page.
fn read_every_way(fixture: &Fixture, expected: &[String], when: &str) {
    let all = fixture.store.all_events().unwrap();
    assert_eq!(shown(&all.list().page().unwrap().events), expected, "{when}");
    let backwards: Vec<String> = expected.iter().rev().cloned().collect();
    assert_eq!(shown(&all.list().newest().page().unwrap().events), backwards, "newest, {when}");
    let walked: Vec<Event> = all.list().limit(100).all().map(Result::unwrap).collect();
    assert_eq!(shown(&walked), expected, "all, {when}");
    for wide in 2..=4 {
        let (page, _) = all.list().limit(100).read_ahead(wide).unwrap();
        assert_eq!(shown(&page.events), expected, "{wide} read ahead, {when}");
    }
    for stream in ["api", "web"] {
        let own: Vec<&String> = expected.iter().filter(|name| name.starts_with(&format!("{stream}/"))).collect();
        let read = shown(&fixture.events(stream).list().page().unwrap().events);
        assert_eq!(read.iter().collect::<Vec<_>>(), own, "{stream}, {when}");
    }
}

// contract: REC-04, DUR-09
#[test]
fn events_of_one_time_come_as_appended_across_streams_late_heads_packing_merges_and_a_reopen() {
    let mut fixture = fixture();
    // a minute behind the clock, so that an event at it behind one twenty seconds after it is late
    let at = fixture.now() - Duration::from_mins(1);
    let ahead = at + SECOND * 20;
    let each_round = [
        ("api", "on", at),
        ("web", "web", at),
        ("api", "ahead", ahead),
        ("api", "behind", at),
        ("web", "web-ahead", ahead),
        ("web", "web-behind", at),
        ("api", "last", at),
    ];
    // each event as `stream/name`, those at `at` and those at `ahead`, as they were appended
    let (mut first, mut then): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
    let (mut late, mut merged) = (0, 0);
    // rounds forty minutes apart, so that a read finds events packed, merged and waiting
    for round in 0..10 {
        for (stream, name, time) in &each_round {
            fixture.events(stream).append_all([NewEvent::new(&format!("{name}-{round}")).at(*time)]).unwrap();
            let appended = if *time == at { &mut first } else { &mut then };
            appended.push(format!("{stream}/{name}-{round}"));
        }
        late = late.max(fixture.rows("heads where late = 1"));
        read_every_way(&fixture, &[first.clone(), then.clone()].concat(), &format!("round {round}"));
        fixture.pass(Duration::from_mins(40));
        merged += maintain(&fixture.store).unwrap().merged;
        if round == 5 {
            fixture = fixture.reopen();
        }
    }
    fixture.pass(Duration::from_hours(1));
    merged += maintain(&fixture.store).unwrap().merged;
    let places = fixture.rows("segments where holder is not null");
    assert_eq!((fixture.rows("heads"), late > 0, merged > 0, places > 0), (0, true, true, true), "{late} {merged}");
    read_every_way(&fixture, &[first, then].concat(), "every event packed");
}

// contract: REC-05
#[test]
fn pages_go_on_without_losing_or_repeating_an_event_from_either_end() {
    let fixture = fixture();
    let api = fixture.events("api");
    timeline(&fixture, &api, 10);
    let forward = pages(&api.list().limit(4));
    assert_eq!(forward, [vec!["0", "1", "2", "3"], vec!["4", "5", "6", "7"], vec!["8", "9"]]);
    let backward = pages(&api.list().newest().limit(4));
    assert_eq!(backward, [vec!["9", "8", "7", "6"], vec!["5", "4", "3", "2"], vec!["1", "0"]]);
}

// contract: REC-05
#[test]
fn a_page_never_splits_a_time_and_more_at_one_time_than_it_holds_is_limit() {
    let fixture = fixture();
    let api = fixture.events("api");
    let now = fixture.now();
    let at = |name: &str, seconds: u64| NewEvent::new(name).at(now - Duration::from_secs(seconds));
    api.append_all([at("a", 3), at("b1", 2), at("b2", 2), at("b3", 2), at("c", 1)]).unwrap();
    assert_eq!(pages(&api.list().limit(3)), [vec!["a"], vec!["b1", "b2", "b3"], vec!["c"]]);
    assert_eq!(pages(&api.list().newest().limit(3)), [vec!["c"], vec!["b3", "b2", "b1"], vec!["a"]]);
    let refused = api.list().limit(2).after(&api.list().limit(1).page().unwrap().next.unwrap()).page().unwrap_err();
    assert_eq!(refused.kind(), ErrorKind::Limit);
}

// contract: REC-05
#[test]
fn a_page_reads_on_past_the_events_that_match_nothing_until_it_holds_its_limit_or_the_range_ends() {
    let fixture = fixture();
    let audit = fixture.events("audit");
    let start = fixture.now() - SECOND;
    let at = |n: u32| start + Duration::from_millis(u64::from(n));
    // one student uploads a file, then two hundred others sign in, an append each
    audit.append_all([NewEvent::new("upload").fields(&json!({ "user": 1 })).at(at(0))]).unwrap();
    for user in 2..202 {
        audit.append_all([NewEvent::new("signed.in").fields(&json!({ "user": user })).at(at(user))]).unwrap();
    }
    let uploads = || audit.list().filter("user", &1).names(["upload"]).limit(50);
    for when in ["waiting", "packed"] {
        for list in [uploads(), uploads().newest()] {
            let page = list.page().unwrap();
            assert_eq!((names(&page.events), page.next), (vec!["upload"], None), "{when}");
        }
        fixture.pass(Duration::from_hours(1));
        maintain(&fixture.store).unwrap();
    }
}

// contract: REC-05
#[test]
fn pages_of_rare_matches_hold_their_limit_but_the_last_and_go_on_without_losing_or_repeating_one() {
    let fixture = fixture();
    let api = fixture.events("api");
    let start = fixture.now() - SECOND * 10;
    // three thousand requests in appends of ten, every hundredth a search
    let request = |n: u32| {
        let path = if n.is_multiple_of(100) { "/search" } else { "/health" };
        NewEvent::new(&n.to_string()).fields(&json!({ "path": path })).at(start + Duration::from_millis(u64::from(n)))
    };
    for row in 0..300 {
        api.append_all((row * 10..row * 10 + 10).map(request)).unwrap();
    }
    let searches: Vec<String> = (0..30).map(|n| (n * 100).to_string()).collect();
    let paged = |searches: Vec<String>| searches.chunks(4).map(<[String]>::to_vec).collect::<Vec<_>>();
    for when in ["waiting", "packed"] {
        let list = api.list().filter("path", &"/search").limit(4);
        assert_eq!(pages(&list), paged(searches.clone()), "{when}");
        let backward: Vec<String> = searches.iter().rev().cloned().collect();
        assert_eq!(pages(&list.newest()), paged(backward), "{when}");
        fixture.pass(Duration::from_hours(1));
        maintain(&fixture.store).unwrap();
    }
}

// contract: REC-05
#[test]
fn a_page_of_rows_of_several_events_is_whole_up_to_its_limit_and_the_next_goes_on_from_there() {
    let fixture = fixture();
    let api = fixture.events("api");
    // a row a second, each of two events: a page of three takes two rows and is whole up to the third
    for second in 0..4_u32 {
        let name = |half: &str| NewEvent::new(&format!("{second}{half}"));
        api.append_all([name("a"), name("b").at(fixture.now() + Duration::from_millis(500))]).unwrap();
        fixture.pass(SECOND);
    }
    let read = pages(&api.list().limit(3));
    assert_eq!(read, [vec!["0a", "0b", "1a"], vec!["1b", "2a", "2b"], vec!["3a", "3b"]]);
    let warn = api.list().min_level(Level::WARN).limit(3);
    assert_eq!(pages(&warn), [Vec::<String>::new()]);
}

#[test]
fn rows_that_reach_over_a_ranges_end_are_all_read_so_that_the_next_page_begins_past_this_one() {
    let fixture = fixture();
    let api = fixture.events("api");
    let now = fixture.now();
    // three rows, each with an event before the range, one in it and one after it
    for n in 0..3_u32 {
        let outside = [NewEvent::new("before").at(now - SECOND * 60), NewEvent::new("after").at(now + SECOND * 60)];
        let inside = NewEvent::new(&n.to_string()).at(now - SECOND * (3 - n));
        api.append_all(outside.into_iter().chain([inside])).unwrap();
    }
    let ranged = api.list().from(now - SECOND * 10).to(now + SECOND * 10).limit(1);
    assert_eq!(pages(&ranged), [vec!["0"], vec!["1"], vec!["2"]]);
    assert_eq!(pages(&ranged.newest()), [vec!["2"], vec!["1"], vec!["0"]]);
}

#[test]
fn a_range_is_a_span_before_now_counted_once_or_a_start_in_it_and_an_end_not() {
    let fixture = fixture();
    let api = fixture.events("api");
    timeline(&fixture, &api, 10);
    let now = fixture.now();
    assert_eq!(names(&api.list().since(SECOND * 3).page().unwrap().events), ["6", "7", "8", "9"]);
    let ranged = api.list().from(now - SECOND * 5).to(now - SECOND * 2);
    assert_eq!(names(&ranged.page().unwrap().events), ["4", "5", "6"]);

    let first = api.list().since(SECOND * 5).limit(2).page().unwrap();
    assert_eq!(names(&first.events), ["4", "5"]);
    fixture.pass(SECOND * 3);
    let second = api.list().since(SECOND * 5).limit(2).after(&first.next.unwrap()).page().unwrap();
    assert_eq!(names(&second.events), ["6", "7"]);

    let both = api.list().since(SECOND).from(now).page().unwrap_err();
    let no_next = api.list().after("yesterday").page().unwrap_err();
    let no_page = [api.list().limit(0).page().unwrap_err(), api.list().limit(10_001).page().unwrap_err()];
    for refused in [both, no_next].iter().chain(&no_page) {
        assert_eq!(refused.kind(), ErrorKind::Invalid, "{refused}");
    }
}

#[test]
fn all_walks_every_event_a_page_at_a_time() {
    let fixture = fixture();
    let api = fixture.events("api");
    timeline(&fixture, &api, 25);
    let walked: Vec<String> = api.list().limit(10).all().map(|event| event.unwrap().name).collect();
    assert_eq!(walked, (0..25).map(|n| n.to_string()).collect::<Vec<_>>());
    let stopped: Vec<String> = api.list().newest().limit(10).all().take(3).map(|event| event.unwrap().name).collect();
    assert_eq!(stopped, ["24", "23", "22"]);
}

/// A stream with a logger's lines and events of other names.
fn mixed(fixture: &Fixture) -> Events {
    let api = fixture.events("api");
    let line = |level: Level, message: &str| NewEvent::new("log").level(level).message(message);
    api.append_all([
        line(Level::INFO, "listening").fields(&json!({ "port": 3000 })),
        line(Level::WARN, "slow request").fields(&json!({ "route": "/notes", "ms": 1200 })),
        line(Level::ERROR, "Charge failed").fields(&json!({ "order": 7, "error": { "cause": ["ECONNRESET", 104] } })),
        NewEvent::new("signup").fields(&json!({ "plan": "pro", "user": 42 })),
        NewEvent::new("role.changed").fields(&json!({ "role": "admin" })).context(&json!({ "user": 42 })),
        NewEvent::new("click").fields(&json!({ "user": "42", "x": 42.0 })).trace(TraceId([5; 16]), SpanId([6; 8])),
    ])
    .unwrap();
    api
}

#[test]
fn a_name_a_level_and_a_trace_find_their_events() {
    let fixture = fixture();
    let api = mixed(&fixture);
    let found = |list: List| names(&list.page().unwrap().events).into_iter().map(str::to_owned).collect::<Vec<_>>();
    assert_eq!(found(api.list().names(["signup", "click"])), ["signup", "click"]);
    assert_eq!(found(api.list().names(["log"])).len(), 3);
    let grave = api.list().min_level(Level::WARN).page().unwrap().events;
    assert_eq!(
        grave.iter().map(|event| event.message.as_deref().unwrap()).collect::<Vec<_>>(),
        ["slow request", "Charge failed"]
    );
    // an event without a level is found by no level
    assert_eq!(api.list().min_level(Level::TRACE).page().unwrap().events.len(), 3);
    assert_eq!(found(api.list().trace_id(TraceId([5; 16]))), ["click"]);
    assert!(found(api.list().trace_id(TraceId([9; 16]))).is_empty());
}

#[test]
fn a_filter_finds_a_key_in_the_fields_or_the_context_by_the_json_of_its_value() {
    let fixture = fixture();
    let api = mixed(&fixture);
    let found = |list: List| names(&list.page().unwrap().events).into_iter().map(str::to_owned).collect::<Vec<_>>();
    assert_eq!(found(api.list().filter("user", &42)), ["signup", "role.changed"]);
    assert_eq!(found(api.list().filter("user", &"42")), ["click"]);
    assert_eq!(found(api.list().filter("x", &42.0)), ["click"]);
    assert!(found(api.list().filter("x", &42)).is_empty());
    assert_eq!(found(api.list().filter("user", &42).filter("plan", &"pro")), ["signup"]);
    // a key is the top's own: nothing looks into a value for it
    assert!(found(api.list().filter("cause", &["ECONNRESET"])).is_empty());
}

// contract: REC-12
#[test]
fn a_key_written_twice_is_found_by_its_last_value_waiting_and_packed() {
    let fixture = fixture();
    let api = fixture.events("api");
    let twice = |name: &str, fields: &str, context: &str| {
        let mut event = NewEvent::new(name);
        (event.fields, event.context) = (Fields::read(fields).unwrap(), Fields::read(context).unwrap());
        event
    };
    api.append_all([
        twice("log", r#"{"tag": "a", "tag": "b"}"#, r#"{"component": "http", "component": "access"}"#),
        twice("click", r#"{"tag": "a"}"#, r#"{"component": "http"}"#),
    ])
    .unwrap();
    let found = |list: List| names(&list.page().unwrap().events).into_iter().map(str::to_owned).collect::<Vec<_>>();
    let finds = || {
        assert_eq!(found(api.list().filter("component", &"access")), ["log"]);
        assert_eq!(found(api.list().filter("component", &"http")), ["click"]);
        assert_eq!(found(api.list().filter("tag", &"b")), ["log"]);
        assert_eq!(found(api.list().filter("tag", &"a")), ["click"]);
    };
    finds();
    fixture.pass(Duration::from_secs(60 * 60));
    maintain(&fixture.store).unwrap();
    assert_eq!((fixture.rows("heads"), fixture.rows("blocks")), (0, 1), "packed");
    finds();
}

#[test]
fn a_search_finds_its_phrase_in_the_message_the_name_and_the_values_whatever_its_case() {
    let fixture = fixture();
    let api = mixed(&fixture);
    let found = |text: &str| {
        let events = api.list().search(text).page().unwrap().events;
        events.iter().map(|event| event.message.clone().unwrap_or_else(|| event.name.clone())).collect::<Vec<_>>()
    };
    assert_eq!(found("charge FAILED"), ["Charge failed"]);
    assert_eq!(found("econnreset"), ["Charge failed"]);
    assert_eq!(found("104"), ["Charge failed"]);
    assert_eq!(found("Role."), ["role.changed"]);
    assert_eq!(found("/NOTES"), ["slow request"]);
    assert_eq!(found("admin"), ["role.changed"]);
    // a key is no value, and a phrase is whole
    assert!(found("route").is_empty());
    assert!(found("cause").is_empty());
    assert!(found("failed charge").is_empty());
}

/// What three reads take over a corpus the Go engine wrote, packed: an exact
/// filter, a single trace and an absent context value. Run by hand with
/// `TINYSTORE_READS=<the lines>` and `--release -- --ignored --nocapture`.
#[test]
#[ignore = "a measurement, run by hand"]
fn three_reads_of_a_packed_corpus() {
    #[derive(serde::Deserialize)]
    struct Line {
        at: u64,
        name: String,
        level: i32,
        body: String,
        fields: Vec<(String, String)>,
        context: Vec<(String, String)>,
        trace: Option<String>,
        span: Option<String>,
    }
    let Ok(path) = std::env::var("TINYSTORE_READS") else { return };
    let object = |pairs: &[(String, String)]| {
        let pairs: Vec<String> =
            pairs.iter().map(|(key, json)| format!("{}:{json}", serde_json::Value::from(key.as_str()))).collect();
        serde_json::value::RawValue::from_string(format!("{{{}}}", pairs.join(","))).unwrap()
    };
    let bytes = |text: &str| -> Vec<u8> {
        (0..text.len()).step_by(2).map(|at| u8::from_str_radix(&text[at..at + 2], 16).unwrap()).collect()
    };
    let fixture = fixture();
    let api = fixture.events("api");
    let base = fixture.now() - Duration::from_secs(30 * 60);
    let text = std::fs::read_to_string(path).unwrap();
    let mut events = Vec::new();
    let mut trace = None;
    for (place, line) in text.lines().enumerate() {
        let line: Line = serde_json::from_str(line).unwrap();
        let mut event = NewEvent::new(&line.name).at(base + Duration::from_nanos(line.at)).level(Level::of(line.level));
        event = event.message(&line.body).fields(&object(&line.fields)).context(&object(&line.context));
        if let (Some(trace_id), Some(span)) = (&line.trace, &line.span) {
            let (trace_id, span) =
                (TraceId(bytes(trace_id).try_into().unwrap()), SpanId(bytes(span).try_into().unwrap()));
            if place == 64 * 500 {
                trace = Some(trace_id);
            }
            event = event.trace(trace_id, span);
        }
        events.push(event);
    }
    while !events.is_empty() {
        let rest = events.split_off(events.len().min(1000));
        api.append_all(std::mem::replace(&mut events, rest)).unwrap();
    }
    fixture.pass(Duration::from_secs(2 * 60 * 60));
    let done = super::super::maintain::maintain(&fixture.store).unwrap();
    println!("rust packed {} events into {} segments", done.packed, done.segments);
    let read = |name: &str| match name {
        "exact" => api.list().names(["request"]).filter("route", &"/route/7").filter("status", &500),
        "trace" => api.list().trace_id(trace.unwrap()),
        _ => api.list().filter("host", &"nowhere"),
    };
    for name in ["exact", "trace", "absent"] {
        let run = || read(name).limit(10_000).all().map(Result::unwrap).count();
        let found = (0..3).fold(0, |_, _| run());
        let mut runs: Vec<Duration> = (0..15)
            .map(|_| {
                let started = std::time::Instant::now();
                (0..10).for_each(|_| assert_eq!(run(), found));
                started.elapsed() / 10
            })
            .collect();
        runs.sort();
        let ms = |span: Duration| span.as_secs_f64() * 1000.0;
        println!("rust read={name:<7} found={found:<5} median={:.3}ms min={:.3}ms", ms(runs[7]), ms(runs[0]));
    }
}

#[test]
fn a_read_passes_a_block_whose_segment_or_filters_say_it_holds_nothing_asked() {
    let fixture = fixture();
    let api = fixture.events("api");
    let traced = TraceId([7; 16]);
    let request = |n: usize| {
        let event =
            NewEvent::new("request").fields(&json!({ "request": format!("r-{n:03}"), "user": format!("u-{n:03}") }));
        let event = event.context(&json!({ "host": "web", "user": "from-context" }));
        if n == 5 { event.trace(traced, SpanId([1; 8])) } else { event }
    };
    api.append_all((0..32).map(request)).unwrap();
    fixture.pass(Duration::from_secs(60 * 60));
    super::super::maintain::maintain(&fixture.store).unwrap();
    let records = fixture.records();
    let block = |connection: &Connection| {
        let row = connection.query_row("select id, segment from blocks", [], |row| Ok((row.get(0)?, row.get(1)?)));
        Ok(row.unwrap())
    };
    let (id, segment) = records.file.read(block).unwrap();
    let picked = Picked { kind: Kind::Block, id, segment, stream: 1, first_at: 0, last_at: 0, events: 32, size: 0 };
    let may_find = |list: List| {
        let query = &list.query;
        records
            .file
            .read(|connection| Passing { query, connection, segments: HashMap::new() }.may_find(&picked))
            .unwrap()
    };
    assert!(may_find(api.list().trace_id(traced)));
    assert!(!may_find(api.list().trace_id(TraceId([8; 16]))));
    assert!(may_find(api.list().filter("request", &"r-005")));
    assert!(!may_find(api.list().filter("request", &"r-999")));
    assert!(!may_find(api.list().names(["missing"])));
    assert!(!may_find(api.list().filter("tenant", &7)));
    // a context holds no filter of its own, so a value it may hold passes no block
    assert!(may_find(api.list().filter("host", &"nowhere")));
    // nor does a field whose key a context has too
    assert!(may_find(api.list().filter("user", &"from-context")));
    assert!(may_find(api.list().names(["missing", "request"]).filter("request", &"r-031")));
}

#[test]
fn a_read_walks_the_time_index_from_the_end_of_its_range_it_begins_at() {
    let fixture = super::super::fixture::fixture();
    let plans = [
        (HEADS_OLDEST, "heads_by_first (first_at<?)"),
        (HEADS_NEWEST, "heads_by_last (last_at>?)"),
        (BLOCKS_OLDEST, "blocks_by_first (first_at<?)"),
        (BLOCKS_NEWEST, "blocks_by_last (last_at>?)"),
    ];
    for (sql, walked) in plans {
        let plan = fixture.records().file.read(|connection| {
            let mut explain = connection.prepare(&format!("explain query plan {sql}")).unwrap();
            let params = rusqlite::params![0, 1, 0, None::<String>];
            let details = explain.query_map(params, |row| row.get::<_, String>(3)).unwrap();
            Ok(details.map(Result::unwrap).collect::<Vec<_>>().join("; "))
        });
        let plan = plan.unwrap();
        assert!(plan.contains(walked), "{sql}: {plan}");
    }
}

#[test]
fn a_read_finds_the_events_of_blocks_of_every_size() {
    for count in [1, 2, 1023, 1024, 1025, 2049] {
        let fixture = super::super::fixture::fixture();
        let api = fixture.events("api");
        let first = fixture.now() - std::time::Duration::from_millis(count);
        let at = |n: u64| first + std::time::Duration::from_millis(n);
        api.append_all((0..count).map(|n| crate::records::NewEvent::new(&format!("e{n}")).at(at(n)))).unwrap();
        fixture.pass(std::time::Duration::from_secs(3601));
        crate::records::maintain(&fixture.store).unwrap();
        assert_eq!(fixture.rows("heads"), 0, "all {count} packed");
        let read: Vec<String> = api.list().all().map(|event| event.unwrap().name).collect();
        let written: Vec<String> = (0..count).map(|n| format!("e{n}")).collect();
        assert_eq!(read, written, "{count}");
    }
}

#[test]
fn a_page_or_a_count_whose_token_was_cancelled_fails_cancelled() {
    // contract: STORE-09
    let fixture = fixture();
    let api = fixture.events("api");
    timeline(&fixture, &api, 5);
    let token = crate::CancellationToken::new();
    token.cancel();
    let page = token.run(|| api.list().page()).unwrap_err();
    assert_eq!(page.kind(), ErrorKind::Cancelled, "{page}");
    let counted = token.run(|| api.list().count()).unwrap_err();
    assert_eq!(counted.kind(), ErrorKind::Cancelled, "{counted}");
    assert_eq!(api.list().page().unwrap().events.len(), 5, "a read without the token answers");
}