devsandbox 0.11.1

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

use std::io;
use std::net::{IpAddr, SocketAddr, TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use super::bridge::{self, Bridge};
use super::hash;
use crate::devsbd::{format_procs, Arch};

/// Where a connection should be dialed, resolved fresh for each (re)spawn of
/// a [`local_opener`]'s bridge. `container` is the instance whose helper carries the tunnel;
/// the daemon there dials `host:port` (loopback for an instance forward, a
/// service alias otherwise). `arch` is the instance's recorded helper arch, or
/// `None` when unknown (a pre-embedding instance) — only the Hello's
/// informational hash uses it. `label` is what the UI shows, e.g. `api:3000`
/// or `postgres:5432 (via instance api)`. `process_container` is where the
/// forwarded port actually lives — for the listening-process lookup: the
/// dialed `container` for an instance/injection forward (the bridge's helper
/// answers), but the *service* container for a via-instance route (the
/// instance can't see the service's processes, so `ForwardSpec.probe` runs).
pub struct Route {
    pub container: String,
    pub arch: Option<Arch>,
    pub host: String,
    pub port: u16,
    pub label: String,
    pub process_container: String,
    /// Whether the bridge serves the host agent: never for an instance with
    /// a git-host claim, whose daemon bridge serves it key-filtered
    /// (`agent_filter::Gate`).
    pub agent: bool,
}

/// The host port to bind. `Fixed` fails if the port is taken; `Prefer` walks
/// up from its preferred port (`3000`, `3001`, … for [`PREFER_SPAN`] ports) so
/// the result stays predictable, and only then takes an OS-assigned one.
/// `Prefer(0)` is straight to OS-assigned.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostPort {
    Fixed(u16),
    Prefer(u16),
}

/// How many ports `HostPort::Prefer` tries, its preferred one included.
pub const PREFER_SPAN: u16 = 100;

/// What an [`Opener`] tells the engine about the bridge it just opened:
/// the route label the UI shows, where the far daemon dials (`host`, `port`),
/// and where the listening process is looked up.
pub struct Opened {
    pub label: String,
    pub host: String,
    pub port: u16,
    pub lookup: ProcessLookup,
}

/// Where the listening process on the forwarded port is found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProcessLookup {
    /// The port lives where the bridge's helper runs: ask it
    /// (`Bridge::listening`), falling back to `ForwardSpec.probe` in
    /// `container` only when the helper predates the lookup.
    Helper { container: String },
    /// The port lives in `container`, which the helper can't see (a
    /// via-instance route): straight to `ForwardSpec.probe`.
    Probe { container: String },
    /// Nowhere this side can look: the process stays unknown.
    None,
}

/// Opens one bridge for a forward: called on the supervisor thread for each
/// (re)spawn, so it may touch config/state/docker (never on the caller's
/// thread). Returns as soon as the bridge is spawned; the engine waits for
/// its handshake. `stop` is set when the `Forward` is dropped: an opener that
/// blocks before it has a bridge must poll it and bail with an `Err`
/// (not shown: the forward is going away) so the drop stays prompt.
pub type Opener = Box<dyn Fn(&AtomicBool) -> Result<(Opened, Bridge), String> + Send + Sync>;

/// The opener for a forward into a local instance: `resolve` the route, then
/// `exec` a bridge into its container (`bridge::spawn_for`, serving the host
/// ssh-agent when there is one and the route allows it). The helper answers the listening-process
/// lookup when the port lives in the dialed container.
pub fn local_opener(resolve: Box<dyn Fn() -> Result<Route, String> + Send + Sync>) -> Opener {
    Box::new(move |_stop| {
        let route = resolve()?;
        let hash = route.arch.and_then(hash).unwrap_or_default();
        let bridge = bridge::spawn_for(&route.container, hash, route.agent)
            .ok_or_else(|| format!("could not exec into {}", route.container))?;
        let lookup = lookup_for(&route);
        Ok((Opened { label: route.label, host: route.host, port: route.port, lookup }, bridge))
    })
}

/// Where a local route's listening process is found: the bridge's helper when
/// the port lives in the dialed container, else the probe in the container it
/// does live in (a via-instance route).
fn lookup_for(route: &Route) -> ProcessLookup {
    let container = route.process_container.clone();
    if route.process_container == route.container {
        ProcessLookup::Helper { container }
    } else {
        ProcessLookup::Probe { container }
    }
}

/// Everything `Forward::start` needs.
pub struct ForwardSpec {
    pub bind: IpAddr,
    pub host_port: HostPort,
    pub open: Opener,
    /// Fallback listening-process lookup for the forwarded port, run in the
    /// opener's `ProcessLookup` container when the bridge's helper can't answer
    /// (`Bridge::listening`: a via-instance route, an older helper; docs/
    /// architecture/daemon/forwards.md). Called only on the forward's own
    /// (supervisor) thread, never the caller's; any failure yields `None`.
    /// Passed in so `forward.rs` stays runtime- and `commands`-generic and the
    /// pure lifecycle tests can inject a stub.
    pub probe: Box<dyn Fn(&str, u16) -> Option<String> + Send + Sync>,
}

/// Retry gap after a bridge dies before its route is re-resolved and a new one
/// spawned. Short so a transient outage (daemon restart) heals quickly; a
/// version mismatch waits longer, since only a helper rewrite (instance
/// restart) can fix it, and re-exec'ing every gap is pointless.
const RETRY: Duration = Duration::from_secs(2);
const MISMATCH_RETRY: Duration = Duration::from_secs(30);

/// How long the supervisor waits for a fresh bridge's handshake before
/// declaring it failed. Matches the bridge's own handshake watchdog: past this
/// the bridge has already killed its `exec`, so `outcome` yields the error.
const HANDSHAKE_WAIT: Duration = Duration::from_secs(10);

/// Poll cadence for the nonblocking accept loop, so `Drop` can stop it
/// promptly without `accept` blocking forever on a quiet listener.
const ACCEPT_POLL: Duration = Duration::from_millis(50);

/// Minimum gap between listening-process probes while a forward is Active.
/// Runs on the supervisor thread, folded into its bridge-liveness poll; a
/// helper query is a round trip on the bridge and the `lsof` fallback an exec
/// of ~100ms, so this keeps the poll's overhead negligible while still
/// catching a dev server that restarts under a new pid within ~10s.
const PROBE_REFRESH: Duration = Duration::from_secs(10);

/// How long a probe waits for the helper's answer. Short: the supervisor's
/// liveness poll waits behind it, so a wedged helper costs at most this.
const LOOKUP_TIMEOUT: Duration = Duration::from_secs(2);

/// The forwarder's coarse state, for the UI. `Connecting` = no live bridge yet
/// (initial spawn or a retry in flight); `Active` = a bridge handshook and is
/// carrying (or ready to carry) connections; `Error` = the last resolve/spawn
/// failed and we're in the retry gap, with the reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ForwardState {
    Connecting,
    Active,
    Error(String),
}

/// A snapshot of a forward, cheap to poll from the CLI loop or the daemon's registry.
#[derive(Debug, Clone)]
pub struct ForwardStatus {
    pub local_addr: SocketAddr,
    pub route_label: String,
    pub state: ForwardState,
    // Read by the daemon's registry for the Ports tab (docs/architecture/daemon/forwards.md); the
    // CLI doesn't surface it.
    pub open_conns: usize,
    /// `None` while a connection is open; else when the last one closed (or
    /// was accepted), or the forward's start when it never had one. What the
    /// registry's idle stop of open forwards reads.
    pub idle_since: Option<Instant>,
    /// The process listening on the forwarded port, e.g. `node (pid 412)`, or
    /// `None` when unknown (no match, no answer, or not yet probed). Refreshed
    /// on the forward's own thread; cleared whenever the bridge isn't Active.
    pub process: Option<String>,
}

/// A live forward. Dropping it stops accepting, kills the bridge (which ends
/// the mux, shutting every open connection), and joins the threads, so nothing
/// outlives it.
pub struct Forward {
    local_addr: SocketAddr,
    shared: Arc<Shared>,
    stop: Arc<AtomicBool>,
    accept: Option<std::thread::JoinHandle<()>>,
    supervisor: Option<std::thread::JoinHandle<()>>,
}

/// State shared between the supervisor (writer of `bridge`/`state`), the accept
/// loop (reader of both), and `status`/`drain_notes` callers.
struct Shared {
    /// The current bridge and its coarse state; `bridge` is `Some` only once a
    /// handshake succeeds. A single lock so a connection sees a consistent
    /// (state, bridge) pair.
    inner: Mutex<Inner>,
    /// Open connections and the idle clock, surfaced in the status.
    conns: Conns,
    /// Per-connection error notes for the UI, drained by `drain_notes`.
    notes: Mutex<Notes>,
    route_label: Mutex<String>,
    /// Where the daemon should dial for this bridge (`host`, `port`), set by
    /// the supervisor on each (re)spawn and read by `handle_conn`.
    dial: Mutex<(String, u16)>,
    /// Fallback listening-process lookup; run only on the supervisor thread.
    probe: Box<dyn Fn(&str, u16) -> Option<String> + Send + Sync>,
    /// Where to look for the listening process and on which port, from the
    /// opener, set by the supervisor on each (re)spawn.
    probe_target: Mutex<(ProcessLookup, u16)>,
    /// The last known listening process, refreshed on the supervisor thread and
    /// read by `status`. `None` whenever the forward isn't Active.
    process: Mutex<Option<String>>,
    /// Per-connection handler threads (each does the handshake wait + hands the
    /// socket to the mux, then exits). Kept so `Drop` joins them; finished ones
    /// are pruned as new connections arrive.
    handlers: Mutex<Vec<std::thread::JoinHandle<()>>>,
}

/// Open connections plus when the forward last went idle. The counter is an
/// `AtomicUsize` so `closed` (which may run on the mux reader thread) is
/// cheap; the clock is reset on every accept and whenever the count drops
/// back to 0, so a connection that opens and closes between two status
/// polls still shows as recent activity.
struct Conns {
    open: AtomicUsize,
    last_idle: Mutex<Instant>,
}

impl Conns {
    fn new(start: Instant) -> Self {
        Self { open: AtomicUsize::new(0), last_idle: Mutex::new(start) }
    }

    fn open(&self) -> usize {
        self.open.load(Ordering::Relaxed)
    }

    fn touch(&self, now: Instant) {
        *self.last_idle.lock().unwrap() = now;
    }

    fn opened(&self) {
        self.open.fetch_add(1, Ordering::Relaxed);
    }

    fn closed(&self, now: Instant) {
        // Clock under the lock first, so a reader seeing 0 open sees it too.
        let mut last = self.last_idle.lock().unwrap();
        if self.open.fetch_sub(1, Ordering::Relaxed) == 1 {
            *last = now;
        }
    }

    fn idle_since(&self) -> Option<Instant> {
        let last = self.last_idle.lock().unwrap();
        (self.open.load(Ordering::Relaxed) == 0).then_some(*last)
    }
}

struct Inner {
    // `Bridge` is `Send` but not `Sync` (its handshake channel), so it can't be
    // shared as `&Bridge` across threads. A `Mutex` makes the handle `Sync`;
    // `connect` under it is quick (register a stream, send one frame), so the
    // brief hold doesn't stall concurrent clients meaningfully.
    bridge: Option<Arc<Mutex<Bridge>>>,
    state: ForwardState,
}

/// Notes with consecutive-duplicate suppression: a broken bridge closing many
/// connections with the same reason (or a storm of `""`/`bridge closed`)
/// mustn't flood the UI.
#[derive(Default)]
struct Notes {
    pending: Vec<String>,
    last: Option<String>,
}

impl Notes {
    /// Record `note` unless it's empty, a bare `bridge closed` (routine
    /// teardown), or identical to the previous one.
    fn push(&mut self, note: String) {
        if note.is_empty() || note == "bridge closed" {
            return;
        }
        if self.last.as_deref() == Some(note.as_str()) {
            return;
        }
        self.last = Some(note.clone());
        self.pending.push(note);
    }
}

impl Forward {
    /// Bind the listener (errors here are immediate and precise), then start
    /// the accept loop and the bridge supervisor. The bridge is opened
    /// eagerly, so a bad route or a dead daemon shows up in `status`
    /// without waiting for a first client.
    pub fn start(spec: ForwardSpec) -> io::Result<Forward> {
        let ForwardSpec { bind, host_port, open, probe } = spec;
        let listener = bind_listener(bind, host_port)?;
        listener.set_nonblocking(true)?;
        let local_addr = listener.local_addr()?;

        let shared = Arc::new(Shared {
            inner: Mutex::new(Inner { bridge: None, state: ForwardState::Connecting }),
            conns: Conns::new(Instant::now()),
            notes: Mutex::new(Notes::default()),
            route_label: Mutex::new(String::new()),
            dial: Mutex::new((String::new(), 0)),
            probe,
            probe_target: Mutex::new((ProcessLookup::None, 0)),
            process: Mutex::new(None),
            handlers: Mutex::new(Vec::new()),
        });
        let stop = Arc::new(AtomicBool::new(false));

        let supervisor = {
            let shared = Arc::clone(&shared);
            let stop = Arc::clone(&stop);
            std::thread::spawn(move || supervise(open, shared, stop))
        };
        let accept = {
            let shared = Arc::clone(&shared);
            let stop = Arc::clone(&stop);
            std::thread::spawn(move || accept_loop(listener, shared, stop))
        };

        Ok(Forward { local_addr, shared, stop, accept: Some(accept), supervisor: Some(supervisor) })
    }

    /// A consistent snapshot for the UI/CLI.
    pub fn status(&self) -> ForwardStatus {
        let inner = self.shared.inner.lock().unwrap();
        ForwardStatus {
            local_addr: self.local_addr,
            route_label: self.shared.route_label.lock().unwrap().clone(),
            state: inner.state.clone(),
            open_conns: self.shared.conns.open(),
            idle_since: self.shared.conns.idle_since(),
            process: self.shared.process.lock().unwrap().clone(),
        }
    }

    /// Take the per-connection error notes accumulated since the last drain.
    pub fn drain_notes(&self) -> Vec<String> {
        std::mem::take(&mut self.shared.notes.lock().unwrap().pending)
    }
}

impl Drop for Forward {
    fn drop(&mut self) {
        // Stop accepting and end the supervisor's retry sleeps (and a
        // blocking opener, which polls it).
        self.stop.store(true, Ordering::Relaxed);
        // Drop the bridge: ends its mux, so every open connection's local
        // socket is shut and its relay threads finish.
        self.shared.inner.lock().unwrap().bridge = None;
        for handle in [self.accept.take(), self.supervisor.take()].into_iter().flatten() {
            let _ = handle.join();
        }
        // Per-connection handlers: `stop` breaks any handshake wait, the
        // dropped bridge unblocks any in-flight `connect`. Join so none
        // outlives the Forward.
        for handle in std::mem::take(&mut *self.shared.handlers.lock().unwrap()) {
            let _ = handle.join();
        }
    }
}

/// Bind the requested host port, honouring the `Prefer` fallback. `Fixed` maps
/// any bind error straight through (a clear "address already in use"); `Prefer`
/// moves on to the next port only when one is taken, so a busy default port
/// doesn't abort the forward but other errors (a privileged port) still do.
fn bind_listener(bind: IpAddr, host_port: HostPort) -> io::Result<TcpListener> {
    let port = match host_port {
        HostPort::Fixed(port) => return TcpListener::bind(SocketAddr::new(bind, port)),
        HostPort::Prefer(port) => port,
    };
    if port != 0 {
        for p in port..=port.saturating_add(PREFER_SPAN - 1) {
            match TcpListener::bind(SocketAddr::new(bind, p)) {
                Err(e) if e.kind() == io::ErrorKind::AddrInUse => continue,
                other => return other,
            }
        }
    }
    TcpListener::bind(SocketAddr::new(bind, 0))
}

/// Accept connections until `stop`. Each accepted socket is dialed through the
/// current bridge; a nonblocking listener + short sleep lets `Drop` stop the
/// loop promptly (std `accept` would otherwise block on a quiet port).
fn accept_loop(listener: TcpListener, shared: Arc<Shared>, stop: Arc<AtomicBool>) {
    while !stop.load(Ordering::Relaxed) {
        match listener.accept() {
            Ok((sock, _)) => {
                // Even a connection the bridge then drops is activity: a
                // short one between two registry polls must still count.
                shared.conns.touch(Instant::now());
                // macOS (BSD) sockets inherit the listener's O_NONBLOCK on
                // accept, Linux ones don't; the relay reads blocking, so clear
                // it or every read fails with WouldBlock.
                if sock.set_nonblocking(false).is_err() {
                    continue;
                }
                // A handler may wait (bounded) for a Connecting bridge; run it
                // off the accept loop so one client's wait can't stall the next
                // accept. Track it so `Drop` joins it, pruning finished ones.
                let handle = {
                    let (shared, stop) = (Arc::clone(&shared), Arc::clone(&stop));
                    std::thread::spawn(move || handle_conn(sock, &shared, &stop))
                };
                let mut handlers = shared.handlers.lock().unwrap();
                handlers.retain(|h| !h.is_finished());
                handlers.push(handle);
            }
            Err(e) if e.kind() == io::ErrorKind::WouldBlock => std::thread::sleep(ACCEPT_POLL),
            // Interrupted: retry. Any other error is the listener itself
            // failing; stop rather than spin.
            Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(_) => return,
        }
    }
}

/// Dial one accepted socket through the bridge. While the bridge is
/// `Connecting`, wait (bounded) for the handshake rather than dropping the
/// client; in `Error`/retry-gap, close it at once with a note so a broken
/// bridge doesn't re-exec per connection.
fn handle_conn(sock: TcpStream, shared: &Arc<Shared>, stop: &Arc<AtomicBool>) {
    let _ = sock.set_nodelay(true);
    let deadline = Instant::now() + HANDSHAKE_WAIT;
    let bridge = loop {
        if stop.load(Ordering::Relaxed) {
            return;
        }
        let (bridge, state) = {
            let inner = shared.inner.lock().unwrap();
            (inner.bridge.clone(), inner.state.clone())
        };
        match (bridge, state) {
            (Some(bridge), _) => break bridge,
            // Retry gap / hard error: don't hold the client waiting.
            (None, ForwardState::Error(reason)) => {
                shared.notes.lock().unwrap().push(format!("connection dropped: {reason}"));
                return;
            }
            // Connecting: the supervisor is spawning a bridge; wait for it.
            (None, _) => {
                if Instant::now() >= deadline {
                    shared.notes.lock().unwrap().push("connection dropped: bridge not ready".into());
                    return;
                }
                std::thread::sleep(ACCEPT_POLL);
            }
        }
    };

    shared.conns.opened();
    let (host, port) = { shared.dial.lock().unwrap().clone() };
    let on_close = {
        let shared = Arc::clone(shared);
        move |reason: String| {
            shared.conns.closed(Instant::now());
            shared.notes.lock().unwrap().push(reason);
        }
    };
    let result = bridge.lock().unwrap().connect(sock, &host, port, on_close);
    if let Err(e) = result {
        // connect didn't take ownership of the callback, so undo the increment
        // and record why (a dead bridge, an outdated helper).
        shared.conns.closed(Instant::now());
        shared.notes.lock().unwrap().push(format!("connect failed: {e}"));
    }
}

/// Keep a bridge alive for the forward. Open one eagerly; when the bridge
/// dies, wait a retry gap (longer for a version mismatch) and open again (the
/// opener re-resolves, so route changes heal). Never re-exec per connection.
fn supervise(open: Opener, shared: Arc<Shared>, stop: Arc<AtomicBool>) {
    while !stop.load(Ordering::Relaxed) {
        let gap = match try_spawn(&open, &shared, &stop) {
            SpawnOutcome::Serving(bridge) => {
                // Just became Active: probe the listening process once now, then
                // periodically inside `wait_until_dead` (docs, _Listening
                // process_). On the supervisor thread, never the caller's.
                refresh_process(&shared, &bridge);
                wait_until_dead(&bridge, &shared, &stop);
                if stop.load(Ordering::Relaxed) {
                    return;
                }
                // Bridge died: drop it, mark connecting, clear the process (it's
                // no longer known), retry per its cause.
                let mismatch = bridge.lock().unwrap().is_mismatch();
                {
                    let mut inner = shared.inner.lock().unwrap();
                    inner.bridge = None;
                    inner.state = ForwardState::Connecting;
                }
                *shared.process.lock().unwrap() = None;
                drop(bridge);
                retry_gap(mismatch)
            }
            SpawnOutcome::Failed { mismatch } => retry_gap(mismatch),
        };
        sleep_interruptible(gap, &stop);
    }
}

enum SpawnOutcome {
    /// A live, handshook bridge is now serving.
    Serving(Arc<Mutex<Bridge>>),
    /// The opener or the handshake failed; `mismatch` picks the retry gap.
    Failed { mismatch: bool },
}

/// Gap before the next spawn after a bridge died or failed: short normally, so
/// a transient outage heals fast, but long after a version mismatch, which only
/// a helper rewrite (instance restart) can fix — re-exec'ing sooner is wasted.
fn retry_gap(mismatch: bool) -> Duration {
    if mismatch { MISMATCH_RETRY } else { RETRY }
}

/// Open one bridge, waiting for its handshake. Publishes the result into
/// `shared` (state + label + bridge). On any failure records a note and leaves
/// the forward in `Error`; an opener that bailed because `stop` was set
/// records nothing.
fn try_spawn(open: &Opener, shared: &Arc<Shared>, stop: &Arc<AtomicBool>) -> SpawnOutcome {
    let (opened, bridge) = match open(stop) {
        Ok(opened) => opened,
        Err(_) if stop.load(Ordering::Relaxed) => return SpawnOutcome::Failed { mismatch: false },
        Err(reason) => {
            set_error(shared, reason);
            return SpawnOutcome::Failed { mismatch: false };
        }
    };
    *shared.route_label.lock().unwrap() = opened.label;
    *shared.dial.lock().unwrap() = (opened.host, opened.port);
    *shared.probe_target.lock().unwrap() = (opened.lookup, opened.port);
    // The handshake channel is consumed here (still sole owner), before the
    // bridge is wrapped for sharing across accept threads. Wait in short slices
    // so a `Drop` mid-handshake bails within a slice instead of blocking up to
    // HANDSHAKE_WAIT (~10s): dropping `bridge` here kills its `exec`.
    match wait_handshake(&bridge, stop) {
        Handshake::Ok => {
            let bridge = Arc::new(Mutex::new(bridge));
            {
                let mut inner = shared.inner.lock().unwrap();
                inner.bridge = Some(Arc::clone(&bridge));
                inner.state = ForwardState::Active;
            }
            SpawnOutcome::Serving(bridge)
        }
        Handshake::Err(reason) => {
            let mismatch = bridge.is_mismatch();
            set_error(shared, reason);
            SpawnOutcome::Failed { mismatch }
        }
        Handshake::TimedOut => {
            let mismatch = bridge.is_mismatch();
            set_error(shared, "helper handshake timed out".into());
            SpawnOutcome::Failed { mismatch }
        }
        // `Drop` set `stop` mid-handshake: bail silently (no note). Dropping
        // `bridge` here kills its `exec`, so the supervisor exits at once.
        Handshake::Stopped => SpawnOutcome::Failed { mismatch: false },
    }
}

/// Slice of the handshake wait, so a `stop` set by `Drop` is noticed within one
/// slice instead of blocking the whole `HANDSHAKE_WAIT`.
const HANDSHAKE_SLICE: Duration = Duration::from_millis(100);

/// Outcome of waiting for a fresh bridge's handshake.
enum Handshake {
    Ok,
    Err(String),
    /// No result within `HANDSHAKE_WAIT` (the bridge's own watchdog has already
    /// killed the `exec`).
    TimedOut,
    /// `stop` was set (a `Drop`) before the handshake resolved.
    Stopped,
}

/// Wait for `bridge`'s handshake in `HANDSHAKE_SLICE` slices up to
/// `HANDSHAKE_WAIT`, checking `stop` between slices so a `Drop` mid-handshake
/// returns promptly (the caller then drops the bridge, killing its `exec`)
/// rather than hanging for seconds. `outcome` yields its result at most once, so
/// a slice that returns `Some(..)` is the final answer.
fn wait_handshake(bridge: &Bridge, stop: &Arc<AtomicBool>) -> Handshake {
    let deadline = Instant::now() + HANDSHAKE_WAIT;
    loop {
        if stop.load(Ordering::Relaxed) {
            return Handshake::Stopped;
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Handshake::TimedOut;
        }
        match bridge.outcome(HANDSHAKE_SLICE.min(remaining)) {
            Some(Ok(())) => return Handshake::Ok,
            Some(Err(reason)) => return Handshake::Err(reason),
            // Slice elapsed with no result yet: loop to re-check `stop`.
            None => {}
        }
    }
}

fn set_error(shared: &Arc<Shared>, reason: String) {
    let mut inner = shared.inner.lock().unwrap();
    inner.state = ForwardState::Error(reason.clone());
    inner.bridge = None;
    drop(inner);
    // Leaving Active: the listening process is no longer known.
    *shared.process.lock().unwrap() = None;
    shared.notes.lock().unwrap().push(reason);
}

/// Find the listening process and store it, per the opener's
/// [`ProcessLookup`]: asked of the bridge's helper when it can see the port
/// (`helper_answer`), else the `probe` fallback in the lookup's container.
/// Only ever called on the supervisor thread; any failure (no match, no
/// answer, container gone) leaves `None`. The bridge's lock is held for the
/// query, at most `LOOKUP_TIMEOUT`.
fn refresh_process(shared: &Arc<Shared>, bridge: &Arc<Mutex<Bridge>>) {
    let (lookup, port) = shared.probe_target.lock().unwrap().clone();
    let found = match lookup {
        ProcessLookup::Helper { container } => {
            helper_answer(|| bridge.lock().unwrap().listening(port, LOOKUP_TIMEOUT))
                .unwrap_or_else(|| (shared.probe)(&container, port))
        }
        ProcessLookup::Probe { container } => (shared.probe)(&container, port),
        ProcessLookup::None => None,
    };
    *shared.process.lock().unwrap() = found;
}

/// The helper's say on the listening process: `Some(found)` when it settled
/// it (an answer, or a failure that leaves it unknown), `None` when the
/// fallback probe should run instead — the helper predates `PORT_INFO`
/// (`Unsupported`). A timeout doesn't fall back: a wedged helper's container
/// wouldn't serve an `exec` much better.
fn helper_answer(ask: impl FnOnce() -> io::Result<Vec<(u32, String)>>) -> Option<Option<String>> {
    match ask() {
        Ok(procs) => Some(format_procs(&procs)),
        Err(e) if e.kind() == io::ErrorKind::Unsupported => None,
        Err(_) => Some(None),
    }
}

/// Poll the bridge until it reports done or `stop` is set, so the supervisor
/// can respawn promptly without a keepalive of its own. Folds in the periodic
/// listening-process refresh (at most every `PROBE_REFRESH`) so it stays on
/// this thread — a probe every 10s is a negligible add to the poll.
fn wait_until_dead(bridge: &Arc<Mutex<Bridge>>, shared: &Arc<Shared>, stop: &Arc<AtomicBool>) {
    let mut next_probe = Instant::now() + PROBE_REFRESH;
    while !stop.load(Ordering::Relaxed) && !bridge.lock().unwrap().is_done() {
        if Instant::now() >= next_probe {
            refresh_process(shared, bridge);
            next_probe = Instant::now() + PROBE_REFRESH;
        }
        std::thread::sleep(ACCEPT_POLL);
    }
}

/// Sleep `dur` but wake as soon as `stop` is set, so `Drop` doesn't wait out a
/// full retry gap.
fn sleep_interruptible(dur: Duration, stop: &Arc<AtomicBool>) {
    let deadline = Instant::now() + dur;
    while Instant::now() < deadline {
        if stop.load(Ordering::Relaxed) {
            return;
        }
        std::thread::sleep(ACCEPT_POLL.min(deadline.saturating_duration_since(Instant::now())));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::net::Ipv4Addr;

    const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);

    #[test]
    fn retry_gap_is_short_unless_a_mismatch() {
        assert_eq!(retry_gap(false), RETRY);
        assert_eq!(retry_gap(true), MISMATCH_RETRY);
        assert!(MISMATCH_RETRY > RETRY);
    }

    #[test]
    fn helper_answer_table() {
        let err = |kind| move || Err(io::Error::new(kind, "x"));
        // Answered: formatted like the lsof path; empty = nothing listens.
        assert_eq!(helper_answer(|| Ok(vec![(412, "node".into())])), Some(Some("node (pid 412)".into())));
        assert_eq!(helper_answer(|| Ok(Vec::new())), Some(None));
        // Older helper: fall back to the probe.
        assert_eq!(helper_answer(err(io::ErrorKind::Unsupported)), None);
        // No answer / dead bridge: unknown, no fallback exec.
        assert_eq!(helper_answer(err(io::ErrorKind::TimedOut)), Some(None));
        assert_eq!(helper_answer(err(io::ErrorKind::BrokenPipe)), Some(None));
    }

    /// Which lookup `local_opener` picks: the helper when the port lives in
    /// the dialed container, the probe otherwise (via-instance). The
    /// "helper isn't even asked" case is `ProcessLookup::Probe`'s arm.
    #[test]
    fn local_opener_lookup_follows_the_process_container() {
        let route = |process_container: &str| Route {
            container: "c".into(),
            arch: None,
            host: "127.0.0.1".into(),
            port: 80,
            label: "x:80".into(),
            process_container: process_container.into(),
            agent: true,
        };
        assert_eq!(lookup_for(&route("c")), ProcessLookup::Helper { container: "c".into() });
        assert_eq!(lookup_for(&route("svc")), ProcessLookup::Probe { container: "svc".into() });
        // Resolve fails: no exec, the reason comes through as is.
        let open = local_opener(Box::new(|| Err("no running container".into())));
        assert_eq!(open(&AtomicBool::new(false)).err().as_deref(), Some("no running container"));
    }

    #[test]
    fn idle_since_is_none_while_open_and_resets_on_accept_and_last_close() {
        let t0 = Instant::now();
        let at = |s| t0 + Duration::from_secs(s);
        let c = Conns::new(t0);
        assert_eq!((c.open(), c.idle_since()), (0, Some(t0)), "never had one: the start");
        c.touch(at(1));
        c.opened();
        c.opened();
        assert_eq!((c.open(), c.idle_since()), (2, None));
        c.closed(at(2));
        assert_eq!(c.idle_since(), None, "one still open");
        c.closed(at(3));
        assert_eq!(c.idle_since(), Some(at(3)), "the last close");
        // A connection accepted then dropped before it was counted.
        c.touch(at(4));
        assert_eq!(c.idle_since(), Some(at(4)));
    }

    #[test]
    fn notes_drop_empty_bridge_closed_and_consecutive_dupes() {
        let mut n = Notes::default();
        n.push(String::new()); // empty: dropped
        n.push("bridge closed".into()); // routine teardown: dropped
        n.push("connection refused (127.0.0.1:3000)".into());
        n.push("connection refused (127.0.0.1:3000)".into()); // consecutive dupe
        n.push("no such host db".into());
        n.push("connection refused (127.0.0.1:3000)".into()); // not consecutive: kept
        assert_eq!(
            n.pending,
            vec![
                "connection refused (127.0.0.1:3000)".to_string(),
                "no such host db".into(),
                "connection refused (127.0.0.1:3000)".into(),
            ]
        );
    }

    #[test]
    fn prefer_walks_up_when_taken() {
        // Occupy a port, then Prefer(that port) must bind a *higher* one close
        // by (usually port + 1; a parallel test may hold that one too).
        let taken = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = taken.local_addr().unwrap().port();
        if port > u16::MAX - PREFER_SPAN {
            return; // no room above an ephemeral port this high
        }
        let listener = bind_listener(LOOPBACK, HostPort::Prefer(port)).unwrap();
        let got = listener.local_addr().unwrap().port();
        assert!(got > port && got < port + PREFER_SPAN, "{port} taken, bound {got}");
    }

    #[test]
    fn prefer_uses_the_requested_port_when_free() {
        // Reserve then release a port so it's free. Parallel tests bind
        // ephemeral loopback ports too, so one can grab it before we rebind and
        // Prefer (correctly) falls back; retry with a fresh port. A Prefer that
        // ignored a free port would miss on every attempt, so this still fails.
        for _ in 0..20 {
            let port = {
                let l = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
                l.local_addr().unwrap().port()
            };
            let listener = bind_listener(LOOPBACK, HostPort::Prefer(port)).unwrap();
            if listener.local_addr().unwrap().port() == port {
                return;
            }
        }
        panic!("Prefer never bound the requested port in 20 attempts");
    }

    #[test]
    fn fixed_errors_when_the_port_is_taken() {
        let taken = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
        let port = taken.local_addr().unwrap().port();
        let err = bind_listener(LOOPBACK, HostPort::Fixed(port)).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::AddrInUse);
    }

    /// `start` binds synchronously (so this never blocks on docker), the
    /// supervisor drives the failing resolve into `Error` with a note, and
    /// `Drop` joins cleanly. A client that connects during the outage is closed
    /// at once (a note), not held.
    #[test]
    fn failing_resolve_surfaces_error_and_drops_cleanly() {
        let forward = Forward::start(ForwardSpec {
            bind: LOOPBACK,
            host_port: HostPort::Prefer(0),
            open: local_opener(Box::new(|| Err("no running container for service redis".into()))),
            probe: no_probe(),
        })
        .unwrap();
        let addr = forward.status().local_addr;
        assert_eq!(addr.ip(), LOOPBACK);
        let started = forward.status().idle_since.expect("idle from the start");

        let mut errored = false;
        for _ in 0..200 {
            if let ForwardState::Error(reason) = forward.status().state {
                assert!(reason.contains("redis"), "{reason}");
                errored = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(errored, "state never reached Error");

        // A client during the outage is closed promptly with a note.
        let mut c = TcpStream::connect(addr).unwrap();
        let mut buf = [0u8; 1];
        c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        assert_eq!(c.read(&mut buf).unwrap(), 0, "connection closed during outage");
        let mut noted = false;
        for _ in 0..200 {
            if forward.drain_notes().iter().any(|n| n.contains("redis")) {
                noted = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        assert!(noted, "no note for the dropped connection");
        // The dropped connection still reset the idle clock.
        assert!(forward.status().idle_since.unwrap() > started);
        drop(forward); // joins without deadlock
    }

    /// An opener of any kind that fails (not just a failing resolve) lands the
    /// forward in `Error` with its reason as a note, and is retried; `Drop`
    /// stays prompt.
    #[test]
    fn failing_opener_surfaces_error_and_drops_promptly() {
        let calls = Arc::new(AtomicUsize::new(0));
        let open: Opener = {
            let calls = Arc::clone(&calls);
            Box::new(move |_| {
                calls.fetch_add(1, Ordering::Relaxed);
                Err("ssh: connect to host box: Connection refused".into())
            })
        };
        let forward =
            Forward::start(ForwardSpec { bind: LOOPBACK, host_port: HostPort::Prefer(0), open, probe: no_probe() }).unwrap();
        let deadline = Instant::now() + Duration::from_secs(2);
        while !matches!(forward.status().state, ForwardState::Error(_)) && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        assert_eq!(forward.status().state, ForwardState::Error("ssh: connect to host box: Connection refused".into()));
        assert_eq!(forward.drain_notes(), ["ssh: connect to host box: Connection refused"]);
        assert_eq!(forward.status().process, None);
        // Dropped inside the retry gap: no second open, and no waiting it out.
        let started = Instant::now();
        drop(forward);
        assert!(started.elapsed() < Duration::from_secs(1), "drop took {:?}", started.elapsed());
        assert_eq!(calls.load(Ordering::Relaxed), 1);
    }

    /// A blocking opener (the remote one waits on ssh) sees `stop` once the
    /// `Forward` is dropped, so the drop returns as soon as it bails; its
    /// `Err` then is no note or `Error`, the forward is just going away.
    #[test]
    fn drop_stops_a_blocking_opener() {
        let (entered_tx, entered) = std::sync::mpsc::channel();
        let (stopped_tx, stopped) = std::sync::mpsc::channel();
        let open: Opener = {
            let (entered_tx, stopped_tx) = (Mutex::new(entered_tx), Mutex::new(stopped_tx));
            Box::new(move |stop| {
                let _ = entered_tx.lock().unwrap().send(());
                while !stop.load(Ordering::Relaxed) {
                    std::thread::sleep(Duration::from_millis(10));
                }
                let _ = stopped_tx.lock().unwrap().send(());
                Err("stopped".into())
            })
        };
        let forward =
            Forward::start(ForwardSpec { bind: LOOPBACK, host_port: HostPort::Prefer(0), open, probe: no_probe() }).unwrap();
        entered.recv_timeout(Duration::from_secs(5)).expect("opener called");
        assert_eq!(forward.status().state, ForwardState::Connecting);
        let shared = Arc::clone(&forward.shared);
        let started = Instant::now();
        drop(forward);
        assert!(started.elapsed() < Duration::from_secs(1), "drop took {:?}", started.elapsed());
        stopped.try_recv().expect("the opener saw stop before drop returned");
        assert!(shared.notes.lock().unwrap().pending.is_empty(), "no note for a stopped open");
        assert_eq!(shared.inner.lock().unwrap().state, ForwardState::Connecting);
    }

    use crate::devsbd::{install, Arch};
    use std::process::Command;

    fn ok(cmd: &mut Command) -> bool {
        matches!(cmd.output(), Ok(o) if o.status.success())
    }

    /// A local opener whose route targets `container`'s loopback `port`
    /// (`port.rs` does the real resolution; here a fixed route is enough).
    fn loopback_route(container: String, arch: Arch, port: u16) -> Opener {
        local_opener(Box::new(move || {
            Ok(Route {
                container: container.clone(),
                arch: Some(arch),
                host: "127.0.0.1".into(),
                port,
                label: format!("test:{port}"),
                process_container: container.clone(),
                agent: true,
            })
        }))
    }

    /// A probe stub that never finds a process — the lifecycle/docker echo
    /// tests don't care about the listening-process column.
    fn no_probe() -> Box<dyn Fn(&str, u16) -> Option<String> + Send + Sync> {
        Box::new(|_, _| None)
    }

    fn wait_active(forward: &Forward) -> bool {
        for _ in 0..300 {
            if forward.status().state == ForwardState::Active {
                return true;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        false
    }

    /// Docker-gated: forward to a loopback-only echo server inside the
    /// container. Round-trips a small message, then 20 MiB (written and read
    /// concurrently so the echo drains both ways), then several concurrent
    /// clients. The server (`nc -lk … -e cat`) is the container's main command
    /// so a later `docker restart` brings it back.
    #[test_utils::docker_test(helper)]
    fn forwards_to_a_loopback_echo_server_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let name = format!("devsandbox-fwd-echo-{stamp}");
        // Loopback-only echo, reachable only from inside the netns (where the
        // daemon dials). `-lk` keeps serving across connects.
        let serve = "busybox nc -lk -s 127.0.0.1 -p 8080 -e cat";
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        crate::test_support::with_cleanup(cleanup, || {
            assert!(ok(crate::test_support::runtime_cmd().args(["run", "-d", "--name", &name, "alpine:3.20", "sh", "-c", serve])));
            let arch = install(&name, None).unwrap();

            let forward = Forward::start(ForwardSpec {
                bind: LOOPBACK,
                host_port: HostPort::Prefer(0),
                open: loopback_route(name.clone(), arch, 8080),
                probe: no_probe(),
            })
            .unwrap();
            assert!(wait_active(&forward), "forward never became Active: {:?}", forward.status().state);
            let addr = forward.status().local_addr;

            // Small round-trip. `nc -lk` may not have bound yet the instant the
            // container starts, so retry the whole client.
            let small = || -> io::Result<bool> {
                let mut c = TcpStream::connect(addr)?;
                c.set_read_timeout(Some(Duration::from_secs(5)))?;
                c.write_all(b"ping\n")?;
                let mut buf = [0u8; 5];
                c.read_exact(&mut buf)?;
                Ok(&buf == b"ping\n")
            };
            let mut round_tripped = false;
            for _ in 0..40 {
                if matches!(small(), Ok(true)) {
                    round_tripped = true;
                    break;
                }
                std::thread::sleep(Duration::from_millis(200));
            }
            assert!(round_tripped, "small echo did not round-trip");

            // 20 MiB, writing and reading concurrently (echo needs both drained).
            const N: usize = 20 << 20;
            let mut c = TcpStream::connect(addr).unwrap();
            c.set_read_timeout(Some(Duration::from_secs(30))).unwrap();
            let mut w = c.try_clone().unwrap();
            let writer = std::thread::spawn(move || {
                let mut off = 0;
                let mut buf = vec![0u8; 64 * 1024];
                while off < N {
                    let len = buf.len().min(N - off);
                    for (j, b) in buf[..len].iter_mut().enumerate() {
                        *b = (off + j) as u8;
                    }
                    w.write_all(&buf[..len]).unwrap();
                    off += len;
                }
                w.shutdown(std::net::Shutdown::Write).unwrap();
            });
            let mut got = 0;
            let mut buf = vec![0u8; 64 * 1024];
            loop {
                let n = c.read(&mut buf).unwrap();
                if n == 0 {
                    break;
                }
                for (j, &b) in buf[..n].iter().enumerate() {
                    assert_eq!(b, (got + j) as u8, "byte {} differs", got + j);
                }
                got += n;
            }
            writer.join().unwrap();
            assert_eq!(got, N, "20 MiB echoed intact");

            // Several concurrent clients each round-trip a distinct message.
            let handles: Vec<_> = (0..8)
                .map(|i| {
                    std::thread::spawn(move || {
                        let msg = format!("hello-{i}\n");
                        let mut c = TcpStream::connect(addr).unwrap();
                        c.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
                        c.write_all(msg.as_bytes()).unwrap();
                        let mut buf = vec![0u8; msg.len()];
                        c.read_exact(&mut buf).unwrap();
                        assert_eq!(buf, msg.as_bytes());
                    })
                })
                .collect();
            for h in handles {
                h.join().unwrap();
            }
            drop(forward);
            Ok(())
        })
    }

    /// Docker-gated: the listening process comes from the bridge's helper in an
    /// image where the `lsof` path finds nothing (alpine's `lsof` is busybox's,
    /// which ignores `-F`), while a route whose port lives in another container
    /// (a via-instance route) still uses the fallback probe.
    #[test_utils::docker_test(helper)]
    fn listening_process_comes_from_the_helper_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let name = format!("devsandbox-fwd-procs-{stamp}");
        let serve = "busybox nc -lk -s 127.0.0.1 -p 8080 -e cat";
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        crate::test_support::with_cleanup(cleanup, || {
            assert!(ok(crate::test_support::runtime_cmd().args(["run", "-d", "--name", &name, "alpine:3.20", "sh", "-c", serve])));
            let arch = install(&name, None).unwrap();
            let fallback = || -> Box<dyn Fn(&str, u16) -> Option<String> + Send + Sync> {
                Box::new(|container, _| Some(format!("fallback in {container}")))
            };
            let process_of = |forward: &Forward| {
                // `nc` may not have bound yet on the first probe; the next
                // comes `PROBE_REFRESH` later.
                let deadline = Instant::now() + PROBE_REFRESH + Duration::from_secs(5);
                loop {
                    if let Some(p) = forward.status().process {
                        return Some(p);
                    }
                    if Instant::now() >= deadline {
                        return None;
                    }
                    std::thread::sleep(Duration::from_millis(100));
                }
            };

            let direct = Forward::start(ForwardSpec {
                bind: LOOPBACK,
                host_port: HostPort::Prefer(0),
                open: loopback_route(name.clone(), arch, 8080),
                probe: fallback(),
            })
            .unwrap();
            assert!(wait_active(&direct), "forward never became Active: {:?}", direct.status().state);
            let found = process_of(&direct).ok_or("listening process never found")?;
            assert!(found.contains(" (pid ") && !found.contains("fallback"), "{found}");
            assert_eq!(crate::commands::port::listening_procs(&name, 8080), None, "lsof path can't tell");
            drop(direct);

            let elsewhere = {
                let name = name.clone();
                Box::new(move || {
                    Ok(Route {
                        container: name.clone(),
                        arch: Some(arch),
                        host: "127.0.0.1".into(),
                        port: 8080,
                        label: "test:8080 (via)".into(),
                        process_container: "svc-container".into(),
                        agent: true,
                    })
                })
            };
            let via = Forward::start(ForwardSpec {
                bind: LOOPBACK,
                host_port: HostPort::Prefer(0),
                open: local_opener(elsewhere),
                probe: fallback(),
            })
            .unwrap();
            assert!(wait_active(&via), "forward never became Active: {:?}", via.status().state);
            assert_eq!(process_of(&via).as_deref(), Some("fallback in svc-container"));
            drop(via);
            Ok(())
        })
    }

    /// Docker-gated: a forward to a *closed* container port. The client
    /// connection closes and a note mentions "refused".
    #[test_utils::docker_test(helper)]
    fn forward_to_a_closed_port_notes_refused_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let name = format!("devsandbox-fwd-closed-{stamp}");
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        crate::test_support::with_cleanup(cleanup, || {
            assert!(ok(crate::test_support::runtime_cmd().args(["run", "-d", "--name", &name, "alpine:3.20", "sleep", "300"])));
            let arch = install(&name, None).unwrap();
            // Port 9: nothing listening → the daemon's dial is refused.
            let forward = Forward::start(ForwardSpec {
                bind: LOOPBACK,
                host_port: HostPort::Prefer(0),
                open: loopback_route(name.clone(), arch, 9),
                probe: no_probe(),
            })
            .unwrap();
            assert!(wait_active(&forward), "forward never became Active: {:?}", forward.status().state);
            let addr = forward.status().local_addr;

            let mut c = TcpStream::connect(addr).unwrap();
            c.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
            let mut buf = [0u8; 1];
            assert_eq!(c.read(&mut buf).unwrap(), 0, "refused dial closes the client");

            let mut refused = false;
            for _ in 0..200 {
                if forward.drain_notes().iter().any(|n| n.contains("refused")) {
                    refused = true;
                    break;
                }
                std::thread::sleep(Duration::from_millis(20));
            }
            assert!(refused, "no note mentioning refused");
            drop(forward);
            Ok(())
        })
    }

    /// Docker-gated heal: `docker restart` the container (its main command is
    /// the echo server, so it comes back). After the retry gap the forward
    /// re-resolves, respawns a bridge (the helper binary survives in the
    /// writable layer; the bridge self-starts the daemon), and a new client
    /// works again.
    #[test_utils::docker_test(helper)]
    fn forward_heals_after_a_container_restart_with_docker() -> Result<(), &'static str> {
        let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let name = format!("devsandbox-fwd-heal-{stamp}");
        let serve = "busybox nc -lk -s 127.0.0.1 -p 8080 -e cat";
        let cleanup = || {
            let _ = crate::test_support::runtime_cmd().args(["rm", "-f", &name]).output();
        };
        let echo_ok = |addr: SocketAddr| -> bool {
            for _ in 0..40 {
                if let Ok(mut c) = TcpStream::connect(addr) {
                    let _ = c.set_read_timeout(Some(Duration::from_secs(5)));
                    if c.write_all(b"ping\n").is_ok() {
                        let mut buf = [0u8; 5];
                        if matches!(c.read_exact(&mut buf), Ok(())) && &buf == b"ping\n" {
                            return true;
                        }
                    }
                }
                std::thread::sleep(Duration::from_millis(250));
            }
            false
        };
        crate::test_support::with_cleanup(cleanup, || {
            assert!(ok(crate::test_support::runtime_cmd().args(["run", "-d", "--name", &name, "alpine:3.20", "sh", "-c", serve])));
            let arch = install(&name, None).unwrap();
            let forward = Forward::start(ForwardSpec {
                bind: LOOPBACK,
                host_port: HostPort::Prefer(0),
                open: loopback_route(name.clone(), arch, 8080),
                probe: no_probe(),
            })
            .unwrap();
            assert!(wait_active(&forward), "forward never became Active: {:?}", forward.status().state);
            let addr = forward.status().local_addr;
            assert!(echo_ok(addr), "echo before restart");

            // Restart the container: the bridge's exec dies, the daemon is gone.
            assert!(ok(crate::test_support::runtime_cmd().args(["restart", "-t", "1", &name])));
            // The supervisor notices, waits the retry gap, re-resolves and
            // respawns; the helper survives the restart so the bridge revives.
            assert!(echo_ok(addr), "echo after restart (healed)");
            assert_eq!(forward.status().state, ForwardState::Active, "back to Active");
            drop(forward);
            Ok(())
        })
    }
}