mxc-sdk 1.0.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
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
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Named-pipe control server: accepts phase-process connections, decodes one
//! [`DaemonRequest`] per connection, dispatches it to the WSLc worker via a
//! [`SessionHandle`], and writes back a [`DaemonResponse`] (plus a
//! [`StreamFrame`] stream for exec).
//!
//! One request per connection keeps the framing trivial and matches how the
//! state-aware client drives each lifecycle phase as a discrete call. Exec is
//! the exception: after an `Ok` admission it enters the [`StreamFrame`] data
//! phase (live stdio) until a terminal `Exit` / `Error`.
//!
//! SECURITY: every pipe instance is created with a protected DACL that grants
//! access to only the current user and Local SYSTEM (mirroring the owner-only
//! DACL stamped on the daemon's on-disk record), so no other Windows user can
//! connect to the control plane.

use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{bail, Context, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
use tokio::sync::{oneshot, Semaphore};
use tokio::task::JoinSet;
use tokio::time::timeout;
use windows::core::{PCWSTR, PWSTR};
use windows::Win32::Foundation::{CloseHandle, LocalFree, HANDLE, HLOCAL};
use windows::Win32::Security::Authorization::{
    ConvertSidToStringSidW, ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows::Win32::Security::{
    GetTokenInformation, TokenUser, PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES, TOKEN_QUERY,
    TOKEN_USER,
};
use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

use mxc_sdk::wslc_common::container_steps::OutStream;
use mxc_sdk::wslc_common::daemon_protocol::{
    encode_frame, DaemonRequest, DaemonResponse, DeprovisionConfig, ExecTerminal, StreamFrame,
    MAX_FRAME_SIZE,
};

use crate::session_manager::{ExecStream, SessionHandle, WorkerError};

/// The WSLc SDK worker is apartment-affine and executes one command at a time.
/// Refuse additional execs instead of admitting a queue that cannot run.
const MAX_CONCURRENT_EXECS: usize = 1;

/// Capacity reserved for cancellation and lifecycle requests while all exec
/// stream slots are occupied.
const CONTROL_CLIENT_RESERVE: usize = 8;

/// Upper bound on concurrently-serviced client connections. Connections beyond
/// this bound are refused without blocking the accept loop.
const MAX_CONCURRENT_CLIENTS: usize = MAX_CONCURRENT_EXECS + CONTROL_CLIENT_RESERVE;

/// Deadline for a freshly-connected client to send its first (request) frame. A
/// client that connects and then stalls must not pin a handler task — and a
/// concurrency slot — indefinitely.
const FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(30);

/// Bound on how long shutdown waits for in-flight handlers to finish before
/// abandoning them, so a wedged handler cannot block daemon exit forever.
const DRAIN_TIMEOUT: Duration = Duration::from_secs(30);

/// Bounded-backoff retry budget for recreating a control-pipe instance after a
/// transient create failure (handle/resource exhaustion). A single transient
/// hiccup must not tear the daemon — and every live sandbox — down; only a
/// failure that persists past the whole budget is treated as fatal.
const INSTANCE_RETRY_ATTEMPTS: u32 = 5;
const INSTANCE_RETRY_BACKOFF: Duration = Duration::from_millis(50);
const INSTANCE_RETRY_MAX_BACKOFF: Duration = Duration::from_millis(500);

/// Bind the first pipe instance and build the owner-only security descriptor.
///
/// Called synchronously before the daemon record is published so a client never
/// discovers a `ready` record for a pipe that is not yet listening.
pub fn bind(pipe_name: &str) -> Result<(OwnerOnlySecurity, NamedPipeServer)> {
    let security = OwnerOnlySecurity::new().context("build owner-only pipe security")?;
    let first = create_secured_instance(pipe_name, &security, true)?;
    Ok((security, first))
}

/// Run the accept loop until `shutdown` is notified.
///
/// Keeps one un-connected server instance listening; when it connects, hand it
/// to a task and create the next instance so the next client is never refused.
/// `active_clients` tracks in-flight requests so the idle watchdog does not tear
/// the daemon down mid-request. Concurrency is bounded by a semaphore, and on
/// shutdown all in-flight handlers are drained before returning so the caller
/// can release the WSLc session without racing a live handler. `activity` is a
/// monotonic connection counter the watchdog compares across polls to catch
/// bursts that start and finish between two of its samples.
pub async fn run(
    session: SessionHandle,
    pipe_name: String,
    security: OwnerOnlySecurity,
    first_instance: NamedPipeServer,
    signals: crate::DaemonSignals,
) -> Result<()> {
    let crate::DaemonSignals {
        active_clients,
        activity,
        shutdown,
        draining,
    } = signals;
    let mut server = first_instance;
    let client_limiter = Arc::new(Semaphore::new(MAX_CONCURRENT_CLIENTS));
    let exec_limiter = Arc::new(Semaphore::new(MAX_CONCURRENT_EXECS));
    let mut clients: JoinSet<()> = JoinSet::new();

    // A create-instance failure that persists past its retry budget is fatal:
    // we can no longer listen for new clients. Record it, break, then drain and
    // surface it after in-flight handlers finish — never mid-loop, so an already
    // accepted client is not abandoned.
    let mut fatal: Option<anyhow::Error> = None;

    loop {
        tokio::select! {
            // Bias toward shutdown: once the watchdog signals, prefer tearing
            // down over accepting a connection that raced the final idle sample.
            biased;

            _ = shutdown.notified() => break,
            connect = server.connect() => {
                if let Err(e) = connect {
                    eprintln!("[wslc-daemon] pipe connect error: {e}");
                    match create_secured_instance_retry(&pipe_name, &security).await {
                        Ok(next) => server = next,
                        Err(e) => {
                            fatal = Some(e.context("recreate control pipe after connect error"));
                            break;
                        }
                    }
                    continue;
                }
                // The watchdog may have entered the draining state after its
                // final sample but before this connection arrived. Refuse it
                // rather than provision into a session that is about to be
                // released, handing the client an ID that teardown invalidates.
                // The client re-spawns a fresh daemon once our record is gone.
                if draining.load(Ordering::SeqCst) {
                    break;
                }
                let connected = server;
                // Record the connection so an idle streak that spans this
                // request is invalidated even if it completes between polls.
                activity.fetch_add(1, Ordering::SeqCst);

                // Recreate the next listening instance before servicing this one
                // so the next client is not refused. Transient failures are
                // retried with bounded backoff rather than tearing the whole
                // daemon down on a single accept-capacity hiccup.
                let next = create_secured_instance_retry(&pipe_name, &security).await;

                // Service the accepted client regardless of whether we managed to
                // recreate the next instance, so a fatal recreate failure below
                // does not abandon a connection we already accepted.
                spawn_client_handler(
                    &mut clients,
                    &client_limiter,
                    &exec_limiter,
                    &session,
                    &active_clients,
                    connected,
                );

                match next {
                    Ok(n) => server = n,
                    Err(e) => {
                        fatal = Some(e.context("recreate control pipe instance"));
                        break;
                    }
                }
            }
            // Reap finished handlers so the JoinSet does not accumulate.
            Some(_) = clients.join_next() => {}
        }
    }

    // Drain in-flight handlers so the caller never releases the session/worker
    // while a handler is still using it. Abandon anything past the deadline so a
    // wedged handler cannot block daemon exit forever.
    if timeout(DRAIN_TIMEOUT, async {
        while clients.join_next().await.is_some() {}
    })
    .await
    .is_err()
    {
        eprintln!("[wslc-daemon] drain timed out; abandoning in-flight client handlers");
        clients.shutdown().await;
    }

    match fatal {
        Some(e) => Err(e),
        None => Ok(()),
    }
}

/// Spawn a bounded task to service one accepted client connection.
fn spawn_client_handler(
    clients: &mut JoinSet<()>,
    client_limiter: &Arc<Semaphore>,
    exec_limiter: &Arc<Semaphore>,
    session: &SessionHandle,
    active_clients: &Arc<AtomicUsize>,
    connected: NamedPipeServer,
) {
    let Ok(permit) = client_limiter.clone().try_acquire_owned() else {
        // The connection is already accepted, so dropping it is the only
        // bounded refusal path that cannot stall the accept loop.
        return;
    };

    let session = session.clone();
    let exec_limiter = Arc::clone(exec_limiter);
    let active = active_clients.clone();
    active.fetch_add(1, Ordering::SeqCst);
    clients.spawn(async move {
        let _permit = permit;
        if let Err(e) = handle_client(connected, session, exec_limiter).await {
            eprintln!("[wslc-daemon] client connection error: {e:#}");
        }
        active.fetch_sub(1, Ordering::SeqCst);
    });
}

/// Recreate a listening pipe instance, retrying transient failures with bounded
/// backoff so one accept-capacity/handle-exhaustion hiccup does not tear the
/// daemon — and every live sandbox — down. Only a failure that persists past the
/// whole budget is returned as an error.
async fn create_secured_instance_retry(
    pipe_name: &str,
    security: &OwnerOnlySecurity,
) -> Result<NamedPipeServer> {
    let mut backoff = INSTANCE_RETRY_BACKOFF;
    for attempt in 1..=INSTANCE_RETRY_ATTEMPTS {
        match create_secured_instance(pipe_name, security, false) {
            Ok(server) => return Ok(server),
            Err(e) if attempt < INSTANCE_RETRY_ATTEMPTS => {
                eprintln!(
                    "[wslc-daemon] pipe instance create failed \
                     (attempt {attempt}/{INSTANCE_RETRY_ATTEMPTS}): {e:#}; retrying in {backoff:?}"
                );
                tokio::time::sleep(backoff).await;
                backoff = (backoff * 2).min(INSTANCE_RETRY_MAX_BACKOFF);
            }
            Err(e) => return Err(e).context("pipe instance create exhausted retries"),
        }
    }
    unreachable!("the loop returns on the final attempt")
}

/// Create one named-pipe server instance carrying the owner-only DACL.
fn create_secured_instance(
    pipe_name: &str,
    security: &OwnerOnlySecurity,
    first: bool,
) -> Result<NamedPipeServer> {
    let mut attrs = security.attributes();
    // SAFETY: `attrs` is a valid SECURITY_ATTRIBUTES whose security descriptor
    // is owned by `security` and outlives this call.
    let server = unsafe {
        ServerOptions::new()
            .first_pipe_instance(first)
            .create_with_security_attributes_raw(
                pipe_name,
                &mut attrs as *mut SECURITY_ATTRIBUTES as *mut c_void,
            )
    }?;
    Ok(server)
}

/// Owns a `PSECURITY_DESCRIPTOR` describing a protected DACL that grants the
/// current user and Local SYSTEM full access, and nothing else.
pub(crate) struct OwnerOnlySecurity {
    psd: PSECURITY_DESCRIPTOR,
}

// SAFETY: `psd` is a self-contained LocalAlloc'd security descriptor with no
// thread affinity; ownership can move across threads freely.
unsafe impl Send for OwnerOnlySecurity {}

// SAFETY: the descriptor is immutable after construction — `attributes()` only
// copies the pointer into a `SECURITY_ATTRIBUTES` and the OS reads (never
// mutates) it, and the sole `LocalFree` happens in `Drop` on the owning thread.
// Shared `&OwnerOnlySecurity` access across threads (e.g. held across an await
// in the accept loop) is therefore race-free.
unsafe impl Sync for OwnerOnlySecurity {}

impl OwnerOnlySecurity {
    fn new() -> Result<Self> {
        let sid = current_user_sid_string()?;
        let sddl = format!("D:P(A;;FA;;;{sid})(A;;FA;;;SY)");
        let mut wide: Vec<u16> = sddl.encode_utf16().collect();
        wide.push(0);

        let mut psd = PSECURITY_DESCRIPTOR(std::ptr::null_mut());
        // SAFETY: `wide` is a NUL-terminated UTF-16 SDDL string; `psd` receives a
        // LocalAlloc'd descriptor freed in `Drop`.
        unsafe {
            ConvertStringSecurityDescriptorToSecurityDescriptorW(
                PCWSTR(wide.as_ptr()),
                SDDL_REVISION_1,
                &mut psd,
                None,
            )
        }
        .context("ConvertStringSecurityDescriptorToSecurityDescriptorW")?;
        if psd.0.is_null() {
            bail!("ConvertStringSecurityDescriptorToSecurityDescriptorW returned NULL");
        }
        Ok(Self { psd })
    }

    /// A `SECURITY_ATTRIBUTES` referencing the owned descriptor. The returned
    /// value borrows `self`; keep `self` alive while it is in use.
    fn attributes(&self) -> SECURITY_ATTRIBUTES {
        SECURITY_ATTRIBUTES {
            nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
            lpSecurityDescriptor: self.psd.0,
            bInheritHandle: false.into(),
        }
    }
}

impl Drop for OwnerOnlySecurity {
    fn drop(&mut self) {
        if !self.psd.0.is_null() {
            // SAFETY: `psd` was allocated by
            // `ConvertStringSecurityDescriptorToSecurityDescriptorW`, which
            // documents `LocalFree` as the matching deallocator.
            unsafe {
                let _ = LocalFree(Some(HLOCAL(self.psd.0)));
            }
        }
    }
}

/// Resolve the current process token's user SID as an SDDL string (e.g. `S-1-5-...`).
fn current_user_sid_string() -> Result<String> {
    // SAFETY: standard token-query sequence; every raw pointer is backed by a
    // live local, and both the token handle and the LocalAlloc'd SID string are
    // released before returning.
    unsafe {
        let mut token = HANDLE::default();
        OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token)
            .context("OpenProcessToken")?;

        // First call sizes the buffer (expected to fail with insufficient buffer).
        let mut len = 0u32;
        let _ = GetTokenInformation(token, TokenUser, None, 0, &mut len);
        let mut buf = vec![0u8; len as usize];
        let info = GetTokenInformation(
            token,
            TokenUser,
            Some(buf.as_mut_ptr() as *mut c_void),
            len,
            &mut len,
        );
        let _ = CloseHandle(token);
        info.context("GetTokenInformation(TokenUser)")?;

        let token_user = &*(buf.as_ptr() as *const TOKEN_USER);
        let mut sid_wstr = PWSTR::null();
        ConvertSidToStringSidW(token_user.User.Sid, &mut sid_wstr)
            .context("ConvertSidToStringSidW")?;
        let sid = sid_wstr
            .to_string()
            .context("SID string was not valid UTF-16")?;
        let _ = LocalFree(Some(HLOCAL(sid_wstr.0 as *mut c_void)));
        Ok(sid)
    }
}

/// Attempts to release a sandbox whose id never reached its caller, and the
/// wait between them. The container holds the idle watchdog open, so a
/// transient SDK failure is worth retrying rather than logging once.
const UNDELIVERED_RELEASE_ATTEMPTS: u32 = 3;
const UNDELIVERED_RELEASE_BACKOFF: Duration = Duration::from_secs(2);

/// Deprovision a sandbox whose `Provisioned` reply could not be delivered.
///
/// Nobody else can: the id exists only here, so this is its last owner.
async fn release_undelivered_sandbox(session: &SessionHandle, sandbox_id: &str) {
    for attempt in 1..=UNDELIVERED_RELEASE_ATTEMPTS {
        let config = DeprovisionConfig {
            sandbox_id: sandbox_id.to_string(),
        };
        match session.deprovision(config).await {
            Ok(()) => {
                eprintln!(
                    "[wslc-daemon] released {sandbox_id}: its provision reply never \
                     reached the client"
                );
                return;
            }
            Err(e) if attempt == UNDELIVERED_RELEASE_ATTEMPTS => {
                eprintln!(
                    "[wslc-daemon] could not release {sandbox_id} after \
                     {UNDELIVERED_RELEASE_ATTEMPTS} attempts: {e}. It was retired from the live \
                     count and will be deleted when the daemon shuts down."
                );

                // Nothing can reach this sandbox, so counting it would hold the
                // daemon open for a client that will never call back.
                session.retire(sandbox_id.to_string()).await.ok();
            }
            Err(e) => {
                eprintln!("[wslc-daemon] release of {sandbox_id} failed ({e}); retrying");
                tokio::time::sleep(UNDELIVERED_RELEASE_BACKOFF).await;
            }
        }
    }
}

/// Write a provision reply, releasing the sandbox if the reply did not land.
///
/// An id that never reaches its caller names a container nobody can
/// deprovision, and its entry holds the idle watchdog's count above zero.
///
/// `release` is a parameter so this path can be tested without a live session.
async fn deliver_provision_reply<S, F, Fut>(
    pipe: &mut S,
    resp: &DaemonResponse,
    release: F,
) -> Result<()>
where
    S: AsyncWrite + Unpin,
    F: FnOnce(String) -> Fut,
    Fut: std::future::Future<Output = ()>,
{
    let delivered = write_frame(pipe, resp).await;
    if let (Err(_), DaemonResponse::Provisioned { sandbox_id }) = (&delivered, resp) {
        release(sandbox_id.clone()).await;
    }
    delivered
}

/// Service exactly one request on a freshly-connected pipe instance.
async fn handle_client<S>(
    mut pipe: S,
    session: SessionHandle,
    exec_limiter: Arc<Semaphore>,
) -> Result<()>
where
    S: AsyncRead + AsyncWrite + Unpin,
{
    // Bound the wait for the request frame so a client that connects and then
    // stalls cannot pin this handler (and its concurrency slot) indefinitely.
    let request: DaemonRequest = timeout(FIRST_FRAME_TIMEOUT, read_frame(&mut pipe))
        .await
        .context("timed out waiting for the client's first frame")??;
    match request {
        DaemonRequest::Ping => {
            write_frame(&mut pipe, &DaemonResponse::Pong).await?;
        }
        DaemonRequest::Provision(config) => {
            let resp = match session.provision(config).await {
                Ok(sandbox_id) => DaemonResponse::Provisioned { sandbox_id },
                Err(e) => worker_err_response(e),
            };
            deliver_provision_reply(&mut pipe, &resp, |sandbox_id| {
                let session = &session;
                async move { release_undelivered_sandbox(session, &sandbox_id).await }
            })
            .await?;
        }
        DaemonRequest::Start(config) => {
            let resp = ok_or_err(session.start(config).await);
            write_frame(&mut pipe, &resp).await?;
        }
        DaemonRequest::Stop(config) => {
            let resp = ok_or_err(session.stop(config).await);
            write_frame(&mut pipe, &resp).await?;
        }
        DaemonRequest::Deprovision(config) => {
            let resp = ok_or_err(session.deprovision(config).await);
            write_frame(&mut pipe, &resp).await?;
        }
        DaemonRequest::Exec(config) => {
            let Ok(exec_permit) = exec_limiter.try_acquire_owned() else {
                write_frame(
                    &mut pipe,
                    &DaemonResponse::Err {
                        kind: mxc_sdk::wslc_common::daemon_protocol::ErrKind::Busy,
                        message: "WSLc daemon exec capacity is exhausted".to_string(),
                    },
                )
                .await?;
                return Ok(());
            };
            handle_exec(pipe, session, config, exec_permit).await?;
        }
        DaemonRequest::CancelExec(config) => {
            session.cancel_exec(&config.exec_id, &config.run_token);
            write_frame(&mut pipe, &DaemonResponse::Ok).await?;
        }
    }
    Ok(())
}

/// Exec: validate-then-admit, then stream the run's stdout/stderr live as
/// [`StreamFrame`]s, followed by a terminal frame.
///
/// The sandbox is validated (exists + started) *before* the `Ok` admission is
/// written, and — critically — admission is **atomic** with the start of the
/// run on the worker thread (see [`SessionHandle::exec`]): the worker validates
/// and begins running within one command handler, so no `Stop`/`Deprovision`
/// can invalidate the checked state between the admission and the run. An
/// unknown/not-started sandbox therefore comes back as a pre-admission typed
/// [`DaemonResponse::Err`] rather than a post-admission stream `Error` frame.
///
/// Output streaming (process -> `Stdout`/`Stderr`) is live. Client `Stdin`
/// frames are NOT forwarded: the WSLc SDK consumes all process IO handles once
/// any `WslcSetProcessSettingsCallbacks` is registered (the callback path this
/// live output streaming depends on), so `WslcGetProcessIOHandle(STDIN)` is
/// unavailable. Piped stdin would require a handle-mode rearchitecture (no
/// callbacks; `ReadFile` threads for stdout/stderr + `WriteFile` for stdin) and
/// is deferred; stdin forwarding is tracked in issue #804.
async fn handle_exec<S>(
    mut pipe: S,
    session: SessionHandle,
    config: mxc_sdk::wslc_common::daemon_protocol::ExecConfig,
    _exec_permit: tokio::sync::OwnedSemaphorePermit,
) -> Result<()>
where
    S: AsyncWrite + Unpin,
{
    // Await the worker's admission decision before writing anything: a rejected
    // exec is a pre-admission typed error, never a post-admission stream frame.
    write_exec_result(&mut pipe, session.exec(config).await).await
}

/// Turn an exec **admission** outcome into the client's frame sequence, generic
/// over the transport so the protocol can be exercised over an in-memory duplex
/// in tests. On rejection it writes a single typed [`DaemonResponse::Err`]; on
/// admission it writes `Ok`, then pumps live `Stdout`/`Stderr` frames as output
/// arrives, and finally writes exactly one terminal [`StreamFrame`] — `Exit` on
/// success, `Error` on a run failure or a dropped completion channel.
async fn write_exec_result<S: AsyncWrite + Unpin>(
    pipe: &mut S,
    admission: Result<ExecStream, WorkerError>,
) -> Result<()> {
    let ExecStream {
        done,
        mut output,
        overflowed,
        registration: _registration,
    } = match admission {
        Ok(stream) => stream,
        Err(e) => {
            write_frame(pipe, &worker_err_response(e)).await?;
            return Ok(());
        }
    };
    write_frame(pipe, &DaemonResponse::Ok).await?;

    // Pump live output until the run completes, then write exactly one terminal
    // frame. The select is **biased toward `done`** so a completed run always
    // makes progress to termination: on the deliberate kill/leak path the sink's
    // sender stays alive and can keep producing forever, and a biased-toward-
    // output loop would let that continuously non-empty queue starve the ready
    // `done` branch — the terminal frame would never be written and the client
    // would stream forever. While the run is in flight `done` is not ready, so
    // the fall-through streams live output as it arrives.
    //
    // Once `done` resolves we `close()` the receiver (so any leaked producer can
    // enqueue nothing further), drain only the already-queued bounded tail with
    // non-blocking `try_recv`, and terminate. On the normal path the run has
    // already stopped producing, so that tail is exactly the remaining real
    // output; the sink's sender also drops as the run returns, so `output` may
    // instead close first — the `None` arm handles that and awaits the exit code.
    let mut done = done;
    let (notice, terminal) = loop {
        tokio::select! {
            biased;
            result = &mut done => {
                output.close();
                while let Ok(chunk) = output.try_recv() {
                    write_frame(pipe, &output_frame(chunk)).await?;
                }
                break terminal_frames(result, &overflowed);
            }
            chunk = output.recv() => match chunk {
                Some(chunk) => {
                    write_frame(pipe, &output_frame(chunk)).await?;
                }
                // Senders dropped before `done` fired (normal path): the run has
                // completed and every chunk is flushed. Await the exit code.
                None => break terminal_frames(done.await, &overflowed),
            },
        }
    };
    if let Some(notice) = notice {
        write_frame(pipe, &notice).await?;
    }
    write_frame(pipe, &terminal).await?;
    Ok(())
}

/// Map a live-output chunk to its wire frame.
fn output_frame((kind, data): (OutStream, Vec<u8>)) -> StreamFrame {
    match kind {
        OutStream::Stdout => StreamFrame::Stdout { data },
        OutStream::Stderr => StreamFrame::Stderr { data },
    }
}

/// Choose the exec's terminal [`StreamFrame`], and the notice that precedes it
/// when the sink had to drop live output.
///
/// Truncation travels ahead of the terminal rather than replacing it: every
/// terminal carries something the client cannot reconstruct — an exit code, or
/// why the run ended.
fn terminal_frames(
    result: Result<Result<ExecTerminal, WorkerError>, oneshot::error::RecvError>,
    overflowed: &AtomicBool,
) -> (Option<StreamFrame>, StreamFrame) {
    let terminal = exit_terminal(result);
    if overflowed.load(Ordering::Relaxed) {
        (Some(StreamFrame::Truncated), terminal)
    } else {
        (None, terminal)
    }
}

/// Map a completed exec's result (or a dropped completion channel) to its
/// terminal [`StreamFrame`].
fn exit_terminal(
    result: Result<Result<ExecTerminal, WorkerError>, oneshot::error::RecvError>,
) -> StreamFrame {
    match result {
        Ok(Ok(ExecTerminal::Exited(code))) => StreamFrame::Exit { code },
        Ok(Ok(ExecTerminal::TimedOut)) => StreamFrame::TimedOut,
        Ok(Ok(ExecTerminal::Cancelled)) => StreamFrame::Cancelled,
        Ok(Err(e)) => StreamFrame::Error {
            message: e.to_string(),
        },
        Err(_) => StreamFrame::Error {
            message: "WSLc worker dropped the exec reply channel".to_string(),
        },
    }
}

/// Map a worker `Result<()>` to an `Ok` / typed `Err` response.
fn ok_or_err(result: Result<(), WorkerError>) -> DaemonResponse {
    match result {
        Ok(()) => DaemonResponse::Ok,
        Err(e) => worker_err_response(e),
    }
}

/// Build a [`DaemonResponse::Err`] carrying the worker error's protocol `kind`.
fn worker_err_response(e: WorkerError) -> DaemonResponse {
    DaemonResponse::Err {
        kind: e.kind(),
        message: e.to_string(),
    }
}

/// Read one length-prefixed frame and deserialise it.
async fn read_frame<S: AsyncRead + Unpin, T: DeserializeOwned>(pipe: &mut S) -> Result<T> {
    let mut len_buf = [0u8; 4];
    pipe.read_exact(&mut len_buf).await?;
    let len = u32::from_le_bytes(len_buf) as usize;
    if len > MAX_FRAME_SIZE {
        bail!("incoming frame length {len} exceeds maximum {MAX_FRAME_SIZE}");
    }
    let mut body = vec![0u8; len];
    pipe.read_exact(&mut body).await?;
    Ok(serde_json::from_slice(&body)?)
}

/// Serialise `msg` and write it as a length-prefixed frame.
async fn write_frame<S: AsyncWrite + Unpin, T: Serialize>(pipe: &mut S, msg: &T) -> Result<()> {
    let frame = encode_frame(msg)?;
    pipe.write_all(&frame).await?;
    pipe.flush().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session_manager::{register_exec, spawn};
    use mxc_sdk::wslc_common::daemon_protocol::{
        CancelExecConfig, ErrKind, ExecConfig, ProvisionConfig,
    };
    use tokio::io::duplex;
    use tokio::sync::mpsc;

    fn test_registration() -> Arc<crate::session_manager::ExecRegistration> {
        let active_execs = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let cancellation = Arc::new(AtomicBool::new(false));
        Arc::new(register_exec(&active_execs, "test-exec", "test-run", &cancellation).unwrap())
    }

    #[tokio::test]
    async fn exhausted_exec_capacity_returns_busy() {
        let session = spawn().unwrap();
        let exec_limiter = Arc::new(Semaphore::new(1));
        let _permit = exec_limiter.clone().acquire_owned().await.unwrap();
        let (mut client, server) = duplex(64 * 1024);
        write_frame(
            &mut client,
            &DaemonRequest::Exec(ExecConfig {
                exec_id: "exec-busy".to_string(),
                run_token: "run-busy".to_string(),
                sandbox_id: "wslc:test".to_string(),
                script_code: "echo hi".to_string(),
                working_directory: String::new(),
                env: Vec::new(),
                env_scope: mxc_sdk::wslc_common::process_env::EnvScope::Merge,
                timeout_ms: 0,
            }),
        )
        .await
        .unwrap();

        handle_client(server, session.clone(), exec_limiter)
            .await
            .unwrap();

        let response: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(
            response,
            DaemonResponse::Err {
                kind: ErrKind::Busy,
                message: "WSLc daemon exec capacity is exhausted".to_string(),
            }
        );
        session.shutdown().await.unwrap();
    }

    /// A writer that always fails, standing in for a client that has gone.
    struct BrokenPipe;

    impl AsyncWrite for BrokenPipe {
        fn poll_write(
            self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
            _buf: &[u8],
        ) -> std::task::Poll<std::io::Result<usize>> {
            std::task::Poll::Ready(Err(std::io::Error::from(std::io::ErrorKind::BrokenPipe)))
        }

        fn poll_flush(
            self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            std::task::Poll::Ready(Ok(()))
        }

        fn poll_shutdown(
            self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
        ) -> std::task::Poll<std::io::Result<()>> {
            std::task::Poll::Ready(Ok(()))
        }
    }

    #[tokio::test]
    async fn an_undelivered_provisioned_reply_releases_that_sandbox() {
        let released = std::cell::RefCell::new(Vec::new());
        let resp = DaemonResponse::Provisioned {
            sandbox_id: "wslc:abc".to_string(),
        };

        let outcome = deliver_provision_reply(&mut BrokenPipe, &resp, |id| {
            released.borrow_mut().push(id);
            std::future::ready(())
        })
        .await;

        assert!(outcome.is_err(), "a failed write must not report success");
        assert_eq!(released.into_inner(), vec!["wslc:abc".to_string()]);
    }

    #[tokio::test]
    async fn an_undelivered_error_reply_releases_nothing() {
        let released = std::cell::RefCell::new(Vec::new());
        let resp = DaemonResponse::Err {
            kind: ErrKind::Backend,
            message: "provision failed".to_string(),
        };

        let outcome = deliver_provision_reply(&mut BrokenPipe, &resp, |id| {
            released.borrow_mut().push(id);
            std::future::ready(())
        })
        .await;

        assert!(outcome.is_err(), "a failed write must not report success");
        assert!(
            released.into_inner().is_empty(),
            "an error reply names no sandbox to release"
        );
    }

    #[tokio::test]
    async fn a_delivered_provisioned_reply_releases_nothing() {
        let released = std::cell::RefCell::new(Vec::new());
        let resp = DaemonResponse::Provisioned {
            sandbox_id: "wslc:abc".to_string(),
        };
        let (mut client, mut server) = duplex(64 * 1024);

        let outcome = deliver_provision_reply(&mut server, &resp, |id| {
            released.borrow_mut().push(id);
            std::future::ready(())
        })
        .await;

        assert!(outcome.is_ok(), "the write succeeded");
        assert!(
            released.into_inner().is_empty(),
            "a delivered id has an owner; releasing it would destroy a live sandbox"
        );
        let echoed: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(echoed, resp);
    }

    /// A client that disappears before reading its reply must surface as an
    /// error from the handler, which is what triggers releasing the sandbox its
    /// id would have named.
    #[tokio::test]
    async fn a_vanished_client_fails_the_provision_handler() {
        let session = spawn().unwrap();
        let exec_limiter = Arc::new(Semaphore::new(1));
        let (mut client, server) = duplex(64 * 1024);
        write_frame(
            &mut client,
            &DaemonRequest::Provision(ProvisionConfig {
                image: "alpine:latest".to_string(),
                image_tar_path: None,
                volumes: Vec::new(),
                network: Default::default(),
            }),
        )
        .await
        .unwrap();
        drop(client);

        let outcome = handle_client(server, session.clone(), exec_limiter).await;
        assert!(
            outcome.is_err(),
            "an undelivered reply must not be reported as a served request"
        );

        // Whichever way provision went, no sandbox may be left behind: a minted
        // id was released above, and a failure minted none.
        assert_eq!(session.container_count().await.unwrap(), 0);
        session.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn cancel_exec_request_dispatches_successfully() {
        let session = spawn().unwrap();
        let exec_limiter = Arc::new(Semaphore::new(1));
        let (mut client, server) = duplex(64 * 1024);
        write_frame(
            &mut client,
            &DaemonRequest::CancelExec(CancelExecConfig {
                exec_id: "unknown-exec".to_string(),
                run_token: "unknown-run".to_string(),
            }),
        )
        .await
        .unwrap();

        handle_client(server, session.clone(), exec_limiter)
            .await
            .unwrap();

        let response: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(response, DaemonResponse::Ok);
        session.shutdown().await.unwrap();
    }

    /// Admit an exec whose output channel is already closed (no live output),
    /// so `write_exec_result` goes straight from `Ok` to the terminal frame.
    fn admitted_no_output(
        done: oneshot::Receiver<Result<ExecTerminal, WorkerError>>,
    ) -> Result<ExecStream, WorkerError> {
        let (tx, output) = mpsc::channel(16);
        drop(tx);
        Ok(ExecStream {
            done,
            output,
            overflowed: Arc::new(AtomicBool::new(false)),
            registration: test_registration(),
        })
    }

    /// A rejected admission (unknown sandbox) round-trips as a single typed
    /// `DaemonResponse::Err { NotProvisioned }` through frame encode → transport
    /// → decode, with no terminal frame following it.
    #[tokio::test]
    async fn exec_rejection_round_trips_as_typed_error() {
        let (mut server, mut client) = duplex(64 * 1024);
        let admission = Err(WorkerError::NotProvisioned("wslc:nope".to_string()));

        write_exec_result(&mut server, admission).await.unwrap();
        drop(server);

        let resp: DaemonResponse = read_frame(&mut client).await.unwrap();
        match resp {
            DaemonResponse::Err { kind, message } => {
                assert_eq!(kind, ErrKind::NotProvisioned);
                assert!(message.contains("wslc:nope"), "message was {message:?}");
            }
            other => panic!("expected a typed Err response, got {other:?}"),
        }
        // A rejected exec is a single frame: nothing else follows.
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
    }

    /// The `NotStarted` admission contract has an SDK-free regression here: a
    /// provisioned-but-not-started sandbox surfaces as a typed pre-admission
    /// error, exercised without constructing a real container handle.
    #[tokio::test]
    async fn exec_not_started_round_trips_as_typed_error() {
        let (mut server, mut client) = duplex(64 * 1024);
        let admission = Err(WorkerError::NotStarted("wslc:cold".to_string()));

        write_exec_result(&mut server, admission).await.unwrap();
        drop(server);

        let resp: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(
            resp,
            DaemonResponse::Err {
                kind: ErrKind::NotStarted,
                message: "sandbox wslc:cold is not started".to_string(),
            }
        );
    }

    /// Dropping the completion sender after admission must produce exactly one
    /// terminal `StreamFrame::Error` — never a hang or a malformed stream.
    #[tokio::test]
    async fn dropped_completion_channel_yields_single_error_terminal() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        drop(done_tx);

        write_exec_result(&mut server, admitted_no_output(done_rx))
            .await
            .unwrap();
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        let terminal: StreamFrame = read_frame(&mut client).await.unwrap();
        match terminal {
            StreamFrame::Error { message } => {
                assert!(
                    message.contains("dropped the exec reply channel"),
                    "message was {message:?}"
                );
            }
            other => panic!("expected a terminal Error frame, got {other:?}"),
        }
        // Exactly one terminal frame is emitted.
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
    }

    /// A successful run writes admission `Ok` then a single `Exit` terminal
    /// carrying the process exit code.
    #[tokio::test]
    async fn successful_exec_writes_ok_then_exit() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        done_tx.send(Ok(ExecTerminal::Exited(7))).unwrap();

        write_exec_result(&mut server, admitted_no_output(done_rx))
            .await
            .unwrap();
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        let terminal: StreamFrame = read_frame(&mut client).await.unwrap();
        assert_eq!(terminal, StreamFrame::Exit { code: 7 });
    }

    #[tokio::test]
    async fn exec_id_stays_registered_until_terminal_delivery() {
        let active_execs = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let cancellation = Arc::new(AtomicBool::new(false));
        let registration =
            Arc::new(register_exec(&active_execs, "exec-1", "run-1", &cancellation).unwrap());
        let worker_registration = Arc::clone(&registration);
        let (mut server, mut client) = duplex(1);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        done_tx.send(Ok(ExecTerminal::Exited(0))).unwrap();
        let (output_tx, output) = mpsc::channel(1);
        drop(output_tx);

        let writer = tokio::spawn(async move {
            write_exec_result(
                &mut server,
                Ok(ExecStream {
                    done: done_rx,
                    output,
                    overflowed: Arc::new(AtomicBool::new(false)),
                    registration,
                }),
            )
            .await
        });

        assert_eq!(
            read_frame::<_, DaemonResponse>(&mut client).await.unwrap(),
            DaemonResponse::Ok
        );
        drop(worker_registration);
        tokio::task::yield_now().await;

        let replacement = Arc::new(AtomicBool::new(false));
        let error = register_exec(&active_execs, "exec-1", "run-2", &replacement).unwrap_err();
        assert_eq!(error.kind(), ErrKind::Rejected);

        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Exit { code: 0 }
        );
        writer.await.unwrap().unwrap();

        let replacement_registration =
            register_exec(&active_execs, "exec-1", "run-2", &replacement).unwrap();
        drop(replacement_registration);
    }

    #[tokio::test]
    async fn timeout_writes_a_typed_terminal_frame() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        done_tx.send(Ok(ExecTerminal::TimedOut)).unwrap();

        write_exec_result(&mut server, admitted_no_output(done_rx))
            .await
            .unwrap();

        assert_eq!(
            read_frame::<_, DaemonResponse>(&mut client).await.unwrap(),
            DaemonResponse::Ok
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::TimedOut
        );
    }

    #[tokio::test]
    async fn cancellation_writes_a_typed_terminal_frame() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        done_tx.send(Ok(ExecTerminal::Cancelled)).unwrap();

        write_exec_result(&mut server, admitted_no_output(done_rx))
            .await
            .unwrap();

        assert_eq!(
            read_frame::<_, DaemonResponse>(&mut client).await.unwrap(),
            DaemonResponse::Ok
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Cancelled
        );
    }

    /// Live output is streamed as `Stdout`/`Stderr` frames — in the order the
    /// worker enqueued them — before the terminal `Exit`, so the client sees the
    /// run's output incrementally rather than as one buffered blob.
    #[tokio::test]
    async fn live_output_streams_before_exit() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        let (out_tx, output) = mpsc::channel(16);

        // Enqueue interleaved output, then the exit code, then close the channel
        // (mirrors the worker: the sink's sender drops as the run returns).
        out_tx
            .try_send((OutStream::Stdout, b"hello ".to_vec()))
            .unwrap();
        out_tx
            .try_send((OutStream::Stderr, b"warn".to_vec()))
            .unwrap();
        out_tx
            .try_send((OutStream::Stdout, b"world".to_vec()))
            .unwrap();
        done_tx.send(Ok(ExecTerminal::Exited(0))).unwrap();
        drop(out_tx);

        write_exec_result(
            &mut server,
            Ok(ExecStream {
                done: done_rx,
                output,
                overflowed: Arc::new(AtomicBool::new(false)),
                registration: test_registration(),
            }),
        )
        .await
        .unwrap();
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Stdout {
                data: b"hello ".to_vec()
            }
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Stderr {
                data: b"warn".to_vec()
            }
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Stdout {
                data: b"world".to_vec()
            }
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Exit { code: 0 }
        );
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
    }

    /// Leak path: the run completes (`done` fires) while the sink's sender is
    /// still alive and would keep producing. `write_exec_result` must close the
    /// receiver, flush only what was already queued, and write the terminal
    /// frame — it must not stream chunks enqueued after completion nor hang.
    #[tokio::test]
    async fn leak_path_drains_queued_then_terminates() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        let (out_tx, output) = mpsc::channel(16);

        // Two chunks already queued, the run reports its exit, and the sender is
        // deliberately kept alive (the leaked `IoContext`).
        out_tx
            .try_send((OutStream::Stdout, b"queued".to_vec()))
            .unwrap();
        out_tx
            .try_send((OutStream::Stderr, b"tail".to_vec()))
            .unwrap();
        done_tx.send(Ok(ExecTerminal::Exited(3))).unwrap();

        write_exec_result(
            &mut server,
            Ok(ExecStream {
                done: done_rx,
                output,
                overflowed: Arc::new(AtomicBool::new(false)),
                registration: test_registration(),
            }),
        )
        .await
        .unwrap();

        // A post-completion enqueue attempt must fail because the receiver was
        // closed, proving a leaked producer cannot extend the stream.
        assert!(out_tx
            .try_send((OutStream::Stdout, b"after".to_vec()))
            .is_err());
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Stdout {
                data: b"queued".to_vec()
            }
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Stderr {
                data: b"tail".to_vec()
            }
        );
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Exit { code: 3 }
        );
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
    }

    /// Starvation regression: completion (`done`) must terminate the stream even
    /// when a leaked producer keeps the queue continuously non-empty. A task
    /// enqueues forever while `done` is already resolved; because the select is
    /// biased toward `done`, the handler closes the receiver, drains the bounded
    /// tail, and writes the terminal frame instead of streaming the infinite
    /// producer forever. (A biased-toward-output loop would hang here.)
    #[tokio::test]
    async fn continuous_producer_does_not_starve_terminal() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        // Small queue so a fast producer keeps it perpetually non-empty.
        let (out_tx, output) = mpsc::channel(4);

        // Completion is already ready before the handler runs.
        done_tx.send(Ok(ExecTerminal::Exited(5))).unwrap();
        // A producer that keeps enqueuing (the leaked `IoContext` on the kill
        // path). It races the handler; `send` errors once the receiver closes,
        // ending the task — so this never leaks past the test.
        let producer = tokio::spawn(async move {
            loop {
                if out_tx
                    .send((OutStream::Stdout, b"x".to_vec()))
                    .await
                    .is_err()
                {
                    break;
                }
            }
        });

        // Must complete (not hang). A generous timeout guards a regression to a
        // starving loop, which would never return.
        let result = tokio::time::timeout(
            Duration::from_secs(5),
            write_exec_result(
                &mut server,
                Ok(ExecStream {
                    done: done_rx,
                    output,
                    overflowed: Arc::new(AtomicBool::new(false)),
                    registration: test_registration(),
                }),
            ),
        )
        .await
        .expect("write_exec_result must terminate, not starve on continuous output");
        result.unwrap();
        drop(server);
        let _ = producer.await;

        // The stream ends with a single `Exit` terminal after some prefix of
        // `Stdout` frames; it must not stream indefinitely.
        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        let mut saw_exit = false;
        while let Ok(frame) = read_frame::<_, StreamFrame>(&mut client).await {
            match frame {
                StreamFrame::Stdout { .. } => {}
                StreamFrame::Exit { code } => {
                    assert_eq!(code, 5);
                    saw_exit = true;
                    break;
                }
                other => panic!("unexpected frame: {other:?}"),
            }
        }
        assert!(saw_exit, "the stream must end with an Exit terminal");
    }

    /// Overflow regression: the client must be told, and must still receive the
    /// exit code the process produced.
    #[tokio::test]
    async fn overflow_precedes_a_clean_exit_without_replacing_it() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        let (out_tx, output) = mpsc::channel(16);

        // Some output made it through before the drop, then a clean exit, but the
        // sink signalled truncation.
        out_tx
            .try_send((OutStream::Stdout, b"partial".to_vec()))
            .unwrap();
        done_tx.send(Ok(ExecTerminal::Exited(0))).unwrap();
        drop(out_tx);
        let overflowed = Arc::new(AtomicBool::new(true));

        write_exec_result(
            &mut server,
            Ok(ExecStream {
                done: done_rx,
                output,
                overflowed,
                registration: test_registration(),
            }),
        )
        .await
        .unwrap();
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Stdout {
                data: b"partial".to_vec()
            }
        );
        let terminal: StreamFrame = read_frame(&mut client).await.unwrap();
        assert_eq!(terminal, StreamFrame::Truncated);
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::Exit { code: 0 }
        );
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
    }

    #[tokio::test]
    async fn overflow_precedes_a_timeout_terminal_without_replacing_it() {
        assert_eq!(
            overflowed_frames(ExecTerminal::TimedOut).await,
            (Some(StreamFrame::Truncated), StreamFrame::TimedOut)
        );
    }

    #[tokio::test]
    async fn overflow_precedes_a_cancellation_terminal_without_replacing_it() {
        assert_eq!(
            overflowed_frames(ExecTerminal::Cancelled).await,
            (Some(StreamFrame::Truncated), StreamFrame::Cancelled)
        );
    }

    #[tokio::test]
    async fn a_clean_run_emits_no_truncation_notice() {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        let (out_tx, output) = mpsc::channel(16);
        done_tx.send(Ok(ExecTerminal::TimedOut)).unwrap();
        drop(out_tx);

        write_exec_result(
            &mut server,
            Ok(ExecStream {
                done: done_rx,
                output,
                overflowed: Arc::new(AtomicBool::new(false)),
                registration: test_registration(),
            }),
        )
        .await
        .unwrap();
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        assert_eq!(
            read_frame::<_, StreamFrame>(&mut client).await.unwrap(),
            StreamFrame::TimedOut
        );
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
    }

    async fn overflowed_frames(terminal: ExecTerminal) -> (Option<StreamFrame>, StreamFrame) {
        let (mut server, mut client) = duplex(64 * 1024);
        let (done_tx, done_rx) = oneshot::channel::<Result<ExecTerminal, WorkerError>>();
        let (out_tx, output) = mpsc::channel(16);
        done_tx.send(Ok(terminal)).unwrap();
        drop(out_tx);

        write_exec_result(
            &mut server,
            Ok(ExecStream {
                done: done_rx,
                output,
                overflowed: Arc::new(AtomicBool::new(true)),
                registration: test_registration(),
            }),
        )
        .await
        .unwrap();
        drop(server);

        let admit: DaemonResponse = read_frame(&mut client).await.unwrap();
        assert_eq!(admit, DaemonResponse::Ok);
        let first: StreamFrame = read_frame(&mut client).await.unwrap();
        let second: StreamFrame = read_frame(&mut client).await.unwrap();
        assert!(read_frame::<_, StreamFrame>(&mut client).await.is_err());
        (Some(first), second)
    }
}