osmflow 0.15.0

Fast, parallel reading of OpenStreetMap PBF files, and node location stores, from a city extract to the planet
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
//! Finding the diff of a stream that a time falls in, and planning a catch-up over streams of several granularities
//! (day, hour, minute) that downloads each change once.
//!
//! Both work on state files alone, read through [`StateSource`], so they do no I/O of their own: a [`Replication`]
//! reads them from a directory or a server, and a program can read them from wherever it keeps them.
//!
//! [`Replication`]: crate::osc::Replication

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use std::{io, thread};

use tracing::{debug, debug_span, trace};

use crate::Timestamp;
use crate::osc::{OscError, Replication, State};

/// How long after its timestamp a change may first show in a diff: six minutes.
///
/// The API server gives a change its timestamp while it saves it, and the change shows in the first diff cut after
/// the save commits, so a change can be older than diffs cut before it. A diff's state is the newest timestamp of its
/// changes, so a state can also be older than the one before it, by as much. The OSM web servers end a request after
/// 300 seconds, so an upload commits at most that long after it starts, and the change then shows in the next minute
/// diff: six minutes covers both. On the planet's minute stream, over the 1842 diffs 7364100 to 7365941 of November
/// 2026, the latest change came 42 seconds after the state of the diff before its own, and no state was older than
/// the one before it. A plan reads diffs from this much before a snapshot's time, so its first ones may repeat changes
/// the snapshot has, and looks this far around each place it changes streams. The tests take their delays from it.
pub const COMMIT_DELAY: Duration = Duration::from_millis(DELAY_MS.unsigned_abs());

/// [`COMMIT_DELAY`] in milliseconds, as timestamps are.
const DELAY_MS: i64 = 6 * 60_000;

/// The state files of one replication stream: what [`locate`] and [`plan`] read.
///
/// A stream's states are expected in one run of sequences, up to [`latest`](Self::latest): older ones may be gone,
/// as servers delete old diffs, but none is missing in between. Their timestamps go up with their sequences, or down
/// by [`COMMIT_DELAY`] at most.
pub trait StateSource {
    /// The stream's latest state.
    fn latest(&self) -> Result<State, OscError>;

    /// The state of diff `sequence`, or `None` if the stream does not have it: deleted as too old, or not published
    /// yet. Errors are for failures to read, which end a search.
    fn get(&self, sequence: u64) -> Result<Option<State>, OscError>;

    /// Reads ahead the states of `sequences`, which a plan is about to [`get`](Self::get) one after another, so that
    /// they are there when asked for. A source that downloads them does so [`PARALLEL`] at a time, and leaves an
    /// error for `get` to report; by default, nothing is read ahead.
    fn prefetch(&self, sequences: RangeInclusive<u64>) {
        let _ = sequences;
    }
}

/// The most states read ahead for one scan, however irregular the stream.
const MAX_AHEAD: u64 = 64;

/// The most state files a source downloads at once, reading ahead. A state file is a few hundred bytes, so this
/// is set by how many requests a server takes at once, unlike [`Replication::with_read_ahead`], which is set by the
/// memory decoded diffs take.
pub const PARALLEL: usize = 3;

/// Calls `read` for each of `sequences`, on up to [`PARALLEL`] threads, for a source whose reads keep what they read;
/// on this thread alone for one.
pub(crate) fn read_ahead(sequences: &[u64], read: impl Fn(u64) + Sync) {
    if let [sequence] = sequences {
        read(*sequence);
        return;
    }
    let next = AtomicUsize::new(0);
    thread::scope(|scope| {
        for _ in 0..sequences.len().min(PARALLEL) {
            scope.spawn(|| {
                while let Some(&sequence) = sequences.get(next.fetch_add(1, Ordering::Relaxed)) {
                    read(sequence);
                }
            });
        }
    });
}

/// The states of a stream read through a [`Replication`]: a state file it has not cached is downloaded once, then
/// read from the cache. A state the directory or the server does not have is `None`.
impl StateSource for Replication {
    fn latest(&self) -> Result<State, OscError> {
        self.state()
    }

    fn get(&self, sequence: u64) -> Result<Option<State>, OscError> {
        match self.sequence_state(sequence) {
            Ok(state) => Ok(Some(state)),
            Err(OscError::NotFound { .. } | OscError::NotPublished { .. }) => Ok(None),
            Err(OscError::File { source, .. }) if source.kind() == io::ErrorKind::NotFound => {
                Ok(None)
            }
            Err(e) => Err(e),
        }
    }

    /// Downloads the state files of `sequences` that are not cached yet, [`PARALLEL`] at a time; a local directory
    /// has nothing to read ahead.
    fn prefetch(&self, sequences: RangeInclusive<u64>) {
        if self.is_remote() {
            let missing: Vec<u64> = sequences.filter(|&s| !self.has_state_file(s)).collect();
            read_ahead(&missing, |sequence| {
                let _ = self.sequence_state(sequence);
            });
        }
    }
}

/// Where a time falls in a stream, from [`locate`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Located {
    /// The last state at or before the time.
    At(State),
    /// The time is before the oldest state the stream still has, given here: what came before it is not known.
    BeforeOldest(State),
}

/// Finds where the time `at` falls in a stream: the last state at or before it.
///
/// It reads state files only, never a diff: the latest state, then a few others. Diffs come at nearly fixed intervals,
/// so the number of the one sought is estimated from the times of the states read so far, which takes 2 to 4 more
/// reads on a regular stream. Each estimate that misses doubles the next step, and a range that an estimate does not
/// halve is halved instead, so a stream with outages takes at most about twice the reads of a binary search: some 50
/// for the planet's minute stream. Where states are older than ones before them, the state found is at or before the
/// time, though a later one may be too.
///
/// A change can show up in a diff up to [`COMMIT_DELAY`] after its timestamp, so after a snapshot's time [`plan`]
/// starts that much earlier.
pub fn locate(source: &(impl StateSource + ?Sized), at: Timestamp) -> Result<Located, OscError> {
    let latest = source.latest()?;
    locate_from(source, latest, at.as_millis())
}

/// [`locate`], from the stream's latest state.
fn locate_from(
    source: &(impl StateSource + ?Sized),
    latest: State,
    t: i64,
) -> Result<Located, OscError> {
    let _span = debug_span!("locate", at = %Timestamp::from_millis(t)).entered();
    let located = search(source, latest, t)?;
    match located {
        Located::At(state) => {
            debug!(
                sequence = state.sequence,
                state_ms = state.timestamp.as_millis(),
                "located"
            );
        }
        Located::BeforeOldest(oldest) => {
            debug!(oldest = oldest.sequence, "before the oldest state");
        }
    }
    Ok(located)
}

/// [`locate_from`], without its span.
fn search(
    source: &(impl StateSource + ?Sized),
    latest: State,
    t: i64,
) -> Result<Located, OscError> {
    if latest.timestamp.as_millis() <= t {
        return Ok(Located::At(latest));
    }
    // `hi` is always a state after `t`.
    let mut hi = latest;

    // First a state at or before `t`, stepping back from the latest. Once a probe finds no state, the oldest one is
    // somewhere between it and `hi`, and the probes halve that range.
    let mut missing: Option<u64> = None;
    let mut step = 1;
    let mut rate = None;
    let lo = loop {
        let floor = missing.map_or(0, |m| m + 1);
        if hi.sequence <= floor {
            return Ok(Located::BeforeOldest(hi));
        }
        let probe = match (missing, rate) {
            (Some(m), _) => m + (hi.sequence - m) / 2,
            (None, Some(ms_per_diff)) => {
                // Aim a little past the estimate, so the probe is most likely before `t`.
                let estimate = sequences_in(hi.timestamp.as_millis() - t, ms_per_diff);
                let estimate = estimate + estimate / 256 + 2;
                step = estimate.max(step * 2);
                hi.sequence.saturating_sub(step).max(floor)
            }
            (None, None) => hi.sequence - 1,
        };
        let state = source.get(probe)?;
        trace!(probe, ?state, "probe before the time");
        match state {
            Some(state) if state.timestamp.as_millis() <= t => break state,
            Some(state) => {
                rate = ms_per_diff(state, hi).or(rate);
                hi = state;
            }
            None => missing = Some(probe),
        }
    };

    between(source, lo, hi, t).map(Located::At)
}

/// The state at or before `t` whose next is after it, between `lo`, at or before `t`, and `hi`, after it: the range
/// narrowed by estimates, or halved when an estimate did not halve it.
fn between(
    source: &(impl StateSource + ?Sized),
    mut lo: State,
    mut hi: State,
    t: i64,
) -> Result<State, OscError> {
    let mut halve = false;
    while hi.sequence - lo.sequence > 1 {
        let width = hi.sequence - lo.sequence;
        let probe = if halve {
            lo.sequence + width / 2
        } else {
            let estimate = interpolate(lo, hi, t);
            estimate.clamp(lo.sequence + 1, hi.sequence - 1)
        };
        let state = source.get(probe)?;
        trace!(probe, ?state, "probe between");
        let Some(state) = state else {
            return Err(OscError::StateGap { sequence: probe });
        };
        if state.timestamp.as_millis() <= t {
            lo = state;
        } else {
            hi = state;
        }
        halve = !halve && (hi.sequence - lo.sequence) * 2 > width;
    }
    Ok(lo)
}

/// The milliseconds per diff between two states, `a` before `b`; `None` if they are out of order.
#[expect(clippy::cast_precision_loss, reason = "an estimate")]
fn ms_per_diff(a: State, b: State) -> Option<f64> {
    let (diffs, ms) = (
        b.sequence.checked_sub(a.sequence)?,
        b.timestamp.as_millis() - a.timestamp.as_millis(),
    );
    (diffs > 0 && ms > 0).then(|| ms as f64 / diffs as f64)
}

/// The number of diffs that take `ms` at `ms_per_diff`, rounded up.
#[expect(
    clippy::cast_precision_loss,
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "an estimate, which saturates"
)]
fn sequences_in(ms: i64, ms_per_diff: f64) -> u64 {
    (ms as f64 / ms_per_diff).ceil() as u64
}

/// The sequence `t` falls at between `lo` and `hi`, as if diffs came at even intervals between them.
fn interpolate(lo: State, hi: State, t: i64) -> u64 {
    let (span, offset) = (
        i128::from(hi.timestamp.as_millis() - lo.timestamp.as_millis()),
        i128::from(t - lo.timestamp.as_millis()),
    );
    let width = i128::from(hi.sequence - lo.sequence);
    let at = i128::from(lo.sequence) + offset * width / span.max(1);
    u64::try_from(at).unwrap_or(lo.sequence)
}

/// Where a [`plan`] starts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Start {
    /// After a state of one of the streams, by its index in the list given to [`plan`]: where a step of an earlier
    /// plan ended, or the replication sequence in a file's header, as Geofabrik's extracts give it.
    After {
        /// The stream's index.
        stream: usize,
        /// The state of the last diff already applied.
        state: State,
    },
    /// After a time: every change made after it, and none made at or before it, from the first diff whose state is
    /// after it. A diff's state is the newest timestamp of its changes, so each change made after the time is in such
    /// a diff.
    Time {
        /// The time.
        at: Timestamp,
    },
    /// After a snapshot of the database whose newest change is at `at`: the replication timestamp in a planet file's
    /// header, which has no sequence. A change the snapshot does not have
    /// committed after it was taken, and can be up to [`COMMIT_DELAY`] older than that, so the plan starts as
    /// [`Start::Time`] does from `COMMIT_DELAY` before the timestamp, and its first diffs may repeat changes the
    /// snapshot has.
    Snapshot {
        /// The newest timestamp in the snapshot.
        at: Timestamp,
    },
}

/// A run of diffs of one stream, from [`plan`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Step {
    /// The stream's index in the list given to [`plan`].
    pub stream: usize,
    /// The state the first diff continues from: of the diff before it.
    pub from: State,
    /// The state of the last diff.
    pub to: State,
}

impl Step {
    /// The diffs to read, as [`Replication::diffs`] takes them.
    #[must_use]
    pub fn sequences(&self) -> RangeInclusive<u64> {
        self.from.sequence + 1..=self.to.sequence
    }
}

/// Plans reading the changes after `start` up to `until` (or the latest state of the last stream), over `streams`
/// ordered from the coarsest to the finest, such as the planet's day, hour and minute streams. Finer diffs lead up to
/// where a coarser stream's diff starts, as many whole coarser diffs follow as fit, and finer ones again cover the
/// rest. Ten days behind on the planet is then about 10 day diffs and some tens of hour and minute diffs on either
/// side, instead of 14,400 minute diffs. The last step's stream and `to` are the [`Start::After`] of the next plan.
///
/// Each coarser stream is expected to be made from the next finer one as `osmosis --merge-replication-files` makes
/// the planet's: a coarser diff holds the finer diffs after the ones the diff before it holds, up to the last before
/// the first whose state is after its own, and its state's timestamp is on its interval. Where it ends in the finest
/// stream is then found from the finest states around its time, and no change is read twice. After an outage of the
/// stream it is merged from, longer than its interval, the coarser diff in which that stream resumes may have been
/// cut early, holding only the first diff after the outage, which no state shows: where the plan steps down to finer
/// diffs there, it starts them from that diff, and where it steps up, the finer diffs it reads first may be in the
/// coarser diffs too. The changes read twice come as whole versions of their objects, so applying them again changes
/// nothing, and a reader that counts changes drops each (type, ID, version) it has seen.
///
/// Only state files are read, never a diff: each stream's latest state, then some around each place the plan changes
/// streams, which a [`Replication`] caches: some 60 for 10 days of the planet's three streams, in this module's tests.
/// A coarser stream that has no whole diff in a stretch is left out of it. The finest stream must go back to the
/// start, or the plan is an [`OscError::TooOld`] error.
///
/// ```
/// use std::path::Path;
///
/// use osmflow::osc::{OscError, Replication, Start, StateSource, plan};
///
/// /// Applies the planet's changes after `start`, kept in `dir/day`, `dir/hour` and `dir/minute`; with the `http`
/// /// feature, `Replication::http` downloads them there from `https://planet.openstreetmap.org/replication/day` and
/// /// so on. Returns where the next catch-up starts.
/// fn catch_up(dir: &Path, start: Start) -> Result<Start, OscError> {
///     let streams = ["day", "hour", "minute"].map(|s| Replication::local(dir.join(s)));
///     let sources: Vec<&dyn StateSource> = streams.iter().map(|s| s as &dyn StateSource).collect();
///     let mut reached = start;
///     for step in plan(&sources, start, None)? {
///         for diff in streams[step.stream].diffs(step.sequences())? {
///             let diff = diff?;
///             // ... apply `diff.changes`, then keep the position reached:
///             reached = Start::After { stream: step.stream, state: diff.state };
///         }
///     }
///     Ok(reached)
/// }
/// ```
pub fn plan(
    streams: &[&dyn StateSource],
    start: Start,
    until: Option<Timestamp>,
) -> Result<Vec<Step>, OscError> {
    let _span = debug_span!("plan", streams = streams.len(), ?start, ?until).entered();
    let Some((&finest, coarser)) = streams.split_last() else {
        return Ok(Vec::new());
    };
    let fine = Fine {
        known: Known::new(coarser.len(), finest)?,
    };
    let coarser = coarser
        .iter()
        .enumerate()
        .map(|(index, &source)| Coarse::new(index, source))
        .collect::<Result<Vec<_>, _>>()?;
    let from = match start {
        Start::Time { at } => fine.after(at.as_millis())?,
        Start::Snapshot { at } => fine.after(at.saturating_sub(COMMIT_DELAY).as_millis())?,
        Start::After { stream, state } if stream == fine.known.index => state,
        Start::After { stream, state } => {
            let Some(coarse) = coarser.get(stream..) else {
                return Err(OscError::UnknownStream {
                    stream,
                    streams: streams.len(),
                });
            };
            match fine.end(state.timestamp.as_millis())? {
                Some(end) => fine.resumed(coarse, state.timestamp.as_millis(), end.low)?,
                None => return Err(fine.too_old(state.timestamp.as_millis())),
            }
        }
    };
    let to = match until {
        None => fine.known.latest,
        Some(t) => match fine.known.locate(t.as_millis())? {
            Located::At(state) => state,
            Located::BeforeOldest(_) => return Ok(Vec::new()),
        },
    };
    let mut steps = Vec::new();
    cover(&fine, &coarser, from, to, &mut steps)?;
    for step in &steps {
        debug!(
            stream = step.stream,
            first = step.from.sequence + 1,
            last = step.to.sequence,
            "step"
        );
    }
    Ok(steps)
}

/// A stream, its index in the plan's list, its latest state, and the states the plan has read of it.
struct Known<'a> {
    index: usize,
    source: &'a dyn StateSource,
    latest: State,
    seen: RefCell<BTreeMap<u64, State>>,
}

impl<'a> Known<'a> {
    fn new(index: usize, source: &'a dyn StateSource) -> Result<Self, OscError> {
        Ok(Self {
            index,
            source,
            latest: source.latest()?,
            seen: RefCell::default(),
        })
    }

    /// [`locate`], starting between the states already read nearest `t` when there is one at or before it, rather
    /// than from the latest state: the plan locates several times a few minutes apart. Where states are older than
    /// ones before them, the state found, at or before `t` with the next after it, may differ from [`locate`]'s.
    fn locate(&self, t: i64) -> Result<Located, OscError> {
        let near = {
            let seen = self.seen.borrow();
            let lo = seen
                .values()
                .rev()
                .find(|s| s.timestamp.as_millis() <= t)
                .copied();
            lo.map(|lo| {
                let hi = seen.range(lo.sequence + 1..).next().map(|(_, &s)| s);
                (lo, hi.unwrap_or(self.latest))
            })
        };
        match near {
            // Every state read after `lo` is after `t`.
            Some((lo, hi)) if hi.timestamp.as_millis() > t => {
                let _span = debug_span!("locate", at = %Timestamp::from_millis(t)).entered();
                let state = between(self, lo, hi, t)?;
                debug!(
                    sequence = state.sequence,
                    state_ms = state.timestamp.as_millis(),
                    "located near"
                );
                Ok(Located::At(state))
            }
            _ => locate_from(self, self.latest, t),
        }
    }

    /// Reads ahead the states from the one after `from` to about the first after `t`, which a scan reads in turn: as
    /// many as diffs come in that time at the rate between `from` and the latest state, and one more.
    fn prefetch_to(&self, from: State, t: i64) {
        let Some(rate) = ms_per_diff(from, self.latest) else {
            return;
        };
        let ahead = sequences_in(t - from.timestamp.as_millis(), rate)
            .saturating_add(1)
            .min(MAX_AHEAD);
        let last = from
            .sequence
            .saturating_add(ahead)
            .min(self.latest.sequence);
        self.source.prefetch(from.sequence + 1..=last);
    }

    /// The state after `state`, if the stream has one yet.
    fn next(&self, state: State) -> Result<Option<State>, OscError> {
        if state.sequence >= self.latest.sequence {
            return Ok(None);
        }
        let sequence = state.sequence + 1;
        match self.get(sequence)? {
            Some(next) => Ok(Some(next)),
            None => Err(OscError::StateGap { sequence }),
        }
    }
}

/// The stream's states, keeping each one read for [`Known::locate`].
impl StateSource for Known<'_> {
    fn latest(&self) -> Result<State, OscError> {
        Ok(self.latest)
    }

    fn get(&self, sequence: u64) -> Result<Option<State>, OscError> {
        let state = self.source.get(sequence)?;
        if let Some(state) = state {
            self.seen.borrow_mut().insert(sequence, state);
        }
        Ok(state)
    }

    fn prefetch(&self, sequences: RangeInclusive<u64>) {
        self.source.prefetch(sequences);
    }
}

/// A coarser stream, and the length of its diffs, which its states are that far apart: `None` if it has one state.
struct Coarse<'a> {
    known: Known<'a>,
    interval_ms: Option<i64>,
}

impl<'a> Coarse<'a> {
    fn new(index: usize, source: &'a dyn StateSource) -> Result<Self, OscError> {
        let known = Known::new(index, source)?;
        let before = match known.latest.sequence.checked_sub(1) {
            Some(sequence) => known.get(sequence)?,
            None => None,
        };
        let interval_ms =
            before.map(|b| known.latest.timestamp.as_millis() - b.timestamp.as_millis());
        Ok(Self { known, interval_ms })
    }
}

/// Where a coarser diff ends in the finest stream: `low` is never after the last finest diff it holds, and `high`
/// never before; they are the same diff unless a finest state is at the coarser one's time.
struct End {
    low: State,
    high: State,
}

/// The finest stream, whose diffs every other stream's diffs are made of.
struct Fine<'a> {
    known: Known<'a>,
}

impl Fine<'_> {
    /// The state before the first diff whose state is after `t`, found as [`Fine::end`] finds where a coarser diff at
    /// `t` ends.
    fn after(&self, t: i64) -> Result<State, OscError> {
        match self.end(t)? {
            Some(end) => Ok(end.high),
            None => Err(self.too_old(t)),
        }
    }

    /// The [`OscError::TooOld`] error for a position at `t` this stream does not go back to, or the error searching
    /// for its oldest state.
    fn too_old(&self, t: i64) -> OscError {
        match self.known.locate(t.saturating_sub(DELAY_MS)) {
            Ok(Located::At(oldest) | Located::BeforeOldest(oldest)) => OscError::TooOld {
                at: Timestamp::from_millis(t),
                oldest,
            },
            Err(e) => e,
        }
    }

    /// Where a coarser diff whose state is at `t` ends in this stream; `None` if this stream does not go back to it.
    fn end(&self, t: i64) -> Result<Option<End>, OscError> {
        // A state at or before `t - DELAY_MS` is before every finest diff after the coarser one, so the coarser diff
        // ends before the first state after it that is after `t`; a run of the merge that reached a state at `t`
        // ended it there.
        let Located::At(mut high) = self.known.locate(t.saturating_sub(DELAY_MS))? else {
            return Ok(None);
        };
        self.known.prefetch_to(high, t);
        let mut low = None;
        while let Some(next) = self.known.next(high)?
            && next.timestamp.as_millis() <= t
        {
            high = next;
            if high.timestamp.as_millis() == t {
                low = low.or(Some(high));
            }
        }
        Ok(Some(End {
            low: low.unwrap_or(high),
            high,
        }))
    }

    /// `low`, the `End::low` of the diff of `coarse[0]` whose state is at `t`, or where the stream it is merged from,
    /// `coarse[1]` or this one, resumed after an outage longer than the diffs of `coarse[0]`: a run of the merge that
    /// starts with such a diff writes it alone into the coarser diff, ending it early.
    fn resumed(&self, coarse: &[Coarse<'_>], t: i64, low: State) -> Result<State, OscError> {
        let merged = coarse.get(1).map_or(&self.known, |c| &c.known);
        if let Some(interval) = coarse[0].interval_ms
            && let Located::At(before) = merged.locate(t - interval)?
            && let Some(resumed) = merged.next(before)?
            && resumed.timestamp.as_millis() - before.timestamp.as_millis() > interval
        {
            let resumed = if coarse.len() > 1 {
                self.end(resumed.timestamp.as_millis())?.map(|end| end.low)
            } else {
                Some(resumed)
            };
            if let Some(resumed) = resumed
                && resumed.sequence < low.sequence
            {
                return Ok(resumed);
            }
        }
        Ok(low)
    }
}

/// Appends the steps that read the finest diffs after `from` up to `to`, with `coarser` and the finest stream.
fn cover(
    fine: &Fine<'_>,
    coarser: &[Coarse<'_>],
    from: State,
    to: State,
    steps: &mut Vec<Step>,
) -> Result<(), OscError> {
    if from.sequence >= to.sequence {
        return Ok(());
    }
    let Some((coarse, finer)) = coarser.split_first() else {
        steps.push(Step {
            stream: fine.known.index,
            from,
            to,
        });
        return Ok(());
    };
    if let Some(run) = whole(fine, coarser, from, to)? {
        cover(fine, finer, from, run.lead, steps)?;
        steps.push(Step {
            stream: coarse.known.index,
            from: run.first,
            to: run.last,
        });
        return cover(fine, finer, run.tail, to, steps);
    }
    cover(fine, finer, from, to, steps)
}

/// A run of whole diffs of a coarser stream, from [`whole`].
struct Run {
    /// The coarser state before the first diff.
    first: State,
    /// The finest state the finer diffs before the run lead up to.
    lead: State,
    /// The coarser state of the last diff.
    last: State,
    /// The finest state the finer diffs after the run start from.
    tail: State,
}

/// The whole diffs of `coarse[0]` between finest states `from` and `to`.
fn whole(
    fine: &Fine<'_>,
    coarse: &[Coarse<'_>],
    from: State,
    to: State,
) -> Result<Option<Run>, OscError> {
    let known = &coarse[0].known;
    // The first coarse diff that starts at or after `from`: the one after the first that does not end before it. One
    // that ends at `from` is most likely at its time. State 0 of a merged stream has no diff, and the diff after it
    // starts where the merge began, before state 0's time.
    let mut first = match known.locate(from.timestamp.as_millis())? {
        Located::At(state) | Located::BeforeOldest(state) => state,
    };
    let lead = loop {
        // No finest state is older than one before it by more than `DELAY_MS`, so a coarse diff whose state is more
        // than that before `from`'s ends before `from` in the finest stream too, with no need to find where.
        if first.sequence > 0
            && from.timestamp.as_millis() - first.timestamp.as_millis() <= DELAY_MS
            && let Some(end) = fine.end(first.timestamp.as_millis())?
            && end.high.sequence >= from.sequence
        {
            break end.high;
        }
        match known.next(first)? {
            Some(next) => first = next,
            None => return Ok(None),
        }
    };
    // The last that ends at or before `to`.
    let Located::At(mut last) = known.locate(to.timestamp.as_millis().saturating_add(DELAY_MS))?
    else {
        return Ok(None);
    };
    let tail = loop {
        if last.sequence <= first.sequence {
            return Ok(None);
        }
        if let Some(end) = fine.end(last.timestamp.as_millis())?
            && end.high.sequence <= to.sequence
        {
            break fine.resumed(coarse, last.timestamp.as_millis(), end.low)?;
        }
        match known.get(last.sequence - 1)? {
            Some(before) => last = before,
            None => return Ok(None),
        }
    };
    Ok(Some(Run {
        first,
        lead,
        last,
        tail,
    }))
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};
    use std::collections::BTreeSet;
    use std::rc::Rc;

    use rand::rngs::StdRng;
    use rand::{RngExt as _, SeedableRng as _};

    use super::*;

    const SECOND: i64 = 1000;
    const MINUTE: i64 = 60 * SECOND;
    const HOUR: i64 = 60 * MINUTE;
    const DAY: i64 = 24 * HOUR;

    fn ms(n: u64) -> i64 {
        i64::try_from(n).unwrap()
    }

    fn index(n: u64) -> usize {
        usize::try_from(n).unwrap()
    }

    /// A stream computed rather than stored, counting the states read: diffs `first..=last`, the state of `n` at
    /// `time(n)`, or missing where `time` gives `None`.
    struct Stream {
        first: u64,
        last: u64,
        time: Box<dyn Fn(u64) -> Option<i64>>,
        reads: Cell<usize>,
        /// The states read, which a `Replication` downloads once each.
        files: RefCell<BTreeSet<u64>>,
    }

    impl Stream {
        fn new(
            sequences: RangeInclusive<u64>,
            time: impl Fn(u64) -> Option<i64> + 'static,
        ) -> Self {
            Self {
                first: *sequences.start(),
                last: *sequences.end(),
                time: Box::new(time),
                reads: Cell::new(0),
                files: RefCell::default(),
            }
        }

        /// A stream whose every diff ends at `time(n)`.
        fn every(sequences: RangeInclusive<u64>, time: impl Fn(u64) -> i64 + 'static) -> Self {
            Self::new(sequences, move |n| Some(time(n)))
        }

        /// A stream of diffs `first..`, at `times`.
        fn of(first: u64, times: Rc<[i64]>) -> Self {
            let last = first + times.len() as u64 - 1;
            Self::new(first..=last, move |n| {
                times.get(index(n.checked_sub(first)?)).copied()
            })
        }

        fn state(&self, sequence: u64) -> State {
            let timestamp =
                Timestamp::from_millis((self.time)(sequence).expect("the stream has the state"));
            State {
                sequence,
                timestamp,
            }
        }

        /// The answer of a search, found by reading every state from the latest back.
        fn expected(&self, t: i64) -> Located {
            match (self.first..=self.last)
                .rev()
                .find(|&n| (self.time)(n).is_some_and(|ts| ts <= t))
            {
                Some(n) => Located::At(self.state(n)),
                None => Located::BeforeOldest(self.state(self.first)),
            }
        }
    }

    impl StateSource for Stream {
        fn latest(&self) -> Result<State, OscError> {
            self.reads.set(self.reads.get() + 1);
            Ok(self.state(self.last))
        }

        fn get(&self, sequence: u64) -> Result<Option<State>, OscError> {
            self.reads.set(self.reads.get() + 1);
            self.files.borrow_mut().insert(sequence);
            let kept = (self.first..=self.last).contains(&sequence);
            Ok(kept
                .then(|| (self.time)(sequence))
                .flatten()
                .map(|ms| State {
                    sequence,
                    timestamp: Timestamp::from_millis(ms),
                }))
        }
    }

    /// Searches `stream` for `t`, checks the answer, and returns the number of states read.
    fn reads(stream: &Stream, t: i64) -> usize {
        stream.reads.set(0);
        assert_eq!(
            locate(stream, Timestamp::from_millis(t)).unwrap(),
            stream.expected(t),
            "time {t}"
        );
        stream.reads.get()
    }

    #[test]
    fn a_regular_stream_takes_a_few_reads() {
        // The planet's minute stream: some 7.4 million diffs, one a minute, with a few seconds of jitter.
        let minute = Stream::every(0..=7_400_000, |n| ms(n) * MINUTE + ms(n % 7) * 1000);
        let latest = minute.state(7_400_000).timestamp.as_millis();
        for back in [
            0,
            1,
            MINUTE / 2,
            MINUTE,
            90 * MINUTE,
            10 * DAY,
            400 * DAY,
            4000 * DAY,
        ] {
            let n = reads(&minute, latest - back);
            assert!(n <= 6, "{n} reads for {back} ms back");
        }
        let fifth = minute.state(5);
        assert_eq!(
            locate(&minute, fifth.timestamp).unwrap(),
            Located::At(fifth)
        );
        assert_eq!(
            locate(&minute, Timestamp::from_millis(-1)).unwrap(),
            Located::BeforeOldest(minute.state(0))
        );
    }

    #[test]
    fn outages_repeated_times_and_deleted_diffs_are_searched_too() {
        let mut rng = StdRng::seed_from_u64(1);
        for _ in 0..50 {
            // The oldest diffs deleted, outages of up to a week, and diffs at the same time as the one before.
            let first = rng.random_range(0..2000);
            let mut t = 0;
            let times: Vec<i64> = (0..=50_000)
                .map(|_| {
                    t += match rng.random_range(0..1000) {
                        0 => rng.random_range(HOUR..7 * DAY),
                        1..10 => 0,
                        _ => rng.random_range(50_000..70_000),
                    };
                    t
                })
                .collect();
            let (oldest, latest) = (times[index(first)], t);
            let stream = Stream::new(first..=50_000, move |n| times.get(index(n)).copied());
            for _ in 0..40 {
                let n = reads(&stream, rng.random_range(oldest - DAY..latest + DAY));
                assert!(n <= 60, "{n} reads");
            }
        }
    }

    #[test]
    fn a_missing_state_between_others_is_an_error() {
        // The first estimate lands below the gap, and the next one in it.
        let stream = Stream::new(0..=1000, |n| (n != 500).then(|| ms(n) * MINUTE));
        assert!(matches!(
            locate(&stream, Timestamp::from_millis(500 * MINUTE + MINUTE / 2)),
            Err(OscError::StateGap { sequence: 500 })
        ));
    }

    /// A coarser stream made from a finer one, run by run, as `osmosis --merge-replication-files` makes it.
    #[derive(Default)]
    struct Merged {
        /// The timestamp of each coarser state, from sequence 0.
        times: Vec<i64>,
        /// The last finer diff each coarser diff holds.
        ends: Vec<u64>,
        /// When each coarser state was published: at the end of the run that wrote it.
        published: Vec<i64>,
    }

    impl Merged {
        fn push(&mut self, time: i64, end: usize, run: i64) {
            self.times.push(time);
            self.ends.push(end as u64);
            self.published.push(run);
        }
    }

    /// Merges the finer diffs from sequence 0 at `times`, published at `published`, into diffs of `interval`, running
    /// at `runs`.
    fn merge(
        times: &[i64],
        published: &[i64],
        interval: i64,
        runs: impl IntoIterator<Item = i64>,
    ) -> Merged {
        let align = |t: i64| t - t.rem_euclid(interval);
        let mut merged = Merged::default();
        // The finer diff the merge has read up to, and the end of the coarser one it writes.
        let mut local: Option<usize> = None;
        let mut end = 0;
        for run in runs {
            let Some(server) = published.iter().rposition(|&p| p <= run) else {
                continue;
            };
            let Some(start) = local else {
                // The first run writes state 0, at the next interval boundary.
                let at = align(times[server]);
                end = if at < times[server] {
                    at + interval
                } else {
                    at
                };
                merged.push(end, server, run);
                local = Some(server);
                continue;
            };
            let mut maximum = times[server];
            if maximum - times[start] > 10 * interval {
                maximum = times[start] + 10 * interval;
            }
            maximum = align(maximum);
            if merged.times.len() == 1 && maximum <= end {
                maximum -= interval;
            }
            if maximum > times[start] && maximum <= end {
                maximum = times[start];
            }
            let mut open = false;
            let mut at = start;
            while at < server && times[at] < maximum {
                let next = at + 1;
                if times[next] > maximum && at != start {
                    break;
                }
                if !open {
                    end = align(end + interval);
                    open = true;
                }
                while times[next] > end {
                    merged.push(end, at, run);
                    end += interval;
                }
                at = next;
            }
            if open {
                merged.push(end, at, run);
            }
            local = Some(at);
        }
        merged
    }

    /// The planet's streams: minutes at `minutes`, published 20 seconds after their states, and hours and days merged
    /// from them every 15 minutes.
    struct Planet {
        minutes: Rc<[i64]>,
        hours: Merged,
        days: Merged,
    }

    impl Planet {
        fn new(minutes: Vec<i64>) -> Self {
            let published: Vec<i64> = minutes.iter().map(|t| t + 20 * SECOND).collect();
            let until = published[published.len() - 1] + DAY;
            let runs = || {
                (0..)
                    .map(|k| k * 15 * MINUTE + 2 * MINUTE)
                    .take_while(move |&r| r < until)
            };
            let hours = merge(&minutes, &published, HOUR, runs());
            // The day merge runs after the hour merge, in the same minute.
            let days = merge(&hours.times, &hours.published, DAY, runs());
            Self {
                minutes: Rc::from(minutes),
                hours,
                days,
            }
        }

        fn streams(&self) -> [Stream; 3] {
            [
                Stream::of(0, Rc::from(self.days.times.as_slice())),
                Stream::of(0, Rc::from(self.hours.times.as_slice())),
                Stream::of(0, Rc::clone(&self.minutes)),
            ]
        }

        /// The last minute diff the diff `sequence` of stream `stream` holds.
        fn end(&self, stream: usize, sequence: u64) -> u64 {
            match stream {
                0 => self.hours.ends[index(self.days.ends[index(sequence)])],
                1 => self.hours.ends[index(sequence)],
                _ => sequence,
            }
        }

        /// Checks that `steps` read every minute diff after `from` up to `to` and returns how many they read twice.
        fn check(&self, steps: &[Step], from: u64, to: u64) -> u64 {
            let mut reached = from;
            let mut twice = 0;
            for step in steps {
                let (start, end) = (
                    self.end(step.stream, step.from.sequence),
                    self.end(step.stream, step.to.sequence),
                );
                assert!(
                    start <= reached,
                    "minutes {reached}..{start} are missed: {steps:?}"
                );
                assert!(end <= to, "{steps:?}");
                twice += reached.min(end) - start;
                reached = reached.max(end);
            }
            assert_eq!(reached, to.max(from), "{steps:?}");
            twice
        }
    }

    /// Minutes, each cut 0 to 59 seconds into its minute, for `days`.
    fn minutes(rng: &mut StdRng, days: i64) -> Vec<i64> {
        (1..days * 1440)
            .map(|m| m * MINUTE + rng.random_range(0..60) * SECOND)
            .collect()
    }

    fn dyns(streams: &[Stream; 3]) -> [&dyn StateSource; 3] {
        [&streams[0], &streams[1], &streams[2]]
    }

    fn after(stream: usize, state: State) -> Start {
        Start::After { stream, state }
    }

    #[test]
    fn a_search_near_states_read_before_finds_a_state_at_the_time() {
        let mut rng = StdRng::seed_from_u64(11);
        let mut times = minutes(&mut rng, 2);
        // Some minutes older than the minute before, by up to `COMMIT_DELAY`.
        for _ in 0..200 {
            let m = rng.random_range(1..times.len());
            times[m] = times[m - 1] - rng.random_range(0..DELAY_MS);
        }
        let stream = Stream::of(1, times.into());
        let known = Known::new(0, &stream).unwrap();
        // Times a few minutes apart, as a plan locates them, each after the reads of the ones before.
        let mut t = 30 * MINUTE;
        for _ in 0..300 {
            t += rng.random_range(-10..20) * MINUTE + rng.random_range(0..60) * SECOND;
            let Located::At(state) = known.locate(t).unwrap() else {
                panic!("{t} is in the stream");
            };
            assert!(state.timestamp.as_millis() <= t, "{t}");
            if let Some(next) = known.next(state).unwrap() {
                assert!(next.timestamp.as_millis() > t, "{t}");
            }
        }
    }

    #[test]
    fn the_merge_model_cuts_hours_at_their_ends() {
        let mut rng = StdRng::seed_from_u64(3);
        let planet = Planet::new(minutes(&mut rng, 3));
        let hours = planet.hours.times.iter().zip(&planet.hours.ends);
        for (h, (&t, &end)) in hours.enumerate().skip(1) {
            assert_eq!(t % HOUR, 0);
            let (last, next) = (index(end), index(end) + 1);
            assert!(planet.minutes[last] <= t, "hour {h}");
            assert!(planet.minutes.get(next).is_none_or(|&n| n > t), "hour {h}");
        }
        assert_eq!(planet.days.times[1] % DAY, 0);
    }

    #[test]
    fn a_catch_up_takes_days_then_hours_then_minutes() {
        let mut rng = StdRng::seed_from_u64(4);
        let planet = Planet::new(minutes(&mut rng, 30));
        let streams = planet.streams();
        let latest = streams[2].latest().unwrap();
        // 10 days, 5 hours and 7 minutes behind.
        let from = streams[2].state(latest.sequence - (10 * 1440 + 5 * 60 + 7));
        let steps = plan(&dyns(&streams), after(2, from), None).unwrap();
        let shape: Vec<_> = steps.iter().map(|s| s.stream).collect();
        assert_eq!(shape, [2, 1, 0, 1, 2]);
        assert_eq!(planet.check(&steps, from.sequence, latest.sequence), 0);
        let diffs: usize = steps.iter().map(|s| s.sequences().count()).sum();
        assert!(diffs < 10 + 2 * 24 + 2 * 60, "{diffs} diffs");
        // The latest state of each stream, and the state files around where the plan changes streams.
        let files: usize = streams.iter().map(|s| s.files.borrow().len()).sum();
        let reads: usize = streams.iter().map(|s| s.reads.get()).sum();
        assert!(files <= 70, "{files} state files, {reads} reads");

        // Up to a time: no diff ends after it.
        let to = latest.timestamp.as_millis() - 3 * DAY - 30 * MINUTE;
        let steps = plan(
            &dyns(&streams),
            after(2, from),
            Some(Timestamp::from_millis(to)),
        )
        .unwrap();
        let Located::At(end) = streams[2].expected(to) else {
            unreachable!()
        };
        assert_eq!(planet.check(&steps, from.sequence, end.sequence), 0);

        // From where the last step ended, in any stream: nothing more to read.
        let last = steps.last().unwrap();
        let more = plan(
            &dyns(&streams),
            after(last.stream, last.to),
            Some(Timestamp::from_millis(to)),
        )
        .unwrap();
        assert_eq!(more, []);
    }

    #[test]
    fn every_start_is_followed_by_every_change() {
        let mut rng = StdRng::seed_from_u64(5);
        let mut times = minutes(&mut rng, 20);
        // Some minutes older than the minute before, by up to half of `COMMIT_DELAY`, no two in a row.
        for _ in 0..300 {
            let m = rng.random_range(1..times.len() / 3) * 3;
            times[m] = times[m - 1] - rng.random_range(0..DELAY_MS / 2);
        }
        let planet = Planet::new(times);
        let streams = planet.streams();
        let latest = streams[2].latest().unwrap().sequence;
        for _ in 0..300 {
            let stream = rng.random_range(0..3);
            let sequence = rng.random_range(1..=streams[stream].last);
            let state = streams[stream].state(sequence);
            let steps = plan(&dyns(&streams), after(stream, state), None).unwrap();
            let twice = planet.check(&steps, planet.end(stream, sequence), latest);
            assert_eq!(twice, 0, "{steps:?}");
        }
    }

    #[test]
    fn after_an_outage_the_steps_down_start_early_enough() {
        let mut rng = StdRng::seed_from_u64(6);
        let mut times = minutes(&mut rng, 20);
        // Outages of 70 minutes to 2 days, after which the minute stream resumes with one diff of all that was missed.
        for _ in 0..12 {
            let at = rng.random_range(1000..times.len() - 4000);
            let gap = rng.random_range(70..2 * 1440);
            times.drain(at..at + gap);
        }
        let planet = Planet::new(times);
        let streams = planet.streams();
        let latest = streams[2].latest().unwrap().sequence;
        let mut overlap = 0;
        for _ in 0..300 {
            let stream = rng.random_range(0..3);
            let sequence = rng.random_range(1..=streams[stream].last);
            let state = streams[stream].state(sequence);
            let steps = plan(&dyns(&streams), after(stream, state), None).unwrap();
            overlap += planet.check(&steps, planet.end(stream, sequence), latest);
        }
        // Only where a plan steps up into an hour cut early, which its state cannot show.
        assert!(overlap < 300, "{overlap} minute diffs read twice");
    }

    #[test]
    fn snapshots_and_times_are_followed_by_every_change_after_them() {
        // Changes commit through each minute, made up to `COMMIT_DELAY` before they commit; a diff is cut at each
        // minute and its state is the newest timestamp in it. A snapshot taken at `taken` has all committed before it.
        let mut rng = StdRng::seed_from_u64(7);
        let changes: Vec<(i64, i64)> = (0..200 * 1440)
            .map(|_| {
                let commit = rng.random_range(MINUTE..2 * DAY);
                let late = if rng.random_range(0..100) == 0 {
                    rng.random_range(0..DELAY_MS)
                } else {
                    rng.random_range(0..5 * SECOND)
                };
                (commit, commit - late)
            })
            .collect();
        let cut = |commit: i64| commit.div_euclid(MINUTE) + 1;
        let mut times = vec![0; 2 * 1440 + 1];
        for &(commit, made) in &changes {
            let diff = &mut times[index(u64::try_from(cut(commit)).unwrap())];
            *diff = (*diff).max(made);
        }
        let minutes = Stream::of(0, Rc::from(times));
        for _ in 0..200 {
            let taken = rng.random_range(HOUR..2 * DAY - HOUR);
            let newest = changes
                .iter()
                .filter(|c| c.0 <= taken)
                .map(|c| c.1)
                .max()
                .unwrap();
            let steps = plan(
                &[&minutes as &dyn StateSource],
                Start::Snapshot {
                    at: Timestamp::from_millis(newest),
                },
                None,
            )
            .unwrap();
            let first = steps[0].from.sequence + 1;
            let first_missing = changes
                .iter()
                .filter(|c| c.0 > taken)
                .map(|c| cut(c.0))
                .min()
                .unwrap();
            assert!(
                ms(first) <= first_missing,
                "taken at {taken}: starts at {first}"
            );
            assert!(
                first_missing - ms(first) <= DELAY_MS / MINUTE + 2,
                "taken at {taken}: starts at {first}"
            );
        }
        // After a time: every change made after it, from the first diff whose state is after it.
        for _ in 0..200 {
            let t = rng.random_range(HOUR..2 * DAY - HOUR);
            let steps = plan(
                &[&minutes as &dyn StateSource],
                Start::Time {
                    at: Timestamp::from_millis(t),
                },
                None,
            )
            .unwrap();
            let from = steps[0].from;
            let first_made_after = changes
                .iter()
                .filter(|c| c.1 > t)
                .map(|c| cut(c.0))
                .min()
                .unwrap();
            assert!(
                ms(from.sequence) < first_made_after,
                "time {t}: after {from:?}"
            );
            assert!(from.timestamp.as_millis() <= t);
            assert!(
                minutes.state(from.sequence + 1).timestamp.as_millis() > t,
                "time {t}"
            );
        }
        assert!(matches!(
            plan(
                &[&minutes as &dyn StateSource],
                Start::Snapshot {
                    at: Timestamp::EPOCH
                },
                None
            ),
            Err(OscError::TooOld { .. })
        ));
    }

    #[test]
    fn coarse_streams_are_used_where_they_have_whole_diffs() {
        // Days end at day 38, and hours start at day 40: minutes up to day 36, two days, minutes up to day 40, hours
        // up to day 50, and minutes after.
        let streams = [
            Stream::every(30..=38, |d| ms(d) * DAY),
            Stream::every(40 * 24..=50 * 24, |h| ms(h) * HOUR),
            Stream::every(30 * 1440..=50 * 1440 + 125, |m| ms(m) * MINUTE),
        ];
        let from = streams[2].state(35 * 1440 + 120);
        let steps = plan(&dyns(&streams), after(2, from), None).unwrap();
        let shape: Vec<_> = steps
            .iter()
            .map(|s| (s.stream, s.sequences().count()))
            .collect();
        assert_eq!(
            shape,
            [(2, 22 * 60), (0, 2), (2, 2 * 1440), (1, 240), (2, 125)]
        );
        // The finest stream must reach back.
        assert!(matches!(
            plan(&dyns(&streams), after(0, streams[0].state(30)), None),
            Err(OscError::TooOld { .. })
        ));
        // A stream that is not in the list.
        assert!(matches!(
            plan(&dyns(&streams), after(3, streams[0].state(31)), None),
            Err(OscError::UnknownStream {
                stream: 3,
                streams: 3
            })
        ));
        // Caught up already: nothing to read.
        let latest = streams[2].latest().unwrap();
        assert_eq!(plan(&dyns(&streams), after(2, latest), None).unwrap(), []);
        assert_eq!(plan(&[], after(0, latest), None).unwrap(), []);
    }
}