subc-daemon 0.56.10

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
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
use super::*;
use crate::operator_apps::{dev_builds, TestOperatorAppPolicy};
use crate::peer_identity_lane::{CheckPoint, PeerIdentityLane};
use crate::router::test_log::{captured_logs, log_capture};
use std::future::{poll_fn, Future};
use std::pin::{pin, Pin};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Condvar;
use std::task::Poll;
use std::time::{Duration, Instant};
use subc_os::local_peer::{
    check_dev_app_bundle,
    fixture::{SignedAppFixture, SignedPeerFixture},
};
use tokio::sync::Semaphore;

const CONNECTION: ConnectionId = ConnectionId::new(73);
const IDENTIFIER: &str = "io.cortexkit.fixture.route-stamp";

struct Fixture {
    handler: ControlHandler,
    lane: Arc<PeerIdentityLane>,
    checks: Arc<AtomicUsize>,
    caps: CapabilityDeclarations,
    _socket: std::os::unix::net::UnixStream,
    _process: SignedPeerFixture,
    _root: cortexkit_test_support::ScratchDir,
}

impl Fixture {
    fn new() -> Self {
        Self::with_check_probe(false, |_| {})
    }

    fn with_check_probe(dev: bool, probe: impl Fn(CheckPoint) + Send + Sync + 'static) -> Self {
        let root = cortexkit_test_support::ScratchDir::new("route-stamp-lane");
        let identifier = if dev {
            dev_builds::IDENTIFIER
        } else {
            IDENTIFIER
        };
        let bundle =
            SignedAppFixture::new(&root.join("app"), identifier, Some("1.2.10"), true, None);
        let mut process = bundle.launch();
        let (socket, peer) = process.connect();
        let checks = Arc::new(AtomicUsize::new(0));
        let lane = Arc::new(
            PeerIdentityLane::start()
                .with_probe({
                    let checks = checks.clone();
                    move || {
                        checks.fetch_add(1, Ordering::Relaxed);
                    }
                })
                .with_check_probe(probe),
        );
        let mut handler = ControlHandler::default();
        handler.operator_app_policy = TestOperatorAppPolicy {
            macos_enabled: true,
            windows_enabled: false,
            linux_enabled: false,
            app: "test-app",
            requirement: "identifier \"io.cortexkit.fixture.route-stamp\"",
            floor: semver::Version::new(1, 2, 10),
            windows_publisher: None,
            windows_path: None,
            linux_path: None,
            windows_breakaway: true,
            linux_force_direct: false,
        }
        .into();
        if dev {
            let code = check_dev_app_bundle(bundle.bundle(), identifier).unwrap();
            let store = dev_builds::TrustedBuilds::memory_for_tests();
            store
                .add(subc_control::TrustedAppBuild::new(
                    identifier.into(),
                    dev_builds::format_hash(code.cdhash),
                    "1.2.10".into(),
                    code.build_time,
                    0,
                ))
                .unwrap();
            handler.operator_app_policy.trusted_builds = Arc::new(store);
        }
        handler.operator_app_policy.test_lane = Some(lane.clone());
        handler.record_captured_peer(CONNECTION, peer);
        let caps =
            serde_json::from_value(serde_json::json!({"provides": [OPERATOR_APP_CAPABILITY]}))
                .unwrap();
        Self {
            handler,
            lane,
            checks,
            caps,
            _socket: socket,
            _process: process,
            _root: root,
        }
    }

    async fn bind(&self) -> Option<OperatorAppStamp> {
        self.candidate()
            .await
            .and_then(RouteOperatorApp::into_current_stamp)
    }

    async fn candidate(&self) -> Option<RouteOperatorApp> {
        self.handler
            .route_operator_app(CONNECTION, Some(&self.caps), "restarted-module", "test")
            .await
    }

    async fn describe(&self) -> subc_control::ConnectionDescribeReply {
        let (tx, _rx) = tokio::sync::mpsc::channel(1);
        let ctx = RouteCtx {
            connection_id: CONNECTION,
            egress: crate::router::FrameSink::new(tx),
        };
        let request = Frame::build(
            FrameType::Request,
            control_flags(),
            0,
            0,
            1,
            serde_json::to_vec(&subc_control::ConnectionDescribeRequest::new()).unwrap(),
        )
        .unwrap();
        let reply = self
            .handler
            .handle_connection_describe(&ctx, request)
            .await
            .unwrap();
        serde_json::from_slice(&reply[0].body).unwrap()
    }
}

struct Hold {
    entered: Semaphore,
    released: Mutex<bool>,
    wake: Condvar,
}

struct Occupancy(Arc<Hold>);

type Filler<'a> = Pin<Box<dyn Future<Output = Option<()>> + 'a>>;

impl Occupancy {
    fn new() -> Self {
        Self(Arc::new(Hold {
            entered: Semaphore::new(0),
            released: Mutex::new(false),
            wake: Condvar::new(),
        }))
    }

    fn check_probe(&self, point: CheckPoint) -> impl Fn(CheckPoint) + Send + Sync + 'static {
        let hold = self.0.clone();
        move |reached| {
            if reached == point {
                hold.block();
            }
        }
    }

    async fn fill<'a>(&self, lane: &'a PeerIdentityLane, count: usize) -> Vec<Filler<'a>> {
        let mut jobs = Vec::new();
        let deadline = Instant::now() + Duration::from_secs(5);
        for _ in 0..count {
            let hold = self.0.clone();
            let mut job: Filler<'_> = Box::pin(lane.run_until(deadline, move || hold.block()));
            assert!(poll_once(job.as_mut()).await.is_pending());
            jobs.push(job);
        }
        jobs
    }

    async fn workers_entered(&self) {
        self.entered(2).await;
    }

    async fn entered(&self, n: u32) {
        tokio::time::timeout(Duration::from_secs(5), self.0.entered.acquire_many(n))
            .await
            .expect("worker reached the hold")
            .unwrap()
            .forget();
    }

    fn release(&self) {
        *self.0.released.lock().unwrap() = true;
        self.0.wake.notify_all();
    }
}

impl Hold {
    fn block(&self) {
        let released = self.released.lock().unwrap();
        self.entered.add_permits(1);
        drop(
            self.wake
                .wait_while(released, |released| !*released)
                .unwrap(),
        );
    }
}

impl Drop for Occupancy {
    fn drop(&mut self) {
        self.release();
    }
}

async fn poll_once<F: Future + ?Sized>(mut future: Pin<&mut F>) -> Poll<F::Output> {
    poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx))).await
}

#[tokio::test]
async fn first_bind_stamps_after_the_describe_budget_elapses() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionStarted));
    let mut bind = pin!(fixture.bind());
    assert!(poll_once(bind.as_mut()).await.is_pending());
    hold.entered(1).await;

    let described = tokio::time::timeout(Duration::from_secs(1), fixture.describe())
        .await
        .expect("describe must not wait for the full bind budget");
    assert!(described.operator_app.is_none());
    hold.release();

    assert!(bind.await.is_some(), "bind should outwait describe");
    assert_eq!(fixture.checks.load(Ordering::Relaxed), 1);
}

#[tokio::test]
async fn describe_times_out_but_joining_bind_gets_its_recognition() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionStarted));
    let mut describe = pin!(fixture.describe());
    assert!(poll_once(describe.as_mut()).await.is_pending());
    hold.entered(1).await;
    let mut bind = pin!(fixture.bind());
    assert!(poll_once(bind.as_mut()).await.is_pending());

    let described = tokio::time::timeout(Duration::from_secs(1), describe)
        .await
        .expect("joining bind must not prolong describe's wait");
    assert!(described.operator_app.is_none());
    hold.release();

    assert!(
        bind.await.is_some(),
        "bind should extend the in-flight check"
    );
    assert_eq!(fixture.checks.load(Ordering::Relaxed), 1);
}

#[tokio::test]
async fn expired_describe_cannot_fall_back_to_the_late_cached_stamp() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionStarted));
    let mut delayed = pin!(fixture.describe());
    assert!(poll_once(delayed.as_mut()).await.is_pending());
    hold.entered(1).await;
    let mut bind = pin!(fixture.bind());
    assert!(poll_once(bind.as_mut()).await.is_pending());

    // Let another describe exhaust the same budget before polling the earlier
    // describe again, as if its task was not scheduled until the bind finished.
    assert!(fixture.describe().await.operator_app.is_none());
    hold.release();
    assert!(bind.await.is_some());
    assert!(delayed.await.operator_app.is_none());
    assert_eq!(fixture.checks.load(Ordering::Relaxed), 1);
}

#[tokio::test]
async fn revocation_fences_slow_recognition_before_it_publishes() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(true, hold.check_probe(CheckPoint::RecognitionReturned));
    let store = &fixture.handler.operator_app_policy.trusted_builds;
    let hash = store.list().unwrap().remove(0).cdhash;
    let mut bind = pin!(fixture.bind());
    assert!(poll_once(bind.as_mut()).await.is_pending());
    hold.entered(1).await;
    assert!(fixture.describe().await.operator_app.is_none());

    assert!(store.remove(&hash).unwrap());
    hold.release();

    assert!(
        bind.await.is_none(),
        "revoked evidence must not stamp the bind"
    );
    assert!(!fixture
        .handler
        .operator_apps
        .lock()
        .unwrap()
        .contains_key(&CONNECTION));
    assert_eq!(fixture.checks.load(Ordering::Relaxed), 1);
}

#[tokio::test]
async fn completed_recognition_of_an_untrusted_peer_does_not_warn() {
    let fixture = Fixture::with_check_probe(true, |_| {});
    let store = &fixture.handler.operator_app_policy.trusted_builds;
    let hash = store.list().unwrap().remove(0).cdhash;
    assert!(store.remove(&hash).unwrap());
    let (output, _logs) = log_capture(tracing::Level::WARN);

    assert!(fixture.bind().await.is_none());
    assert_eq!(fixture.checks.load(Ordering::Relaxed), 1);
    assert!(!captured_logs(&output).contains("unstamped_binds"));
}

#[tokio::test]
async fn concurrent_reopened_binds_share_only_the_in_flight_check() {
    let fixture = Fixture::new();
    let original = fixture.bind().await.expect("recognize stamped peer");
    let occupied = Occupancy::new();
    let _workers = occupied.fill(&fixture.lane, 2).await;
    occupied.workers_entered().await;
    let before = fixture.checks.load(Ordering::Relaxed);
    let mut pending = Vec::new();
    for _ in 0..6 {
        let mut bind = Box::pin(fixture.bind());
        assert!(
            poll_once(bind.as_mut()).await.is_pending(),
            "a reopened bind was refused while the workers were busy"
        );
        pending.push(bind);
    }
    occupied.release();
    for bind in pending {
        assert!(original.same_generation(&bind.await.expect("reopened route is stamped")));
    }
    assert_eq!(fixture.checks.load(Ordering::Relaxed), before + 1);
    assert!(original.same_generation(&fixture.bind().await.unwrap()));
    assert_eq!(
        fixture.checks.load(Ordering::Relaxed),
        before + 2,
        "a later bind must revalidate again"
    );
}

#[tokio::test]
async fn reopened_bind_waits_for_a_full_identity_queue() {
    bind_waits_for_full_queue(true).await;
}

#[tokio::test]
async fn first_bind_waits_for_a_full_identity_queue() {
    bind_waits_for_full_queue(false).await;
}

async fn bind_waits_for_full_queue(recognize_first: bool) {
    let fixture = Fixture::new();
    if recognize_first {
        fixture.bind().await.expect("recognize stamped peer");
    }
    let occupied = Occupancy::new();
    let _workers = occupied.fill(&fixture.lane, 2).await;
    occupied.workers_entered().await;
    let _queued = occupied.fill(&fixture.lane, 2).await;
    let mut bind = pin!(fixture.bind());
    tokio::select! {
        () = fixture.lane.waiting_for_capacity.notified() => {},
        _ = &mut bind => panic!("bind did not wait for lane capacity"),
    }
    occupied.release();
    assert!(bind.await.is_some(), "bind stamps after a queue slot opens");
}

#[tokio::test]
async fn first_bind_retries_refused_immediate_recognition() {
    let fixture = Fixture::new();
    let occupied = Occupancy::new();
    let _workers = occupied.fill(&fixture.lane, 2).await;
    occupied.workers_entered().await;
    let _queued = occupied.fill(&fixture.lane, 2).await;

    let mut describe = pin!(fixture.handler.recognize_operator_peer(
        CONNECTION,
        Admission::Immediate,
        Instant::now() + EVIDENCE_BUDGET
    ));
    assert!(poll_once(describe.as_mut()).await.is_pending());
    let original_deadline = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION]
        .recognized
        .lock()
        .unwrap()
        .as_ref()
        .unwrap()
        .deadline
        .current();
    let before_bind = Instant::now();
    let mut bind = pin!(fixture.bind());
    assert!(poll_once(bind.as_mut()).await.is_pending());
    let after_bind = Instant::now();
    let described = describe.await;
    assert!(described.fresh.is_none());
    assert!(poll_once(bind.as_mut()).await.is_pending());
    let capture = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION].clone();
    {
        let recognition = capture.recognized.lock().unwrap();
        let retry = recognition.as_ref().unwrap();
        let retry_deadline = retry.deadline.current();
        assert!(
            retry_deadline > original_deadline
                && (before_bind + BIND_EVIDENCE_BUDGET..=after_bind + BIND_EVIDENCE_BUDGET)
                    .contains(&retry_deadline),
            "retry is bounded by the bind's original deadline, not describe's deadline"
        );
        assert!(matches!(
            *retry.verdict.borrow(),
            RecognitionVerdict::Pending
        ));
    }
    occupied.release();
    assert!(bind.await.is_some());
}

#[tokio::test]
async fn reopened_binds_fail_closed_and_warn_once_when_admission_expires() {
    let fixture = Fixture::new();
    fixture.bind().await.expect("recognize stamped peer");
    let occupied = Occupancy::new();
    let _workers = occupied.fill(&fixture.lane, 2).await;
    occupied.workers_entered().await;
    let _queued = occupied.fill(&fixture.lane, 2).await;
    let before = fixture.checks.load(Ordering::Relaxed);
    let (output, _logs) = log_capture(tracing::Level::WARN);

    let (first, second) = tokio::join!(fixture.bind(), fixture.bind());
    assert!(first.is_none() && second.is_none());
    assert_eq!(
        fixture.checks.load(Ordering::Relaxed),
        before,
        "native work did not run"
    );
    let logs = captured_logs(&output);
    let mut warnings = logs
        .lines()
        .filter(|line| line.contains("operator app stamp could not be revalidated"));
    let warning = warnings.next().expect("timed-out stamp check warns");
    assert!(warning.contains("connection_id=73"), "{warning}");
    assert!(
        warning.contains("module_id=\"restarted-module\""),
        "{warning}"
    );
    assert!(warning.contains("reason=\"deadline\""), "{warning}");
    assert!(warning.contains("unstamped_binds=1"), "{warning}");
    assert!(
        warnings.next().is_none(),
        "concurrent binds should not repeat the warning: {logs}"
    );
}

#[tokio::test]
async fn revocation_fences_a_bind_joining_an_already_checked_flight() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(true, hold.check_probe(CheckPoint::RevalidationChecked));
    let original = fixture.bind().await.expect("approved dev build is stamped");
    let hash = original
        .dev_hash()
        .expect("fixture stamped through dev trust");
    let mut first = Box::pin(fixture.bind());
    assert!(poll_once(first.as_mut()).await.is_pending());
    hold.entered(1).await;

    // Store removal precedes eviction of stamps and closing their connections.
    assert!(fixture
        .handler
        .operator_app_policy
        .trusted_builds
        .remove(&hash)
        .unwrap());
    let mut joining = Box::pin(fixture.bind());
    let joined = poll_once(joining.as_mut()).await;
    hold.release();
    let stamp = match joined {
        Poll::Ready(stamp) => stamp,
        Poll::Pending => joining.await,
    };
    assert!(
        stamp.is_none(),
        "a bind joining after revocation reused the old trust check"
    );
    assert!(
        first.await.is_none(),
        "revocation also invalidates the first bind"
    );
}

#[tokio::test]
async fn revocation_after_verification_fences_the_stamp_at_attachment() {
    let fixture = Fixture::with_check_probe(true, |_| {});
    let candidate = fixture
        .candidate()
        .await
        .expect("approved dev build is verified");
    let hash = candidate
        .stamp
        .dev_hash()
        .expect("fixture stamped through dev trust");
    assert!(fixture
        .handler
        .operator_app_policy
        .trusted_builds
        .remove(&hash)
        .unwrap());
    assert!(candidate.into_current_stamp().is_none());
}

#[tokio::test]
async fn first_recognition_cannot_resubmit_while_its_native_check_hangs() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionStarted));
    let mut first = Box::pin(fixture.bind());
    assert!(poll_once(first.as_mut()).await.is_pending());
    hold.entered(1).await;
    let (output, _logs) = log_capture(tracing::Level::WARN);
    assert!(first.await.is_none());
    assert!(fixture.bind().await.is_none());
    assert!(fixture.bind().await.is_none());
    assert_eq!(
        fixture.checks.load(Ordering::Relaxed),
        1,
        "a hung recognition resubmitted native work"
    );
    let logs = captured_logs(&output);
    assert_eq!(logs.matches("reason=\"deadline\"").count(), 1, "{logs}");
    assert!(!logs.contains("reason=\"check_running\""), "{logs}");
    assert!(
        logs.contains("connection_id=73") && logs.contains("restarted-module"),
        "{logs}"
    );
    assert_eq!(
        fixture.lane.run(|| 42).await,
        Some(42),
        "the other worker remains available"
    );
    hold.release();
}

#[tokio::test]
async fn a_bind_joining_after_native_recognition_returned_revalidates() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionReturned));
    let mut first = Box::pin(fixture.bind());
    assert!(poll_once(first.as_mut()).await.is_pending());
    hold.entered(1).await;
    let mut later = Box::pin(fixture.bind());
    assert!(poll_once(later.as_mut()).await.is_pending());
    hold.release();

    let original = first.await.expect("recognition stamps the original bind");
    assert!(original.same_generation(&later.await.expect("later bind revalidated")));
    assert_eq!(
        fixture.checks.load(Ordering::Relaxed),
        2,
        "late bind reused evidence from a check that finished before it arrived"
    );
}

#[tokio::test]
async fn cancelling_the_bind_that_started_a_flight_does_not_cancel_the_check() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RevalidationStarted));
    fixture.bind().await.expect("recognize stamped peer");
    let mut first = Box::pin(fixture.bind());
    assert!(poll_once(first.as_mut()).await.is_pending());
    hold.entered(1).await;
    drop(first);
    let mut follower = Box::pin(fixture.bind());
    assert!(poll_once(follower.as_mut()).await.is_pending());
    hold.release();
    assert!(follower.await.is_some());
    assert_eq!(
        fixture.checks.load(Ordering::Relaxed),
        2,
        "recognition plus one flight"
    );
}

#[tokio::test]
async fn reopened_bind_warns_when_its_previous_native_check_is_still_running() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RevalidationStarted));
    fixture.bind().await.expect("recognize stamped peer");
    let mut first = Box::pin(fixture.bind());
    assert!(poll_once(first.as_mut()).await.is_pending());
    hold.entered(1).await;
    let (output, _logs) = log_capture(tracing::Level::WARN);
    assert!(first.await.is_none());
    assert!(fixture.bind().await.is_none());
    assert!(fixture.bind().await.is_none());
    let logs = captured_logs(&output);
    assert_eq!(logs.matches("reason=\"deadline\"").count(), 1, "{logs}");
    assert!(!logs.contains("reason=\"check_running\""), "{logs}");

    // Move the previous warning back to the edge of the quiet period without
    // waiting out a minute or letting the held native worker finish.
    let capture = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION].clone();
    capture.route_fallbacks.lock().unwrap().last_warning =
        Some(Instant::now() - Duration::from_secs(60));
    assert!(fixture.bind().await.is_none());
    assert_eq!(fixture.checks.load(Ordering::Relaxed), 2);
    let logs = captured_logs(&output);
    assert_eq!(
        logs.matches("reason=\"check_running\"").count(),
        1,
        "{logs}"
    );
    assert!(
        logs.lines()
            .any(|line| line.contains("reason=\"check_running\"")
                && line.contains("unstamped_binds=3")),
        "{logs}"
    );
    assert!(
        logs.contains("connection_id=73") && logs.contains("restarted-module"),
        "{logs}"
    );
}

fn set_recognition(
    fixture: &Fixture,
    deadline: Instant,
    initial: RecognitionVerdict,
    progress: Arc<RecognitionProgress>,
) -> watch::Sender<RecognitionVerdict> {
    let (publish, verdict) = watch::channel(initial);
    let capture = fixture.handler.captured_peers.lock().unwrap()[&CONNECTION].clone();
    *capture.recognized.lock().unwrap() = Some(Recognition {
        deadline: CheckDeadline::Fixed(deadline),
        admission: Admission::Immediate,
        verdict,
        progress,
    });
    publish
}

#[tokio::test]
async fn expired_recognition_result_cannot_stamp_a_waiting_bind() {
    let fixture = Fixture::new();
    // The fixture stamp lacks a token for a new native check. A stamp on the
    // bind would therefore mean it reused the expired recognition result.
    let stamp = OperatorAppStamp::fixture("test-app", 42);
    fixture
        .handler
        .operator_apps
        .lock()
        .unwrap()
        .insert(CONNECTION, stamp.clone());
    let deadline = Instant::now() + EVIDENCE_BUDGET;
    let progress = Arc::<RecognitionProgress>::default();
    let publish = set_recognition(
        &fixture,
        deadline,
        RecognitionVerdict::Pending,
        progress.clone(),
    );
    let mut bind = pin!(fixture.bind());
    assert!(poll_once(bind.as_mut()).await.is_pending());
    progress.complete_for_test(deadline);
    tokio::time::sleep_until(deadline.into()).await;
    publish.send_replace(RecognitionVerdict::Complete {
        stamp: Some(stamp),
        dev_build: None,
    });
    assert!(
        bind.await.is_none(),
        "a ready recognition verdict must not beat its elapsed deadline"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn expired_complete_recognition_cannot_be_fresh_on_retry() {
    let hold = Occupancy::new();
    let fixture =
        Fixture::with_check_probe(false, hold.check_probe(CheckPoint::RecognitionRetrying));
    let deadline = Instant::now() + EVIDENCE_BUDGET;
    let publish = set_recognition(
        &fixture,
        deadline,
        RecognitionVerdict::Pending,
        Arc::default(),
    );
    let handler = fixture.handler.clone();
    let mut waiting = Box::pin(async move {
        handler
            .recognize_operator_peer(CONNECTION, Admission::Wait, deadline)
            .await
            .fresh
    });
    assert!(poll_once(waiting.as_mut()).await.is_pending());
    publish.send_replace(RecognitionVerdict::Failed(PeerIdentityError::Busy));
    let retrying = tokio::spawn(waiting);
    hold.entered(1).await;
    // Another waiter completes the retry in time, but the original waiter
    // cannot read it until after the shared deadline.
    let progress = Arc::<RecognitionProgress>::default();
    progress.complete_for_test(deadline);
    let _completed = set_recognition(
        &fixture,
        deadline,
        RecognitionVerdict::Complete {
            stamp: Some(OperatorAppStamp::fixture("test-app", 42)),
            dev_build: None,
        },
        progress,
    );
    tokio::time::sleep_until(deadline.into()).await;
    hold.release();
    assert!(
        retrying.await.unwrap().is_none(),
        "a completed retry must not supply fresh evidence after its deadline"
    );
}