zond-engine 0.15.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
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
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # How far a scan got
//!
//! A position in the plan below which everything is settled, and the handful of
//! positions above it that settled out of order.
//!
//! ## A position needs nothing stored to name it
//!
//! [`TargetMap::iter`](crate::model::target::TargetMap::iter) walks its units in
//! order and each unit's addresses against its ports, and a
//! [`TargetSet`](crate::model::target::TargetSet) is canonical and immutable from
//! construction. So the same plan yields the same targets in the same order on
//! every run, and the nth target is a stable identity that costs nothing to
//! record.
//!
//! That is the whole reason this is affordable. The cursor holds one integer and
//! a small set, not a list of addresses, so its size is a property of how far
//! out of order the scan settled rather than of how large the scan is. A `/8` on
//! a thousand ports checkpoints in the same handful of bytes a `/24` does.
//!
//! This enumeration is load-bearing. The dispatcher decides what to probe by it
//! and this decides what was probed by it, so the two have to be one numbering.
//! The order the targets are asked in is a different question and is nobody's
//! business here: a scan given a seed walks a
//! [`Permutation`](crate::scanner::order::Permutation) of the whole index space
//! and numbers what comes out by where the plan holds it, which it reads through
//! [`TargetIndex`](crate::model::target::TargetIndex). That the index and this
//! walk agree at every position is `model`'s own test,
//! `a_position_names_the_target_the_plans_own_walk_numbers_it`, and it is what
//! keeps the two from being two numberings.
//!
//! ## The watermark chases the settled set
//!
//! [`Cursor::settle`] records a position and then advances the watermark over
//! every consecutive settled position above it. Anything that settles out of
//! order waits in [`above`](Cursor::settled_above) until the gap below it fills.
//!
//! The set stays small on its own, with no window to size and no eviction policy
//! to get wrong. It holds only what the watermark has not caught up to, which is
//! bounded by how far the dispatcher runs ahead of the slowest outstanding probe.
//! A single tarpitting host stalls the watermark and the set grows to the
//! pipeline depth, a few tens of thousands of integers rather than a few million,
//! then collapses the moment that host settles.
//!
//! ## Only settled positions are recorded
//!
//! A position reaches here only from [`Outcome`](super::settle::Outcome)'s
//! settled variants, the only ones that carry one. A target that was interrupted,
//! never asked or never routed has no position to offer, so the watermark stalls
//! behind it and the next sitting asks again.

use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use crate::model::ip::set::{IpSet, Positions};
use crate::model::target::{PlannedTarget, Target};

/// How far a scan has got, maintained as it runs.
///
/// Cheap to update and cheap to snapshot. See the module documentation for why
/// the set stays small without being bounded explicitly.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Cursor {
    watermark: u64,
    above: BTreeSet<u64>,
}

impl Cursor {
    /// A cursor over a plan nothing has been settled in yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Resumes from a checkpoint.
    pub fn from_checkpoint(checkpoint: &Checkpoint) -> Self {
        let mut cursor = Self {
            watermark: checkpoint.watermark,
            above: checkpoint
                .settled_above
                .iter()
                .copied()
                .filter(|position| *position >= checkpoint.watermark)
                .collect(),
        };
        // A checkpoint written by a newer build, or edited by hand, may name
        // positions that are already contiguous with the watermark. Normalising
        // here means the invariant below holds however the values arrived.
        cursor.catch_up();
        cursor
    }

    /// Records that the target at `position` is settled.
    ///
    /// Idempotent: settling a position already below the watermark, or already
    /// recorded, changes nothing. A target can be reported twice, by a probe
    /// retired on its retry budget and then again by a stop path that does not
    /// know it already had a verdict.
    pub fn settle(&mut self, position: u64) {
        if position < self.watermark {
            return;
        }

        self.above.insert(position);
        self.catch_up();
    }

    /// Advances the watermark over every consecutive settled position.
    ///
    /// Saturating, because the positions come out of a cursor file this process
    /// may not have written. A planted `u64::MAX` reaches the increment, and an
    /// unchecked one panics in a debug build and wraps to zero in a release
    /// one, which silently un-settles every target the scan had finished.
    /// Saturating wedges the watermark at the ceiling instead, which is wrong
    /// in the safe direction: a resume re-probes rather than skips.
    fn catch_up(&mut self) {
        while self.above.remove(&self.watermark) {
            self.watermark = self.watermark.saturating_add(1);
        }
    }

    /// The position below which every target is settled.
    ///
    /// A resume starts here, and skips the positions above it that
    /// [`is_settled`](Self::is_settled) names.
    pub fn watermark(&self) -> u64 {
        self.watermark
    }

    /// The settled positions the watermark has not reached, ascending.
    pub fn settled_above(&self) -> impl Iterator<Item = u64> + '_ {
        self.above.iter().copied()
    }

    /// Whether the target at `position` may be skipped.
    pub fn is_settled(&self, position: u64) -> bool {
        position < self.watermark || self.above.contains(&position)
    }

    /// How many targets are settled in total.
    ///
    /// Saturating for the same reason the watermark's own advance is: the
    /// watermark can come from a file this process did not write, and a count
    /// that wrapped would report a nearly-finished scan as barely started.
    pub fn settled_count(&self) -> u64 {
        self.watermark.saturating_add(self.above.len() as u64)
    }

    /// How many settled positions are waiting on a gap below them.
    ///
    /// The size of the out-of-order window, and so the size of a checkpoint.
    /// Worth watching: a number that grows and does not fall is a target that
    /// never settles, which is a tarpit or a defect rather than a slow network.
    pub fn pending_count(&self) -> usize {
        self.above.len()
    }

    /// A snapshot to write to disk.
    pub fn checkpoint(&self) -> Checkpoint {
        Checkpoint {
            watermark: self.watermark,
            settled_above: self.above.iter().copied().collect(),
        }
    }
}

/// A cursor as it is written down.
///
/// Sparse rather than a bitmap over a fixed window. Both are bounded by how far
/// the dispatcher runs ahead, and the sparse form is far smaller in the case that
/// occurs, where a handful of positions are out of order rather than tens of
/// thousands. A bitmap only wins where the window is nearly full, which is the
/// pathological case and not one worth
/// optimising the ordinary one for.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Checkpoint {
    /// The position below which everything is settled.
    pub watermark: u64,
    /// Settled positions at or above the watermark, ascending.
    ///
    /// Ascending is an invariant, not a description: [`is_settled`](Self::is_settled)
    /// binary-searches it. [`new`](Self::new) establishes it, and [`read`](Self::read)
    /// re-establishes it on anything that arrived from a file.
    #[serde(default)]
    pub settled_above: Vec<u64>,
}

impl Checkpoint {
    /// A checkpoint over `watermark` and the settled positions above it.
    ///
    /// The list is sorted and deduplicated here, which is the invariant
    /// [`is_settled`](Self::is_settled) binary-searches on. The fields are public
    /// and this is not the only way to build one, but it is the way that cannot be
    /// built wrong, and a caller keeping journals in something other than a
    /// directory should come through it.
    pub fn new(watermark: u64, settled_above: impl IntoIterator<Item = u64>) -> Self {
        let mut settled_above: Vec<u64> = settled_above
            .into_iter()
            .filter(|position| *position >= watermark)
            .collect();
        settled_above.sort_unstable();
        settled_above.dedup();

        Self {
            watermark,
            settled_above,
        }
    }

    /// Whether the target at `position` may be skipped.
    ///
    /// Binary-searched, so [`settled_above`](Self::settled_above) has to be
    /// ascending. Everything in this module that builds one keeps it that way,
    /// and [`new`](Self::new) is how a caller does.
    pub fn is_settled(&self, position: u64) -> bool {
        position < self.watermark || self.settled_above.binary_search(&position).is_ok()
    }

    /// The addresses a resumed sweep still has to ask about.
    ///
    /// The sweep counterpart of [`remaining`](Self::remaining). It gives back a
    /// set rather than a positioned stream because a
    /// [`HostScanner`](crate::scanner::strategy::HostScanner) owns its targets and
    /// is aimed at them, and its positions come from the context. See
    /// [`ScanContext::settle_address`](crate::scanner::session::ScanContext::settle_address),
    /// which numbers an address against this same plan.
    ///
    /// Computed from the ranges, so continuing a sweep of a `/8` costs what
    /// continuing a sweep of a `/24` does. Everything below the watermark is one
    /// span to drop; above it, only the few positions that settled out of order
    /// are taken out individually. Anything the plan was too large to number
    /// comes back whole, since no checkpoint can have accounted for it.
    ///
    /// `positions` has to number the plan this checkpoint was written against. A
    /// position is an index into one enumeration, and the manifest's plan
    /// fingerprint is what refuses a resume before it reaches here.
    pub fn remaining_addresses(&self, positions: &Positions) -> IpSet {
        let mut remaining = IpSet::new();
        let total = positions.total();
        let mut from = self.watermark;

        // `settled_above` is written ascending, and a checkpoint from disk is
        // only as ordered as the file said. Sorting a copy costs nothing on the
        // window-sized list this holds and makes the walk below
        // right either way.
        let mut above = self.settled_above.clone();
        above.sort_unstable();

        for settled in above {
            if settled < from {
                continue;
            }
            for range in positions.ranges_in(from..settled) {
                remaining.insert_range(range);
            }
            from = settled.saturating_add(1);
        }

        for range in positions.ranges_in(from..total) {
            remaining.insert_range(range);
        }

        // A range too large to number holds no position, so nothing can ever
        // have been recorded against it. Every sitting asks about it again.
        for range in positions.unnumbered() {
            remaining.insert_range(*range);
        }

        remaining.canonicalize();
        remaining
    }

    /// The targets a resumed scan still has to ask about, each carrying its
    /// position in the original plan.
    ///
    /// Takes the plan's enumeration,
    /// [`TargetMap::iter`](crate::model::target::TargetMap::iter), the same walk
    /// the first sitting was numbered by, and yields only what
    /// this checkpoint does not account for.
    ///
    /// The positions are why this yields [`PlannedTarget`] rather than
    /// [`Target`]. A resumed sitting scans a subset, so numbering it afresh would
    /// give position 0 to whatever happens to be left and the two sittings'
    /// cursors would count different things. The original numbering has to
    /// survive the filtering.
    ///
    /// The plan has to be the one this checkpoint was written against. A
    /// position is an index into a specific enumeration, so a changed port list,
    /// a changed exclusion policy or a changed privilege level all move what
    /// position 4,001,927 refers to. Nothing here detects that; the manifest's
    /// plan fingerprint refuses the resume before it gets this far.
    pub fn remaining<'a, I>(&'a self, targets: I) -> impl Iterator<Item = PlannedTarget> + 'a
    where
        I: IntoIterator<Item = Target> + 'a,
    {
        targets
            .into_iter()
            .enumerate()
            .map(|(position, target)| PlannedTarget::new(position as u64, target))
            .filter(move |planned| !self.is_settled(planned.position))
    }
}

#[cfg(feature = "journal-format")]
mod persistence {
    use std::fs;
    use std::io::Write;
    use std::path::Path;

    use super::Checkpoint;
    use crate::journal::file::create_staged;
    use crate::journal::format::JournalError;

    impl Checkpoint {
        /// Writes the checkpoint so that a process killed mid-write leaves the
        /// previous one intact.
        ///
        /// Writes a sibling temporary file and renames it over the destination,
        /// which is atomic on every filesystem this engine runs on. No `fsync`:
        /// the failures this exists for, `^C` and a dropped session and an OOM
        /// kill, are process deaths, and the page cache outlives the process. A
        /// flush per checkpoint would buy protection against machine power loss
        /// alone, at a cost on every scan that survives without it. See
        /// [`journal`](crate::journal) for what that policy promises.
        ///
        /// A torn write is impossible rather than tolerated. The destination only
        /// changes by rename, so a reader sees the whole of one checkpoint or the
        /// whole of the one before it.
        pub fn write_atomically(&self, path: &Path) -> Result<(), JournalError> {
            let temporary = path.with_extension("tmp");

            // Scoped so the handle is closed before the rename. Renaming over a
            // file still held open is a hazard on platforms this may yet reach.
            {
                let mut file = create_staged(&temporary)?;
                file.write_all(serde_json::to_string(self)?.as_bytes())?;
            }

            // The destination becomes the temporary's inode, which already
            // carries the mode and the ownership `create_staged` gave it.
            fs::rename(&temporary, path)?;
            Ok(())
        }

        /// Reads a checkpoint back.
        ///
        /// The `settled_above` list is sorted on read rather than trusted, since
        /// [`is_settled`](Checkpoint::is_settled) binary-searches it and an
        /// unsorted list would answer `false` for a position that is present. That
        /// re-probes a settled target, which is safe and quietly wrong.
        pub fn read(path: &Path) -> Result<Self, JournalError> {
            let text = super::super::store::read_bounded(path, "a journal cursor")?;
            let mut checkpoint: Self = serde_json::from_str(&text)?;
            checkpoint.settled_above.sort_unstable();
            checkpoint.settled_above.dedup();
            Ok(checkpoint)
        }
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

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

    // ─── Resuming a sweep ────────────────────────────────────────────────────

    use std::net::IpAddr;

    fn addresses(written: &str) -> IpSet {
        written.parse().expect("a valid address specification")
    }

    /// What a resumed sweep asks about must be exactly what the first sitting
    /// did not settle. One address too few is a target silently skipped, which
    /// is the failure this whole module exists to prevent.
    #[test]
    fn a_resumed_sweep_asks_about_exactly_what_did_not_settle() {
        let plan = addresses("192.0.2.1-192.0.2.10");
        let positions = plan.positions();

        let checkpoint = Checkpoint {
            watermark: 3,
            settled_above: vec![5, 8],
        };

        let remaining = checkpoint.remaining_addresses(&positions);
        let found: Vec<IpAddr> = remaining.iter().collect();
        let expected: Vec<IpAddr> = plan
            .iter()
            .enumerate()
            .filter(|(position, _)| !checkpoint.is_settled(*position as u64))
            .map(|(_, ip)| ip)
            .collect();

        assert_eq!(found, expected);
        assert_eq!(
            found.len(),
            5,
            "ten addresses, three settled below, two above"
        );
    }

    /// A sweep that settled nothing comes back whole. A resume that quietly
    /// narrowed an untouched plan would lose the whole first sitting's ground.
    #[test]
    fn a_sweep_that_settled_nothing_resumes_over_the_whole_plan() {
        let plan = addresses("192.0.2.1-192.0.2.10,2001:db8::1-2001:db8::4");
        let remaining = Checkpoint::default().remaining_addresses(&plan.positions());

        assert_eq!(remaining, plan);
    }

    /// A plan holding a range too large to number comes back whole, however far
    /// the numbered part of it got. Anything else resumes a sweep of an IPv6
    /// subnet by asking about nothing and reporting that it finished.
    #[test]
    fn a_sweep_of_an_unnumberable_plan_resumes_over_all_of_it() {
        let plan = addresses("192.0.2.0/30,2001:db8::/64");
        let positions = plan.positions();

        let checkpoint = Checkpoint {
            watermark: 4,
            settled_above: Vec::new(),
        };
        let remaining = checkpoint.remaining_addresses(&positions);

        assert!(
            !remaining.is_empty(),
            "the /64 was never numbered and so was never settled"
        );
        assert_eq!(remaining.v4(), &[], "the numbered half did settle");
        assert_eq!(remaining.v6(), plan.v6());
    }

    /// And a sweep that settled everything has nothing left to ask.
    #[test]
    fn a_finished_sweep_resumes_over_nothing() {
        let plan = addresses("192.0.2.1-192.0.2.4");
        let checkpoint = Checkpoint {
            watermark: 4,
            settled_above: Vec::new(),
        };

        assert!(checkpoint.remaining_addresses(&plan.positions()).is_empty());
    }

    /// The two halves have to agree: whatever a resumed sweep is aimed at, the
    /// positions it settles are still the original plan's. An address in the
    /// narrowed set must number the same as it did in the first sitting.
    #[test]
    fn a_resumed_sweep_keeps_the_original_numbering() {
        let plan = addresses("192.0.2.1-192.0.2.10");
        let positions = plan.positions();
        let checkpoint = Checkpoint {
            watermark: 4,
            settled_above: Vec::new(),
        };

        let remaining = checkpoint.remaining_addresses(&positions);
        let first = remaining.iter().next().expect("something is left");

        assert_eq!(
            positions.find(first),
            Some(4),
            "the fifth address is still the fifth, not the first of what is left"
        );
    }

    /// A checkpoint read back from a file is only as ordered as the file said.
    #[test]
    fn an_unsorted_checkpoint_narrows_the_same_way() {
        let plan = addresses("192.0.2.1-192.0.2.10");
        let positions = plan.positions();

        let sorted = Checkpoint {
            watermark: 2,
            settled_above: vec![4, 6, 9],
        };
        let shuffled = Checkpoint {
            watermark: 2,
            settled_above: vec![9, 4, 6],
        };

        assert_eq!(
            sorted.remaining_addresses(&positions),
            shuffled.remaining_addresses(&positions)
        );
    }

    use crate::model::ip::set::IpSet;
    use crate::model::port::PortSet;
    use crate::model::target::{TargetMap, TargetSet};

    fn plan(range: &str, ports: &str) -> TargetMap {
        let mut map = TargetMap::new();
        map.add_unit(TargetSet::new(
            range.parse::<IpSet>().expect("a range"),
            ports.parse::<PortSet>().expect("ports"),
        ));
        map
    }

    /// Settling in order is the ordinary case: the watermark simply follows and
    /// nothing is ever held.
    #[test]
    fn settling_in_order_leaves_nothing_pending() {
        let mut cursor = Cursor::new();

        for position in 0..10 {
            cursor.settle(position);
            assert_eq!(cursor.watermark(), position + 1);
            assert_eq!(cursor.pending_count(), 0, "nothing should be held");
        }
    }

    /// The property the whole design rests on: one unsettled position stalls the
    /// watermark however much settles above it.
    ///
    /// If this ever passes with a higher watermark, a resumed scan skips a
    /// target nobody probed.
    #[test]
    fn one_unsettled_position_stalls_the_watermark() {
        let mut cursor = Cursor::new();

        cursor.settle(0);
        cursor.settle(1);
        // 2 is still outstanding: a tarpit, or a probe mid-retry.
        for position in 3..1_000 {
            cursor.settle(position);
        }

        assert_eq!(cursor.watermark(), 2, "the gap at 2 must hold the line");
        assert!(!cursor.is_settled(2));
        assert_eq!(cursor.settled_count(), 999);

        // And it collapses the moment the gap fills.
        cursor.settle(2);
        assert_eq!(cursor.watermark(), 1_000);
        assert_eq!(cursor.pending_count(), 0);
    }

    /// Out-of-order settling is the normal case, since the dispatcher shuffles
    /// within a batch, so the watermark has to be correct whatever order
    /// positions arrive in.
    #[test]
    fn the_watermark_is_independent_of_arrival_order() {
        let forwards = {
            let mut cursor = Cursor::new();
            for position in 0..64 {
                cursor.settle(position);
            }
            cursor
        };

        let backwards = {
            let mut cursor = Cursor::new();
            for position in (0..64).rev() {
                cursor.settle(position);
            }
            cursor
        };

        let scattered = {
            let mut cursor = Cursor::new();
            for position in [7, 3, 63, 0, 1, 2, 4, 5, 6] {
                cursor.settle(position);
            }
            for position in 8..63 {
                cursor.settle(position);
            }
            cursor
        };

        assert_eq!(forwards.watermark(), 64);
        assert_eq!(backwards.watermark(), 64);
        assert_eq!(scattered.watermark(), 64);
        assert_eq!(forwards, backwards);
        assert_eq!(forwards, scattered);
    }

    /// A target may be reported twice. Neither report may move the watermark
    /// twice, or the cursor claims a position it never heard about.
    #[test]
    fn settling_the_same_position_twice_is_idempotent() {
        let mut cursor = Cursor::new();

        cursor.settle(0);
        cursor.settle(0);
        cursor.settle(0);
        assert_eq!(cursor.watermark(), 1);

        cursor.settle(5);
        cursor.settle(5);
        assert_eq!(cursor.pending_count(), 1);
        assert_eq!(cursor.settled_count(), 2);
    }

    /// A checkpoint round-trips through the cursor without moving.
    #[test]
    fn a_cursor_survives_a_checkpoint() {
        let mut cursor = Cursor::new();
        for position in [0, 1, 2, 9, 11, 12] {
            cursor.settle(position);
        }

        let restored = Cursor::from_checkpoint(&cursor.checkpoint());

        assert_eq!(restored, cursor);
        assert_eq!(restored.watermark(), 3);
        assert!(restored.is_settled(9));
        assert!(!restored.is_settled(3));
    }

    /// The payoff: a resumed scan asks about exactly what the first sitting did
    /// not settle, in the plan's own order.
    #[test]
    fn remaining_yields_only_what_was_not_settled() {
        let map = plan("192.0.2.1-192.0.2.4", "80,443");
        let all: Vec<Target> = map.iter().collect();
        assert_eq!(all.len(), 8, "four addresses on two ports");

        let mut cursor = Cursor::new();
        for position in [0, 1, 2, 5] {
            cursor.settle(position);
        }

        let remaining: Vec<PlannedTarget> = cursor.checkpoint().remaining(map.iter()).collect();

        // The targets that were left, still carrying their positions in the
        // whole plan rather than in the remainder.
        assert_eq!(
            remaining,
            vec![
                PlannedTarget::new(3, all[3]),
                PlannedTarget::new(4, all[4]),
                PlannedTarget::new(6, all[6]),
                PlannedTarget::new(7, all[7]),
            ]
        );
    }

    /// A checkpoint that settled nothing must re-ask the whole plan, and one
    /// that settled everything must ask nothing. The two ends of the range,
    /// where an off-by-one would hide.
    #[test]
    fn the_empty_and_complete_cases_are_both_exact() {
        let map = plan("192.0.2.1-192.0.2.4", "80,443");
        let total = map.iter().count();

        let untouched = Cursor::new().checkpoint();
        assert_eq!(untouched.remaining(map.iter()).count(), total);

        let mut finished = Cursor::new();
        for position in 0..total as u64 {
            finished.settle(position);
        }
        assert_eq!(finished.checkpoint().remaining(map.iter()).count(), 0);
        assert_eq!(finished.watermark(), total as u64);
    }

    /// The cursor numbers targets by the same walk the dispatcher probes them by.
    /// Asserted rather than assumed: the two live in different modules, and a
    /// divergence would resume a scan against positions that mean something else,
    /// which looks like a working resume that skips the wrong targets.
    #[test]
    fn positions_follow_the_plans_own_enumeration() {
        let mut map = plan("192.0.2.1-192.0.2.2", "80,443");
        map.add_unit(TargetSet::new(
            "198.51.100.7".parse::<IpSet>().expect("a range"),
            "22".parse::<PortSet>().expect("ports"),
        ));

        let once: Vec<Target> = map.iter().collect();
        let twice: Vec<Target> = map.iter().collect();

        assert_eq!(once, twice, "the enumeration must be reproducible");
        assert_eq!(once.len(), 5, "two units, four targets then one");
        assert_eq!(
            once[4].ip,
            "198.51.100.7".parse::<std::net::IpAddr>().unwrap(),
            "units are walked in the order they were added"
        );
    }

    /// The checkpoint reaches disk whole, comes back identical, and replacing it
    /// leaves one file rather than a temporary beside it.
    #[cfg(feature = "journal-format")]
    #[test]
    fn a_checkpoint_round_trips_through_a_file() {
        let dir = std::env::temp_dir().join(format!(
            "zond-cursor-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        std::fs::create_dir_all(&dir).expect("scratch directory");
        let path = dir.join("cursor.json");

        let mut cursor = Cursor::new();
        for position in [0, 1, 2, 9, 11, 12] {
            cursor.settle(position);
        }

        cursor.checkpoint().write_atomically(&path).expect("writes");
        assert_eq!(Checkpoint::read(&path).expect("reads"), cursor.checkpoint());

        // Written again over itself, as every checkpoint after the first is.
        cursor.settle(3);
        cursor
            .checkpoint()
            .write_atomically(&path)
            .expect("rewrites");

        let reread = Checkpoint::read(&path).expect("rereads");
        assert_eq!(reread.watermark, 4);
        assert!(
            !dir.join("cursor.tmp").exists(),
            "the temporary file must not survive the rename"
        );

        std::fs::remove_dir_all(&dir).ok();
    }

    /// `is_settled` binary-searches, so a list that arrived unsorted would answer
    /// `false` for a position that is present. That re-probes, which is safe and
    /// silently wrong, so the reader sorts rather than trusting the file.
    #[cfg(feature = "journal-format")]
    #[test]
    fn a_checkpoint_with_an_unsorted_list_is_sorted_on_read() {
        let dir = std::env::temp_dir().join(format!(
            "zond-cursor-unsorted-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        std::fs::create_dir_all(&dir).expect("scratch directory");
        let path = dir.join("cursor.json");

        std::fs::write(&path, r#"{"watermark":2,"settled_above":[9,4,7,4]}"#).expect("writes");

        let checkpoint = Checkpoint::read(&path).expect("reads");

        assert_eq!(
            checkpoint.settled_above,
            vec![4, 7, 9],
            "sorted and deduped"
        );
        for position in [4, 7, 9] {
            assert!(checkpoint.is_settled(position), "{position} is in the file");
        }
        assert!(!checkpoint.is_settled(3));

        std::fs::remove_dir_all(&dir).ok();
    }

    /// A checkpoint naming positions below its own watermark is redundant rather
    /// than wrong, and must normalise instead of double-counting.
    #[test]
    fn a_checkpoint_with_redundant_positions_normalises() {
        let checkpoint = Checkpoint {
            watermark: 5,
            settled_above: vec![1, 2, 5, 6],
        };

        let cursor = Cursor::from_checkpoint(&checkpoint);

        assert_eq!(cursor.watermark(), 7, "5 and 6 are contiguous with 5");
        assert_eq!(cursor.pending_count(), 0);
        assert_eq!(cursor.settled_count(), 7);
    }
}