kshana 0.37.0

Open, reproducible PNT-resilience simulator with quantum-sensor performance models
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
// SPDX-License-Identifier: AGPL-3.0-only
//! **Lock state machine and streaming tracking sessions.**
//!
//! A [`TrackSession`] runs a set of channels over a sample stream in bounded memory. Every
//! loop update goes to an [`EpochSink`] as it happens, so nothing grows with the recording's
//! length. Each channel carries a lock state ([`LockState`]):
//!
//! * `PULL_IN` → `LOCKED` once phase and code lock have both held for `loss_dwell_s`;
//! * `LOCKED` → `LOST` once phase or code lock has been lost for `loss_dwell_s`;
//!   `PULL_IN` → `LOST` after `pull_in_max_s` without lock;
//! * a **false-lock check** runs on every tracking channel (pull-in, locked or lost): every
//!   `cn0_windows` updates the next few milliseconds of samples are searched at the tracked
//!   Doppler and at the ±1/(2T) FLL/PLL ambiguity, `T` being the loop's integration time.
//!   An alias bin stronger than the tracked bin by `false_lock_margin_db` is a false lock:
//!   the channel goes to `LOST`, and its re-acquisition (if enabled) is centred on the
//!   alias;
//! * with `reacquire` on, a `LOST` channel goes to `REACQ`: the next samples are searched
//!   ±`reacq_doppler_window_hz` around its last (or alias) Doppler, and on detection the
//!   channel restarts from that hand-off (`PULL_IN`). A failed search is retried after
//!   `reacq_interval_s` (0.1 s by default, evenly spaced; an optional back-off doubles the
//!   wait up to `reacq_max_interval_s`). A channel that has not
//!   locked again within `reacq_window_s` of being lost (or that used up the optional
//!   `max_reacq_attempts`) is `RETIRED` and stops. With `reacquire` off (the built-in
//!   default) the state machine only observes: the loops run exactly as without it, and a
//!   `LOST` channel returns to `LOCKED` when its locks hold again and no false lock is
//!   suspected.
//!
//! Every transition is an event ([`LockEvent`]) with its reason.

use super::channel::{Channel, ChannelInit, EpochOutput};
use super::design::{AcquisitionDesign, Design, LockConfig};
use super::sink::EpochSink;
use super::LoopConfig;
use crate::iq::acq::{acquire, samples_needed, AcqConfig};
use crate::iq::{Cf64, IqError, IqSource, SampleSpec};
use crate::portable_math::PortableFloat;
use serde::{Deserialize, Serialize};

/// Samples read from a source per chunk.
const CHUNK: usize = 1 << 16;

/// A channel's lock state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LockState {
    /// Loops converging after a hand-off.
    PullIn,
    /// Phase and code lock held.
    Locked,
    /// Lock lost, or a false lock detected.
    Lost,
    /// Re-acquisition search under way (the previous loops keep running meanwhile).
    Reacq,
    /// Given up after too many failed re-acquisitions; the channel stops.
    Retired,
}

impl LockState {
    /// `PULL_IN`, `LOCKED`, `LOST`, `REACQ` or `RETIRED`.
    pub fn as_str(self) -> &'static str {
        match self {
            LockState::PullIn => "PULL_IN",
            LockState::Locked => "LOCKED",
            LockState::Lost => "LOST",
            LockState::Reacq => "REACQ",
            LockState::Retired => "RETIRED",
        }
    }
    /// The binary record's code (0..=4).
    pub fn code(self) -> u8 {
        self as u8
    }
    /// The state a binary code names.
    pub fn from_code(c: u8) -> Option<Self> {
        Some(match c {
            0 => LockState::PullIn,
            1 => LockState::Locked,
            2 => LockState::Lost,
            3 => LockState::Reacq,
            4 => LockState::Retired,
            _ => return None,
        })
    }
}

/// One lock-state transition or check result.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LockEvent {
    /// Channel index.
    pub channel: u32,
    /// The channel's next loop-update index when the event happened.
    pub epoch: u64,
    /// Stream sample at which the event was decided.
    pub sample_index: u64,
    /// Time of the last code epoch (s).
    pub code_epoch_s: f64,
    /// State before.
    pub from: LockState,
    /// State after.
    pub to: LockState,
    /// `locked`, `recovered`, `loss-of-lock`, `pull-in-timeout`, `false-lock`,
    /// `reacq-start`, `reacquired`, `reacq-failed` or `retired`.
    pub reason: String,
    /// Doppler involved (Hz): the alias of a false lock, the result of a re-acquisition.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doppler_hz: Option<f64>,
    /// Code phase found by a re-acquisition (chips, at its first searched sample).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub code_phase_chips: Option<f64>,
    /// The search's peak statistic (a re-acquisition), or the alias-to-tracked power ratio
    /// in dB (a false-lock check).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub statistic: Option<f64>,
    /// The search's threshold (a re-acquisition), or the margin in dB (a false-lock check).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
}

/// Everything one session channel needs: what it tracks, its loops, its lock state machine
/// and its (re-)acquisition search.
#[derive(Clone, Debug)]
pub struct SessionChannel {
    /// The hand-off.
    pub init: ChannelInit,
    /// The loop design.
    pub config: LoopConfig,
    /// The lock state machine.
    pub lock: LockConfig,
    /// The re-acquisition search (Doppler window from `lock`).
    pub acquisition: AcquisitionDesign,
}

impl SessionChannel {
    /// A channel tracking `init` with loop design `d`.
    pub fn from_design(init: ChannelInit, d: &Design) -> Self {
        let config = d.loop_config_for(init.code.period_s());
        Self {
            init,
            config,
            lock: d.lock_config(),
            acquisition: d.acquisition().clone(),
        }
    }

    /// A channel with an ad-hoc loop configuration and the default lock state machine
    /// (observing only) and acquisition.
    pub fn from_config(init: ChannelInit, config: LoopConfig) -> Self {
        Self {
            init,
            config,
            lock: LockConfig::default(),
            acquisition: AcquisitionDesign::default(),
        }
    }
}

/// What a sample collection is for.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Purpose {
    /// Check the tracked Doppler `center` against its ±`alias_hz` aliases.
    FalseLock { center: f64, alias_hz: f64 },
    /// Search ±window around `center`.
    Reacq { center: f64 },
}

/// Samples gathered for a search, from absolute stream sample `start`.
#[derive(Clone, Debug)]
struct Collect {
    purpose: Purpose,
    start: u64,
    cfg: AcqConfig,
    need: usize,
    buf: Vec<Cf64>,
}

/// One channel under the state machine.
struct Managed {
    setup: SessionChannel,
    ch: Option<Channel>,
    state: LockState,
    state_since_s: f64,
    good_since: Option<f64>,
    bad_since: Option<f64>,
    updates_since_check: usize,
    attempts: u32,
    lost_since: Option<f64>,
    next_attempt_s: f64,
    reacq_interval_s: f64,
    suspect: bool,
    check_unavailable: bool,
    reacq_center: f64,
    next_epoch: u64,
    last_t: f64,
    loop_t: f64,
    collect: Option<Collect>,
    /// This channel's loop updates of the chunk being processed.
    scratch: Vec<EpochOutput>,
}

/// A set of channels run over one stream in bounded memory, with the lock state machine.
pub struct TrackSession {
    spec: SampleSpec,
    chans: Vec<Managed>,
    consumed: u64,
    threads: usize,
}

impl TrackSession {
    /// A session on a stream sampled as `spec`.
    pub fn new(spec: SampleSpec, channels: Vec<SessionChannel>) -> Result<Self, String> {
        let chans = channels
            .into_iter()
            .map(|setup| {
                let ch = Channel::new(&spec, &setup.init, &setup.config)?;
                Ok(Managed {
                    reacq_center: setup.init.doppler_hz,
                    setup,
                    ch: Some(ch),
                    state: LockState::PullIn,
                    state_since_s: 0.0,
                    good_since: None,
                    bad_since: None,
                    updates_since_check: 0,
                    attempts: 0,
                    lost_since: None,
                    next_attempt_s: 0.0,
                    reacq_interval_s: 0.0,
                    suspect: false,
                    check_unavailable: false,
                    next_epoch: 0,
                    last_t: 0.0,
                    loop_t: 0.0,
                    collect: None,
                    scratch: Vec::new(),
                })
            })
            .collect::<Result<Vec<_>, String>>()?;
        Ok(Self {
            spec,
            chans,
            consumed: 0,
            threads: 1,
        })
    }

    /// Run the channels of each chunk on up to `n` threads (`n` ≤ 1: one thread, the
    /// default; ignored on `wasm32`). A channel's correlation and state machine touch
    /// nothing but that channel, so they run in parallel; each channel's epochs and events
    /// are buffered and written to the sink on the calling thread in channel order, exactly
    /// the order of a serial run, so the output is bit-identical for any `n`.
    pub fn with_threads(mut self, n: usize) -> Self {
        self.threads = n.max(1);
        self
    }

    /// Feed the next `samples` of the stream to every channel, writing every loop update
    /// and event to `sink` as it happens.
    pub fn process(&mut self, samples: &[Cf64], sink: &mut dyn EpochSink) -> Result<(), IqError> {
        let chunk_start = self.consumed;
        let chunk_end = chunk_start + samples.len() as u64;
        let spec = self.spec;
        #[cfg(not(target_arch = "wasm32"))]
        if self.threads > 1 && self.chans.len() > 1 {
            self.process_parallel(samples, chunk_start, chunk_end, sink)?;
            self.consumed = chunk_end;
            return Ok(());
        }
        for (idx, m) in self.chans.iter_mut().enumerate() {
            m.advance(idx, samples, chunk_start, chunk_end, &spec, sink)?;
        }
        self.consumed = chunk_end;
        Ok(())
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn process_parallel(
        &mut self,
        samples: &[Cf64],
        chunk_start: u64,
        chunk_end: u64,
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        let spec = self.spec;
        let n = self.threads.min(self.chans.len());
        let mut groups: Vec<Vec<(usize, &mut Managed)>> = (0..n).map(|_| Vec::new()).collect();
        for (idx, m) in self.chans.iter_mut().enumerate() {
            groups[idx % n].push((idx, m));
        }
        let mut done: Vec<(usize, Buffered, Result<(), IqError>)> = std::thread::scope(|sc| {
            let handles: Vec<_> = groups
                .into_iter()
                .map(|g| {
                    sc.spawn(move || {
                        g.into_iter()
                            .map(|(idx, m)| {
                                let mut buf = Buffered::default();
                                let r = m.advance(
                                    idx,
                                    samples,
                                    chunk_start,
                                    chunk_end,
                                    &spec,
                                    &mut buf,
                                );
                                (idx, buf, r)
                            })
                            .collect::<Vec<_>>()
                    })
                })
                .collect();
            handles
                .into_iter()
                .flat_map(|h| h.join().expect("a tracking thread panicked"))
                .collect()
        });
        done.sort_by_key(|d| d.0);
        for (_, buf, r) in done {
            buf.replay(sink)?;
            r?;
        }
        Ok(())
    }

    /// Read `src` to its end (or to `max_samples`), writing to `sink`, then flush `sink`.
    pub fn run(
        &mut self,
        src: &mut dyn IqSource,
        max_samples: Option<u64>,
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        let mut buf = vec![Cf64::default(); CHUNK];
        let mut done = 0u64;
        loop {
            let want = match max_samples {
                Some(m) => (m.saturating_sub(done)).min(CHUNK as u64) as usize,
                None => CHUNK,
            };
            if want == 0 {
                break;
            }
            let n = src.read(&mut buf[..want])?;
            if n == 0 {
                break;
            }
            self.process(&buf[..n], sink)?;
            done += n as u64;
        }
        sink.finish()
    }
}

/// One channel's output of a chunk, held until it can be written in channel order.
#[derive(Default)]
struct Buffered(Vec<Item>);

enum Item {
    Epoch(usize, Box<EpochOutput>, LockState),
    Event(Box<LockEvent>),
}

impl Buffered {
    fn replay(self, sink: &mut dyn EpochSink) -> Result<(), IqError> {
        for it in self.0 {
            match it {
                Item::Epoch(ch, e, st) => sink.epoch(ch, &e, st)?,
                Item::Event(ev) => sink.event(&ev)?,
            }
        }
        Ok(())
    }
}

impl EpochSink for Buffered {
    fn epoch(&mut self, ch: usize, e: &EpochOutput, state: LockState) -> Result<(), IqError> {
        self.0.push(Item::Epoch(ch, Box::new(e.clone()), state));
        Ok(())
    }
    fn event(&mut self, ev: &LockEvent) -> Result<(), IqError> {
        self.0.push(Item::Event(Box::new(ev.clone())));
        Ok(())
    }
}

impl Managed {
    /// Run this channel over one chunk: correlate, step the state machine on every loop
    /// update, gather the samples a pending search needs and run it once they are in.
    fn advance(
        &mut self,
        idx: usize,
        samples: &[Cf64],
        chunk_start: u64,
        chunk_end: u64,
        spec: &SampleSpec,
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        let m = self;
        if let Some(ch) = m.ch.as_mut() {
            m.scratch.clear();
            ch.process(samples, &mut m.scratch);
            let epochs = std::mem::take(&mut m.scratch);
            for e in &epochs {
                m.on_epoch(idx, e, chunk_end, spec, sink)?;
                sink.epoch(idx, e, m.state)?;
            }
            m.scratch = epochs;
        }
        // Gather samples for a pending search; a search requested during this chunk starts
        // at the next one.
        if let Some(c) = m.collect.as_mut() {
            if c.start >= chunk_start && c.start < chunk_end {
                let from = (c.start - chunk_start) as usize;
                let take = (c.need - c.buf.len()).min(samples.len() - from);
                c.buf.extend_from_slice(&samples[from..from + take]);
            } else if c.start < chunk_start && c.buf.len() < c.need {
                let take = (c.need - c.buf.len()).min(samples.len());
                c.buf.extend_from_slice(&samples[..take]);
            }
        }
        if m.collect.as_ref().is_some_and(|c| c.buf.len() >= c.need) {
            let c = m.collect.take().expect("checked above");
            m.on_search(idx, c, chunk_end, spec, sink)?;
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn transition(
        &mut self,
        idx: usize,
        to: LockState,
        reason: &str,
        at_sample: u64,
        extra: (Option<f64>, Option<f64>, Option<f64>, Option<f64>),
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        let from = self.state;
        self.state = to;
        self.state_since_s = self.last_t;
        self.good_since = None;
        self.bad_since = None;
        if to == LockState::Locked {
            self.attempts = 0;
            self.lost_since = None;
        }
        if to == LockState::Lost && self.lost_since.is_none() {
            // A new loss: the re-acquisition window starts, and the first search with it.
            self.lost_since = Some(self.last_t);
            self.next_attempt_s = self.last_t;
            self.reacq_interval_s = self.setup.lock.reacq_interval_s;
        }
        sink.event(&LockEvent {
            channel: idx as u32,
            epoch: self.next_epoch,
            sample_index: at_sample,
            code_epoch_s: self.last_t,
            from,
            to,
            reason: reason.into(),
            doppler_hz: extra.0,
            code_phase_chips: extra.1,
            statistic: extra.2,
            threshold: extra.3,
        })
    }

    /// The state machine's step on one loop update.
    fn on_epoch(
        &mut self,
        idx: usize,
        e: &EpochOutput,
        chunk_end: u64,
        spec: &SampleSpec,
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        let lk = self.setup.lock.clone();
        let t = e.code_epoch_s;
        self.last_t = t;
        self.loop_t = e.t_coh_s;
        self.next_epoch = e.epoch + 1;
        let both = e.phase_lock && e.code_lock;
        let held = |since: &mut Option<f64>, cond: bool| -> bool {
            if cond {
                let s = *since.get_or_insert(t);
                t - s >= lk.loss_dwell_s
            } else {
                *since = None;
                false
            }
        };
        match self.state {
            LockState::PullIn => {
                if held(&mut self.good_since, both) {
                    self.transition(
                        idx,
                        LockState::Locked,
                        "locked",
                        e.sample_index,
                        (None, None, None, None),
                        sink,
                    )?;
                } else if t - self.state_since_s > lk.pull_in_max_s {
                    self.reacq_center = e.doppler_hz;
                    self.transition(
                        idx,
                        LockState::Lost,
                        "pull-in-timeout",
                        e.sample_index,
                        (None, None, None, None),
                        sink,
                    )?;
                }
            }
            LockState::Locked => {
                if held(&mut self.bad_since, !both) {
                    self.reacq_center = e.doppler_hz;
                    self.transition(
                        idx,
                        LockState::Lost,
                        "loss-of-lock",
                        e.sample_index,
                        (None, None, None, None),
                        sink,
                    )?;
                }
            }
            LockState::Lost => {
                if lk.reacquire {
                    if self.window_spent(t) {
                        self.ch = None;
                        return self.transition(
                            idx,
                            LockState::Retired,
                            "retired",
                            e.sample_index,
                            (None, None, None, None),
                            sink,
                        );
                    }
                    if self.collect.is_none() && t >= self.next_attempt_s {
                        let searchable = self.start(
                            Purpose::Reacq {
                                center: self.reacq_center,
                            },
                            chunk_end,
                            spec,
                        )?;
                        if !searchable {
                            // No search can run at this sample rate: stop the channel.
                            self.ch = None;
                            return self.transition(
                                idx,
                                LockState::Retired,
                                "retired",
                                e.sample_index,
                                (None, None, None, None),
                                sink,
                            );
                        }
                        self.transition(
                            idx,
                            LockState::Reacq,
                            "reacq-start",
                            e.sample_index,
                            (Some(self.reacq_center), None, None, None),
                            sink,
                        )?;
                    }
                } else if !self.suspect && held(&mut self.good_since, both) {
                    self.transition(
                        idx,
                        LockState::Locked,
                        "recovered",
                        e.sample_index,
                        (None, None, None, None),
                        sink,
                    )?;
                }
            }
            LockState::Reacq | LockState::Retired => {}
        }
        // The false-lock check, on every channel that is tracking. A false lock rarely
        // shows lock indicators, so it is looked for in pull-in and while lost too.
        let watching = matches!(
            self.state,
            LockState::PullIn | LockState::Locked | LockState::Lost
        );
        if lk.false_lock_check && watching && !self.check_unavailable {
            self.updates_since_check += 1;
            if self.updates_since_check >= self.setup.config.cn0_windows && self.collect.is_none() {
                self.updates_since_check = 0;
                let alias_hz = 1.0 / (2.0 * e.t_coh_s);
                let searchable = self.start(
                    Purpose::FalseLock {
                        center: e.doppler_hz,
                        alias_hz,
                    },
                    chunk_end,
                    spec,
                )?;
                if !searchable {
                    self.check_unavailable = true;
                }
            }
        }
        Ok(())
    }

    /// Whether this loss has used up its re-acquisition window at time `t` (s).
    fn window_spent(&self, t: f64) -> bool {
        self.lost_since
            .is_some_and(|s| t - s >= self.setup.lock.reacq_window_s)
    }

    /// A re-acquisition found nothing (or could not run): schedule the next search after
    /// the current interval (which then doubles, up to `reacq_max_interval_s`, when that
    /// is above `reacq_interval_s`), or retire
    /// the channel once the loss has outlasted `reacq_window_s` or used up the optional
    /// `max_reacq_attempts`.
    fn reacq_failed(
        &mut self,
        idx: usize,
        now: u64,
        stat: Option<(f64, f64)>,
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        self.attempts += 1;
        let extra = (None, None, stat.map(|s| s.0), stat.map(|s| s.1));
        let lk = &self.setup.lock;
        let capped = lk.max_reacq_attempts > 0 && self.attempts >= lk.max_reacq_attempts;
        self.next_attempt_s = self.last_t + self.reacq_interval_s;
        self.reacq_interval_s = (2.0 * self.reacq_interval_s).min(lk.reacq_max_interval_s);
        if capped || self.window_spent(self.last_t) {
            self.ch = None;
            self.transition(idx, LockState::Retired, "retired", now, extra, sink)
        } else {
            self.transition(idx, LockState::Lost, "reacq-failed", now, extra, sink)
        }
    }

    /// Begin gathering samples for a search starting at stream sample `start`.
    fn start(&mut self, purpose: Purpose, start: u64, spec: &SampleSpec) -> Result<bool, IqError> {
        let code = self.setup.init.code.as_ref();
        let period = code.period_s();
        let t_track_s = self.setup.config.coherent_periods as f64 * period;
        let base = self.setup.acquisition.acq_config(period, t_track_s);
        let cfg = match purpose {
            Purpose::Reacq { .. } => AcqConfig {
                doppler_max_hz: self.setup.lock.reacq_doppler_window_hz,
                ..base
            },
            Purpose::FalseLock { alias_hz, .. } => {
                // Resolve ±alias_hz: a coherent block of at least 2T, bins at 0, ±alias/2,
                // ±alias.
                let need_s = 2.0 / alias_hz;
                let n = ((need_s / period - 1e-9).ceil() as usize).max(base.coherent_periods);
                AcqConfig {
                    coherent_periods: n,
                    noncoherent: 1,
                    doppler_max_hz: alias_hz,
                    doppler_step_hz: alias_hz / 2.0,
                    pfa: base.pfa,
                }
            }
        };
        // A rate with no whole number of samples per code period cannot be searched; the
        // caller then goes on without the search.
        let Ok(need) = samples_needed(spec, code, &cfg) else {
            return Ok(false);
        };
        self.collect = Some(Collect {
            purpose,
            start,
            cfg,
            need,
            buf: Vec::with_capacity(need),
        });
        Ok(true)
    }

    /// Act on a completed search. `now` is the first stream sample not yet given to the
    /// channels: a re-acquired channel restarts there.
    fn on_search(
        &mut self,
        idx: usize,
        c: Collect,
        now: u64,
        spec: &SampleSpec,
        sink: &mut dyn EpochSink,
    ) -> Result<(), IqError> {
        let code = self.setup.init.code.clone();
        let center = match c.purpose {
            Purpose::FalseLock { center, .. } | Purpose::Reacq { center } => center,
        };
        // Centre the search on `center` by shifting the intermediate frequency.
        let shifted = SampleSpec {
            if_hz: spec.if_hz + center,
            ..*spec
        };
        // A search that cannot run (for example a sample rate with no whole number of
        // samples per code period) never stops tracking: the false-lock check is switched
        // off for the channel, and a re-acquisition counts as a failed attempt.
        let grid = match acquire(&c.buf, &shifted, code.as_ref(), &c.cfg) {
            Ok(g) => g,
            Err(_) => {
                return match c.purpose {
                    Purpose::FalseLock { .. } => {
                        self.check_unavailable = true;
                        Ok(())
                    }
                    Purpose::Reacq { .. } => self.reacq_failed(idx, now, None, sink),
                };
            }
        };
        match c.purpose {
            Purpose::FalseLock { alias_hz, .. } => {
                let row_max = |r: &Vec<f64>| r.iter().copied().fold(0.0_f64, f64::max);
                let mid = grid.grid.len() / 2;
                let tracked = row_max(&grid.grid[mid]);
                let (alias_idx, alias) = [0, grid.grid.len() - 1]
                    .into_iter()
                    .map(|i| (i, row_max(&grid.grid[i])))
                    .fold((0, 0.0), |a, b| if b.1 > a.1 { b } else { a });
                let ratio_db = 10.0 * (alias / tracked.max(f64::MIN_POSITIVE)).plog10();
                let margin = self.setup.lock.false_lock_margin_db;
                if ratio_db > margin {
                    let alias_doppler = center + if alias_idx == 0 { -alias_hz } else { alias_hz };
                    self.reacq_center = alias_doppler;
                    self.suspect = true;
                    let to = match self.state {
                        LockState::PullIn | LockState::Locked => LockState::Lost,
                        s => s,
                    };
                    self.transition(
                        idx,
                        to,
                        "false-lock",
                        now,
                        (Some(alias_doppler), None, Some(ratio_db), Some(margin)),
                        sink,
                    )?;
                } else {
                    self.suspect = false;
                }
            }
            Purpose::Reacq { .. } => {
                let mut r = grid.result.clone();
                if r.acquired {
                    r.doppler_hz += center;
                    let init = ChannelInit::from_acquisition(
                        code,
                        &r,
                        spec,
                        c.start,
                        self.setup.init.periods_per_bit,
                    );
                    let ch = Channel::new_at(spec, &init, &self.setup.config, now, self.next_epoch)
                        .map_err(IqError::Format)?;
                    self.ch = Some(ch);
                    self.suspect = false;
                    self.updates_since_check = 0;
                    self.transition(
                        idx,
                        LockState::PullIn,
                        "reacquired",
                        now,
                        (
                            Some(r.doppler_hz),
                            Some(r.code_phase_chips),
                            Some(r.statistic),
                            Some(r.threshold),
                        ),
                        sink,
                    )?;
                } else {
                    self.reacq_failed(idx, now, Some((r.statistic, r.threshold)), sink)?;
                }
            }
        }
        Ok(())
    }
}