flowscope 0.25.1

Passive flow & session tracking for packet capture (runtime-free, cross-platform)
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
//! Engine lifecycle guarantees (0.25): sweeps and `finish` never lose
//! released data (#180), the driver owns `Ended` and auto-sweeps
//! (#187), events keep their order and `finish` never stamps
//! `Timestamp::MAX` (#188), the memcap frees memory whatever the
//! reassembler does (#185), discarding costs nothing (#183).

#![cfg(all(
    feature = "extractors",
    feature = "reassembler",
    feature = "session",
    feature = "test-helpers"
))]

use std::sync::{Arc, Mutex};
use std::time::Duration;

use flowscope::driver::{Driver, Event};
use flowscope::extract::FiveTuple;
use flowscope::extract::parse::test_frames::ipv4_tcp;
use flowscope::session::{SessionDriver, SessionEvent};
use flowscope::{
    AnomalyKind, BufferedReassemblerFactory, EndReason, EventMask, FlowDriver, FlowEvent, FlowSide,
    FlowTrackerConfig, GapResponse, MemcapPolicy, PacketView, Reassembler, ReassemblerFactory,
    ReassemblyStop, SessionParser, Timestamp,
};

const SYN: u8 = 0x02;
const ACK: u8 = 0x10;
const PSH: u8 = 0x08;
const FIN: u8 = 0x01;
const M: [u8; 6] = [0; 6];
const C: [u8; 4] = [10, 0, 0, 1];
const S: [u8; 4] = [10, 0, 0, 2];
const CISN: u32 = 1000;
const SISN: u32 = 5000;

fn t(ms: u64) -> Timestamp {
    let d = Duration::from_millis(ms);
    Timestamp::new(d.as_secs() as u32, d.subsec_nanos())
}

fn handshake(cp: u16) -> Vec<Vec<u8>> {
    vec![
        ipv4_tcp(M, M, C, S, cp, 9000, CISN, 0, SYN, &[]),
        ipv4_tcp(M, M, S, C, 9000, cp, SISN, CISN + 1, SYN | ACK, &[]),
        ipv4_tcp(M, M, C, S, cp, 9000, CISN + 1, SISN + 1, ACK, &[]),
    ]
}

/// Client data at stream offset `off`.
fn data(cp: u16, off: u32, payload: &[u8]) -> Vec<u8> {
    ipv4_tcp(
        M,
        M,
        C,
        S,
        cp,
        9000,
        CISN + 1 + off,
        SISN + 1,
        PSH | ACK,
        payload,
    )
}

fn fin_exchange(cp: u16, end: u32) -> Vec<Vec<u8>> {
    vec![
        ipv4_tcp(
            M,
            M,
            C,
            S,
            cp,
            9000,
            CISN + 1 + end,
            SISN + 1,
            FIN | ACK,
            &[],
        ),
        ipv4_tcp(
            M,
            M,
            S,
            C,
            9000,
            cp,
            SISN + 1,
            CISN + 2 + end,
            FIN | ACK,
            &[],
        ),
        ipv4_tcp(M, M, C, S, cp, 9000, CISN + 2 + end, SISN + 2, ACK, &[]),
    ]
}

/// Frames 1 ms apart from t = 1 s.
fn timed(frames: Vec<Vec<u8>>) -> Vec<(Timestamp, Vec<u8>)> {
    frames
        .into_iter()
        .enumerate()
        .map(|(i, f)| (t(1_000 + i as u64), f))
        .collect()
}

#[derive(Debug, Clone, PartialEq)]
enum Piece {
    Data(Vec<u8>),
    Gap(u64),
    Tick(Timestamp),
}

/// Records bytes and gaps (continuing past gaps) and tick times.
#[derive(Clone, Default)]
struct Collect;

impl SessionParser for Collect {
    type Message = Piece;
    fn feed_initiator(&mut self, b: &[u8], _: Timestamp, out: &mut Vec<Piece>) {
        out.push(Piece::Data(b.to_vec()));
    }
    fn feed_responder(&mut self, b: &[u8], _: Timestamp, out: &mut Vec<Piece>) {
        out.push(Piece::Data(b.to_vec()));
    }
    fn on_gap(&mut self, _: FlowSide, n: u64, _: Timestamp, out: &mut Vec<Piece>) -> GapResponse {
        out.push(Piece::Gap(n));
        GapResponse::Continue
    }
    fn on_tick(&mut self, now: Timestamp, out: &mut Vec<Piece>) {
        out.push(Piece::Tick(now));
    }
}

fn pieces(events: &[SessionEvent<flowscope::extract::FiveTupleKey, Piece>]) -> Vec<Piece> {
    events
        .iter()
        .filter_map(|e| match e {
            SessionEvent::Application { message, .. } => match message {
                Piece::Tick(_) => None,
                m => Some(m.clone()),
            },
            _ => None,
        })
        .collect()
}

fn joined(p: &[Piece]) -> (Vec<u8>, u64) {
    let mut bytes = Vec::new();
    let mut gap = 0;
    for x in p {
        match x {
            Piece::Data(d) => bytes.extend_from_slice(d),
            Piece::Gap(n) => gap += n,
            Piece::Tick(_) => {}
        }
    }
    (bytes, gap)
}

// ── #180: sweeps / finish never drop released data ──────────────

/// A hole on a flow that then idles out: the data behind the hole
/// is delivered (after a gap) before the flow's end.
#[test]
fn sweep_delivers_released_tail_of_ending_flow() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"hello"));
    frames.push(data(40_000, 10, b"world"));
    let mut d = SessionDriver::new(FiveTuple::bidirectional(), Collect);
    let mut out = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut out);
    }
    // Idle timeout (300 s) and the hole deadline expire together.
    d.sweep_into(t(400_000), &mut out);
    assert!(matches!(
        out.last(),
        Some(SessionEvent::Closed {
            reason: EndReason::IdleTimeout,
            ..
        })
    ));
    assert_eq!(joined(&pieces(&out)), (b"helloworld".to_vec(), 5));
}

#[test]
fn finish_delivers_ooo_tail() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"hello"));
    frames.push(data(40_000, 10, b"world"));
    frames.push(data(40_000, 20, b"again"));
    let mut d = SessionDriver::new(FiveTuple::bidirectional(), Collect);
    let mut out = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut out);
    }
    d.finish_into(&mut out);
    assert_eq!(joined(&pieces(&out)), (b"helloworldagain".to_vec(), 10));
}

/// The first data segment of a flow arrives out of order; its hole
/// expires in a sweep. A port-selected parser still gets it.
#[test]
fn ports_selector_admits_flow_first_seen_in_sweep() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 5, b"late start"));
    let mut b = Driver::builder(FiveTuple::bidirectional());
    let mut slot = b.session_on_ports(Collect, [9000]);
    let mut d = b.build();
    let mut events = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut events);
    }
    // Lone out-of-order segment: skipped after four deadlines, long
    // before the idle timeout.
    d.sweep_into(t(10_000), &mut events);
    let mut msgs = Vec::new();
    slot.drain(&mut msgs);
    let got: Vec<_> = msgs
        .into_iter()
        .map(|m| m.message)
        .filter(|m| !matches!(m, Piece::Tick(_)))
        .collect();
    assert_eq!(
        got,
        vec![Piece::Gap(5), Piece::Data(b"late start".to_vec())]
    );
}

// ── #187: the driver owns Ended and the auto-sweep ──────────────

/// With `Ended` suppressed, per-flow state is still released, and a
/// new connection on the same 5-tuple starts fresh.
#[test]
fn masked_ended_frees_state_and_reuse_is_fresh() {
    let cfg = FlowTrackerConfig::default().with_event_filter(EventMask::ENDED);
    let mut b = Driver::builder(FiveTuple::bidirectional());
    b.config(cfg);
    let mut slot = b.session_broadcast(Collect);
    let mut d = b.build();
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"first"));
    frames.extend(fin_exchange(40_000, 5));
    let mut events = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut events);
    }
    assert!(!events.iter().any(|e| matches!(e, Event::Ended { .. })));
    assert_eq!(d.flow_driver().stream_count(), 0, "stream state released");
    assert_eq!(d.tracker().flow_count(), 0);

    // Same 5-tuple, new connection with a different ISN.
    let reuse = [
        ipv4_tcp(M, M, C, S, 40_000, 9000, 77_000, 0, SYN, &[]),
        ipv4_tcp(M, M, S, C, 9000, 40_000, 88_000, 77_001, SYN | ACK, &[]),
        ipv4_tcp(
            M,
            M,
            C,
            S,
            40_000,
            9000,
            77_001,
            88_001,
            PSH | ACK,
            b"second",
        ),
    ];
    for f in &reuse {
        d.track_into(PacketView::new(f, t(5_000)), &mut events);
    }
    let mut msgs = Vec::new();
    slot.drain(&mut msgs);
    let data: Vec<_> = msgs
        .into_iter()
        .filter_map(|m| match m.message {
            Piece::Data(d) => Some(d),
            _ => None,
        })
        .collect();
    assert_eq!(data, vec![b"first".to_vec(), b"second".to_vec()]);
}

/// `auto_sweep_interval` runs the whole sweep — reassembler
/// deadlines included — not just the tracker's.
#[test]
fn auto_sweep_runs_advance_time() {
    let mut cfg = FlowTrackerConfig::default();
    cfg.auto_sweep_interval = Some(Duration::from_secs(1));
    let mut b = Driver::builder(FiveTuple::bidirectional());
    b.config(cfg);
    let mut slot = b.session_on_ports(Collect, [9000]);
    let mut d = b.build();
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"a"));
    frames.push(data(40_000, 5, b"b")); // lone hole
    let mut events = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut events);
    }
    // Traffic on another flow moves packet time on by 10 s.
    let other = handshake(41_000);
    d.track_into(PacketView::new(&other[0], t(11_000)), &mut events);
    let mut msgs = Vec::new();
    slot.drain(&mut msgs);
    let got: Vec<_> = msgs
        .into_iter()
        .map(|m| m.message)
        .filter(|m| !matches!(m, Piece::Tick(_)))
        .collect();
    assert_eq!(
        got,
        vec![
            Piece::Data(b"a".to_vec()),
            Piece::Gap(4),
            Piece::Data(b"b".to_vec())
        ]
    );
}

#[test]
fn anomaly_mask_bits_honoured() {
    let run = |suppress: EventMask| {
        let cfg = FlowTrackerConfig::default().with_event_filter(suppress);
        let mut b = Driver::builder(FiveTuple::bidirectional());
        b.config(cfg);
        b.emit_anomalies(true);
        let _slot = b.session_broadcast(Collect);
        let mut d = b.build();
        let mut frames = handshake(40_000);
        frames.push(data(40_000, 0, b"a"));
        frames.push(data(40_000, 5, b"b"));
        let mut events = Vec::new();
        for (ts, f) in timed(frames) {
            d.track_into(PacketView::new(&f, ts), &mut events);
        }
        d.finish_into(&mut events);
        events
            .iter()
            .filter(|e| matches!(e, Event::FlowAnomaly { .. }))
            .count()
    };
    assert!(run(EventMask::empty()) > 0);
    assert_eq!(run(EventMask::FLOW_ANOMALY), 0);
}

// ── #188: ordering and end-of-input stamps ──────────────────────

/// The packet that ends a flow carries a retransmit: its anomaly
/// comes before the flow's `Ended`.
#[test]
fn per_packet_anomalies_precede_own_ended() {
    let mut d = FlowDriver::new(
        FiveTuple::bidirectional(),
        BufferedReassemblerFactory::default(),
    )
    .with_emit_anomalies(true);
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"abc"));
    frames.push(ipv4_tcp(
        M,
        M,
        C,
        S,
        40_000,
        9000,
        CISN + 4,
        SISN + 1,
        FIN | ACK,
        &[],
    ));
    frames.push(ipv4_tcp(
        M,
        M,
        S,
        C,
        9000,
        40_000,
        SISN + 1,
        CISN + 5,
        FIN | ACK,
        &[],
    ));
    // Final ACK, retransmitting "abc".
    frames.push(ipv4_tcp(
        M,
        M,
        C,
        S,
        40_000,
        9000,
        CISN + 1,
        SISN + 2,
        ACK,
        b"abc",
    ));
    let mut last = Vec::new();
    for (ts, f) in timed(frames) {
        last = d.track(PacketView::new(&f, ts)).into_vec();
    }
    let kinds: Vec<&str> = last
        .iter()
        .map(|e| match e {
            FlowEvent::FlowAnomaly { .. } => "anomaly",
            FlowEvent::Ended { .. } => "ended",
            _ => "other",
        })
        .filter(|k| *k != "other")
        .collect();
    assert_eq!(kinds, vec!["anomaly", "ended"]);
}

#[test]
fn flush_anomalies_precede_ended_and_finish_never_stamps_max() {
    let mut b = Driver::builder(FiveTuple::bidirectional());
    b.emit_anomalies(true);
    let _slot = b.session_broadcast(Collect);
    let mut d = b.build();
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"a"));
    frames.push(data(40_000, 5, b"b"));
    let frames = timed(frames);
    let last_ts = frames.last().unwrap().0;
    let mut events = Vec::new();
    for (ts, f) in &frames {
        d.track_into(PacketView::new(f, *ts), &mut events);
    }
    events.clear();
    d.finish_into(&mut events);
    let gap_at = events
        .iter()
        .position(|e| {
            matches!(
                e,
                Event::FlowAnomaly {
                    kind: AnomalyKind::StreamGap { .. },
                    ..
                }
            )
        })
        .expect("gap reported");
    let end_at = events
        .iter()
        .position(|e| matches!(e, Event::Ended { .. }))
        .expect("ended");
    assert!(gap_at < end_at);
    for e in &events {
        assert_ne!(e.timestamp(), Timestamp::MAX, "{e:?}");
    }
    assert_eq!(events[gap_at].timestamp(), last_ts);
}

#[test]
fn finish_keeps_monotonic_clock_and_stamps_ticks() {
    let mut d =
        SessionDriver::new(FiveTuple::bidirectional(), Collect).with_monotonic_timestamps(true);
    let mut out = Vec::new();
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"x"));
    let frames = timed(frames);
    let last_ts = frames.last().unwrap().0;
    for (ts, f) in &frames {
        d.track_into(PacketView::new(f, *ts), &mut out);
    }
    out.clear();
    d.finish_into(&mut out);
    // The parser saw "end of input"...
    let ticks: Vec<_> = out
        .iter()
        .filter_map(|e| match e {
            SessionEvent::Application {
                message: Piece::Tick(now),
                ts,
                ..
            } => Some((*now, *ts)),
            _ => None,
        })
        .collect();
    assert_eq!(
        ticks,
        vec![(Timestamp::MAX, last_ts)],
        "stamped with packet time"
    );
    // ... and the clock was not pinned at MAX.
    out.clear();
    let later = handshake(41_000);
    d.track_into(PacketView::new(&later[0], t(20_000)), &mut out);
    let started = out
        .iter()
        .find_map(|e| match e {
            SessionEvent::Started { ts, .. } => Some(*ts),
            _ => None,
        })
        .unwrap();
    assert_eq!(started, t(20_000));
}

#[test]
fn on_tick_gets_clamped_now() {
    let mut d =
        SessionDriver::new(FiveTuple::bidirectional(), Collect).with_monotonic_timestamps(true);
    let mut out = Vec::new();
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"x"));
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut out);
    }
    out.clear();
    d.sweep_into(t(10), &mut out); // earlier than the last packet
    let ticks: Vec<_> = out
        .iter()
        .filter_map(|e| match e {
            SessionEvent::Application {
                message: Piece::Tick(now),
                ..
            } => Some(*now),
            _ => None,
        })
        .collect();
    assert_eq!(ticks, vec![t(1_003)]);
}

// ── #185: memcap ────────────────────────────────────────────────

/// Buffers everything; `release` does nothing (the trait default).
#[derive(Default)]
struct Hoarder {
    buf: Vec<u8>,
}

impl Reassembler for Hoarder {
    fn segment(&mut self, _: u32, payload: &[u8], _: Timestamp) {
        self.buf.extend_from_slice(payload);
    }
    fn current_bytes(&self) -> u64 {
        self.buf.len() as u64
    }
}

#[derive(Default)]
struct HoarderFactory;

impl<K> ReassemblerFactory<K> for HoarderFactory {
    type Reassembler = Hoarder;
    fn new_reassembler(&mut self, _: &K, _: FlowSide) -> Hoarder {
        Hoarder::default()
    }
}

#[test]
fn memcap_frees_custom_noop_release_reassembler_and_tombstones_empty_peer() {
    let mut cfg = FlowTrackerConfig::default();
    cfg.reassembly_memcap = Some(100);
    cfg.reassembly_memcap_policy = MemcapPolicy::DropFlow;
    let mut d = FlowDriver::with_config(FiveTuple::bidirectional(), HoarderFactory, cfg);
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, &[b'x'; 200]));
    // The responder only speaks after the trip.
    frames.push(ipv4_tcp(
        M,
        M,
        S,
        C,
        9000,
        40_000,
        SISN + 1,
        CISN + 201,
        PSH | ACK,
        b"late",
    ));
    let frames = timed(frames);
    let mut key = None;
    for (ts, f) in &frames[..4] {
        let _ = d.track(PacketView::new(f, *ts));
        key = d.last_packet().map(|p| p.key);
    }
    let key = key.unwrap();
    assert_eq!(d.reassembly_memcap_bytes(), 0, "memory freed");
    assert!(d.reassembler(&key, FlowSide::Initiator).is_none());
    let (ts, f) = &frames[4];
    let _ = d.track(PacketView::new(f, *ts));
    assert!(
        d.reassembler(&key, FlowSide::Responder).is_none(),
        "DropFlow released the peer too, although it had no reassembler yet"
    );
    let ended = d.finish();
    let stats = ended
        .iter()
        .find_map(|e| match e {
            FlowEvent::Ended { stats, .. } => Some(stats.clone()),
            _ => None,
        })
        .unwrap();
    assert_eq!(
        stats.reassembly_stop_initiator,
        Some(ReassemblyStop::Memcap)
    );
    assert_eq!(
        stats.reassembly_stop_responder,
        Some(ReassemblyStop::Memcap)
    );
}

// ── #183: discarding costs nothing ──────────────────────────────

#[test]
fn discard_stream_allocates_no_reassembler() {
    let mut d = FlowDriver::new(
        FiveTuple::bidirectional(),
        BufferedReassemblerFactory::default(),
    );
    let frames = timed(handshake(40_000));
    for (ts, f) in &frames {
        let _ = d.track(PacketView::new(f, *ts));
    }
    let key = d.last_packet().unwrap().key;
    d.discard_stream(&key);
    let f = data(40_000, 0, b"ignored");
    let _ = d.track(PacketView::new(&f, t(2_000)));
    assert!(d.reassembler(&key, FlowSide::Initiator).is_none());
    assert!(d.reassembler(&key, FlowSide::Responder).is_none());
    assert_eq!(d.reassembly_memcap_bytes(), 0);
}

/// The parser-visible order around a released tail: data, then the
/// parser close, then the end.
#[test]
fn released_tail_precedes_parser_close_and_end() {
    let seen = Arc::new(Mutex::new(Vec::<&'static str>::new()));
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"a"));
    frames.push(data(40_000, 5, b"b"));
    let mut d = SessionDriver::new(FiveTuple::bidirectional(), Collect);
    let mut out = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut out);
    }
    out.clear();
    d.finish_into(&mut out);
    for e in &out {
        seen.lock().unwrap().push(match e {
            SessionEvent::Application { .. } => "message",
            SessionEvent::ParserClosed { .. } => "parser_closed",
            SessionEvent::Closed { .. } => "closed",
            _ => "other",
        });
    }
    let seen = seen.lock().unwrap();
    let last_message = seen.iter().rposition(|k| *k == "message").unwrap();
    let closed = seen.iter().position(|k| *k == "closed").unwrap();
    assert!(last_message < closed);
    assert_eq!(seen.last(), Some(&"closed"));
}

// ── #189: probing ───────────────────────────────────────────────

fn sig_get(b: &[u8]) -> flowscope::detect::signatures::SignatureMatch {
    use flowscope::detect::signatures::SignatureMatch as M;
    if b.len() < 4 {
        if b"GET ".starts_with(b) {
            M::NeedMoreData
        } else {
            M::NoMatch
        }
    } else if b.starts_with(b"GET ") {
        M::Match
    } else {
        M::NoMatch
    }
}

fn heuristic_messages(frames: Vec<Vec<u8>>, budget: u8, finish: bool) -> Vec<Piece> {
    let mut b = Driver::builder(FiveTuple::bidirectional());
    let mut slot = b.session_heuristic_with_budget(Collect, sig_get, budget);
    let mut d = b.build();
    let mut events = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut events);
    }
    if finish {
        d.finish_into(&mut events);
    }
    let mut msgs = Vec::new();
    slot.drain(&mut msgs);
    msgs.into_iter()
        .map(|m| m.message)
        .filter(|m| !matches!(m, Piece::Tick(_)))
        .collect()
}

/// "GE" + gap + "T /": the signature must not see a spliced "GET /".
#[test]
fn probe_prefix_sealed_at_gap() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"GE"));
    frames.push(data(40_000, 10, b"T / HTTP/1.1\r\n"));
    // Two more segments so the hole is corroborated and skipped.
    frames.push(data(40_000, 30, b"x"));
    let mut cfg_frames = frames;
    cfg_frames.push(data(40_000, 40, b"y"));
    let got = heuristic_messages(cfg_frames, 8, true);
    assert!(got.is_empty(), "never pinned: {got:?}");
}

/// A flow still probing when it ends is probed on its final bytes —
/// and bytes after a leading gap are not the start of the stream, so
/// they never satisfy a signature.
#[test]
fn signature_never_matches_bytes_after_a_leading_gap() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 3, b"GET / HTTP/1.1\r\n")); // hole 0..3
    let got = heuristic_messages(frames, 4, true);
    assert!(got.is_empty(), "{got:?}");
}

/// Probing continues into the final bytes: "GE" then (after the
/// probe budget would have allowed more) the flow ends; the parser
/// never pins on a partial prefix.
#[test]
fn undecided_probe_at_flow_end_is_dropped_quietly() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 0, b"GE"));
    frames.extend(fin_exchange(40_000, 2));
    let mut b = Driver::builder(FiveTuple::bidirectional());
    let _slot = b.session_heuristic(Collect, sig_get);
    let mut d = b.build();
    let mut events = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut events);
    }
    assert!(
        !events
            .iter()
            .any(|e| matches!(e, Event::ParserClosed { .. })),
        "no parser was ever created"
    );
}

/// The server talks first and a lot; the client's "GET " comes after
/// the replay cap. The parser pins, starts with the server's first
/// chunk, then a gap for what was not kept, then everything else.
#[test]
fn replay_overflow_continues_with_leading_gap() {
    let mut frames = handshake(40_000);
    let chunk = vec![b's'; 16 * 1024];
    let mut soff = 0u32;
    for _ in 0..6 {
        frames.push(ipv4_tcp(
            M,
            M,
            S,
            C,
            9000,
            40_000,
            SISN + 1 + soff,
            CISN + 1,
            PSH | ACK,
            &chunk,
        ));
        soff += chunk.len() as u32;
    }
    frames.push(data(40_000, 0, b"GET / HTTP/1.1\r\n"));
    let got = heuristic_messages(frames, 16, false);
    let (bytes, gap) = joined(&got);
    assert!(gap > 0, "the parser is told it starts mid-stream");
    assert_eq!(bytes.len() as u64 + gap, 6 * 16 * 1024 + 16);
    assert!(got.contains(&Piece::Data(b"GET / HTTP/1.1\r\n".to_vec())));
}

/// A port-selected parser picks up a flow whose only data is in the
/// end-of-flow flush.
#[test]
fn first_data_only_in_finals_is_parsed() {
    let mut frames = handshake(40_000);
    frames.push(data(40_000, 3, b"late"));
    let mut b = Driver::builder(FiveTuple::bidirectional());
    let mut slot = b.session_on_ports(Collect, [9000]);
    let mut d = b.build();
    let mut events = Vec::new();
    for (ts, f) in timed(frames) {
        d.track_into(PacketView::new(&f, ts), &mut events);
    }
    d.finish_into(&mut events);
    let mut msgs = Vec::new();
    slot.drain(&mut msgs);
    let got: Vec<_> = msgs
        .into_iter()
        .map(|m| m.message)
        .filter(|m| !matches!(m, Piece::Tick(_)))
        .collect();
    assert_eq!(got, vec![Piece::Gap(3), Piece::Data(b"late".to_vec())]);
}