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
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Owns the WSLc SDK session and containers on a single dedicated worker
//! thread.
//!
//! The WSLc SDK's `WslcSession` / `WslcContainer` / `WslcProcess` handles are
//! thread-affine and must all be created and used from one apartment. This
//! module confines every SDK call to a single long-lived worker thread that
//! joins the MTA for its whole lifetime; async pipe handlers dispatch typed
//! [`WorkerCommand`]s to it over a channel and await the reply.
//!
//! State-aware topology (decided): **one** shared `WslcSession` (the WSL2
//! utility VM, booted lazily on first provision and amortised across all
//! sandboxes) and a refcounted `sandbox_id -> container` map. The session is
//! released when the last container is deprovisioned and the idle timeout
//! elapses.
//!
//! Each phase drives the real WSLc SDK via the reusable steps in
//! [`mxc_sdk::wslc_common::container_steps`] and [`mxc_sdk::wslc_common::image`]: `provision`
//! ensures the session + resolves the image + creates a container with a
//! keepalive init process; `start` boots
//! it; `exec` runs a fresh `WslcCreateContainerProcess` to completion, streaming
//! its stdout/stderr live to the pipe handler via an [`OutputSink`]; `stop` /
//! `deprovision` stop + delete. The completion reply carries the exit code;
//! output flows over the sink. (Client `Stdin` forwarding is a later fill-in.)

use std::collections::{hash_map::Entry, HashMap};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;

use anyhow::Result;
use tokio::sync::mpsc::error::TrySendError;
use tokio::sync::{mpsc, oneshot};

use mxc_sdk::mxc_common::logger::{Logger, Mode};
use mxc_sdk::mxc_common::models::{FailurePhase, ScriptResponse};
use mxc_sdk::wslc_common::container_steps::{self, OutStream, OutputSink, ProcessSettings};
use mxc_sdk::wslc_common::daemon_protocol::{
    DeprovisionConfig, ErrKind, ExecConfig, ExecTerminal, NetworkMode, ProvisionConfig,
    StartConfig, StopConfig,
};
use mxc_sdk::wslc_common::image;
use mxc_sdk::wslc_common::policy_mapping;
use mxc_sdk::wslc_common::process_env::EnvScope;
use mxc_sdk::wslc_common::wslc_bindings::{
    WslcContainer, WslcContainerGuard, WslcContainerNetworkingMode, WslcSdk, WslcSessionGuard,
};

/// Fixed name of the single WSL2 utility-VM session the daemon owns.
const SESSION_NAME: &str = "mxc-wslc-daemon";

/// How long teardown waits for an abandoned pull before giving up on it.
const PULL_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);

/// Default on-disk WSLc image/session store. Matches the one-shot runner's
/// default so both surfaces read and fill the same cache.
fn default_storage_path() -> String {
    std::env::temp_dir()
        .join("mxc-wslc-sessions")
        .to_string_lossy()
        .to_string()
}

/// Convert a step helper's `failure_phase` into a typed failure, since the wire
/// carries only a message and an [`ErrKind`].
fn sr_err(resp: ScriptResponse) -> WorkerError {
    let err = anyhow::anyhow!(resp.error_message);
    match resp.failure_phase {
        FailurePhase::BackendUnavailable => WorkerError::Unavailable(err),
        FailurePhase::Rejected => WorkerError::Rejected(err),
        _ => WorkerError::Backend(err),
    }
}

/// A typed worker failure. The control server maps [`WorkerError::kind`] onto
/// the protocol's [`ErrKind`] so clients can react (e.g. distinguish an unknown
/// sandbox from a backend fault) without string-matching the message.
#[derive(Debug)]
pub enum WorkerError {
    /// The referenced sandbox id is unknown to the daemon.
    NotProvisioned(String),

    /// The sandbox exists but has not been started.
    NotStarted(String),

    /// The host cannot run WSLc at all.
    Unavailable(anyhow::Error),

    /// The request cannot be honored as written.
    Rejected(anyhow::Error),

    /// A backend/SDK-level failure, or an internal worker/channel fault.
    Backend(anyhow::Error),
}

impl WorkerError {
    /// The protocol classification the control server returns for this error.
    pub fn kind(&self) -> ErrKind {
        match self {
            WorkerError::NotProvisioned(_) => ErrKind::NotProvisioned,
            WorkerError::NotStarted(_) => ErrKind::NotStarted,
            WorkerError::Unavailable(_) => ErrKind::Unavailable,
            WorkerError::Rejected(_) => ErrKind::Rejected,
            WorkerError::Backend(_) => ErrKind::Backend,
        }
    }
}

impl std::fmt::Display for WorkerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WorkerError::NotProvisioned(id) => write!(f, "unknown sandbox {id}"),
            WorkerError::NotStarted(id) => write!(f, "sandbox {id} is not started"),
            WorkerError::Unavailable(e) | WorkerError::Rejected(e) | WorkerError::Backend(e) => {
                write!(f, "{e:#}")
            }
        }
    }
}

impl std::error::Error for WorkerError {}

impl From<anyhow::Error> for WorkerError {
    fn from(e: anyhow::Error) -> Self {
        WorkerError::Backend(e)
    }
}

/// A unit of work dispatched from an async pipe handler to the WSLc worker
/// thread. Each variant carries a `oneshot` reply channel the worker fulfils.
pub enum WorkerCommand {
    Provision {
        config: ProvisionConfig,
        reply: oneshot::Sender<Result<String, WorkerError>>,
    },
    Start {
        config: StartConfig,
        reply: oneshot::Sender<Result<(), WorkerError>>,
    },
    /// Validate the sandbox (exists + started) and, if admitted, run the
    /// command to completion. The two replies make admission **atomic** with the
    /// run: because the worker services this whole command on its single thread
    /// without yielding, no `Stop`/`Deprovision` can interleave between the
    /// validation and the run. `admit` carries the pre-run decision (so an
    /// unknown/not-started sandbox is a pre-admission typed error, never a
    /// post-admission stream `Error`); `done` carries the run's exit code.
    Exec {
        config: ExecConfig,
        /// Live-output sink the worker hands to `exec_in_container`; the SDK's
        /// stdout/stderr callbacks push chunks through it to the pipe handler as
        /// bytes arrive, alongside the capped capture buffers.
        sink: OutputSink,
        cancellation: Arc<AtomicBool>,
        registration: Arc<ExecRegistration>,
        admit: oneshot::Sender<Result<(), WorkerError>>,
        done: oneshot::Sender<Result<ExecTerminal, WorkerError>>,
    },
    Stop {
        config: StopConfig,
        reply: oneshot::Sender<Result<(), WorkerError>>,
    },
    Deprovision {
        config: DeprovisionConfig,
        reply: oneshot::Sender<Result<(), WorkerError>>,
    },
    /// Report a parked provision's pull, from the pull thread or its deadline.
    PullFinished {
        token: u64,
        outcome: Result<(), ScriptResponse>,
    },
    /// Give up on a sandbox whose provision reply never reached a client.
    Retire {
        sandbox_id: String,
        reply: oneshot::Sender<()>,
    },
    /// Report the current live-container count (drives the idle watchdog).
    ContainerCount { reply: oneshot::Sender<usize> },
    /// Release all containers + the session and stop the worker thread.
    Shutdown { reply: oneshot::Sender<()> },
}

/// A chunk of live process output streamed from the worker to the pipe handler:
/// which stream it came from and the bytes (owned, so it can cross the channel).
pub type OutputChunk = (OutStream, Vec<u8>);

/// Bound on the number of unconsumed live-output chunks buffered between the
/// SDK's I/O callback threads and the pipe handler. The channel is bounded (not
/// unbounded) so a container emitting output faster than a slow client drains it
/// cannot grow the queue without limit and OOM the persistent daemon, taking
/// down every sandbox it owns — the same hazard the capture-buffer cap guards
/// against. When the queue is full the sink does **not** block (see
/// [`enqueue_output`]): it latches a truncation flag and drops further bytes so
/// the SDK callback thread — which also delivers the process-exit callback — is
/// never parked. Stalling that thread could otherwise block exit delivery and
/// wedge teardown for every sandbox sharing the daemon.
const LIVE_OUTPUT_CHANNEL_CAPACITY: usize = 256;

/// Max bytes per enqueued live-output chunk. A single SDK callback can deliver
/// an arbitrarily large buffer; splitting it here bounds each queue entry's
/// allocation and keeps the resulting `Stdout`/`Stderr` frame well under the
/// protocol's `MAX_FRAME_SIZE` (a `Vec<u8>` serializes as a JSON number array,
/// ~4x expansion), so a large callback can never overflow a frame and abort the
/// stream before its terminal frame.
const LIVE_OUTPUT_MAX_CHUNK_BYTES: usize = 64 * 1024;

/// Enqueue an SDK output callback, splitting it into `LIVE_OUTPUT_MAX_CHUNK_BYTES`
/// pieces so each queue entry and its resulting frame stay bounded regardless of
/// the callback's buffer size.
///
/// This runs **synchronously on the SDK's I/O callback thread**, which also
/// delivers the process-exit callback. It must therefore never block: a
/// [`try_send`](mpsc::Sender::try_send) that finds the bounded queue full does
/// **not** apply backpressure (that would park this thread and could deadlock
/// exit delivery and teardown for every sandbox on the daemon). Instead it
/// latches `overflowed` and stops enqueuing; the pipe handler turns a latched
/// overflow into a terminal `Error` frame so the client sees an explicit
/// truncation rather than a silently short stream. Once latched, subsequent
/// callbacks return immediately so the client receives a clean truncated prefix
/// rather than a gapped stream. A closed receiver (client left / leak-path
/// `close()`) likewise stops enqueuing.
fn enqueue_output(
    tx: &mpsc::Sender<OutputChunk>,
    overflowed: &AtomicBool,
    kind: OutStream,
    bytes: &[u8],
) {
    if overflowed.load(Ordering::Relaxed) {
        return;
    }
    for chunk in bytes.chunks(LIVE_OUTPUT_MAX_CHUNK_BYTES) {
        match tx.try_send((kind, chunk.to_vec())) {
            Ok(()) => {}
            Err(TrySendError::Full(_)) => {
                overflowed.store(true, Ordering::Relaxed);
                return;
            }
            Err(TrySendError::Closed(_)) => return,
        }
    }
}

/// An admitted exec: the completion receiver (the run's exit code), the
/// live-output receiver the pipe handler drains into `Stdout`/`Stderr` frames,
/// and the `overflowed` latch the sink sets when it had to drop output because a
/// slow client let the bounded queue fill. The registration keeps the exec id
/// reserved until the pipe handler finishes terminal delivery. The pipe handler
/// reports a set overflow latch as a terminal `Error` frame.
#[derive(Debug)]
pub struct ExecStream {
    pub done: oneshot::Receiver<Result<ExecTerminal, WorkerError>>,
    pub output: mpsc::Receiver<OutputChunk>,
    pub overflowed: Arc<AtomicBool>,
    pub(crate) registration: Arc<ExecRegistration>,
}

pub(crate) type ActiveExecs = Arc<Mutex<HashMap<String, ActiveExec>>>;

#[derive(Debug)]
pub(crate) struct ActiveExec {
    run_token: String,
    cancellation: Weak<AtomicBool>,
}

#[derive(Debug)]
pub(crate) struct ExecRegistration {
    exec_id: String,
    run_token: String,
    active_execs: ActiveExecs,
    cancellation: Arc<AtomicBool>,
}

impl Drop for ExecRegistration {
    fn drop(&mut self) {
        let mut active_execs = self
            .active_execs
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if active_execs.get(&self.exec_id).is_some_and(|current| {
            current.run_token == self.run_token
                && current
                    .cancellation
                    .ptr_eq(&Arc::downgrade(&self.cancellation))
        }) {
            active_execs.remove(&self.exec_id);
        }
    }
}

pub(crate) fn register_exec(
    active_execs: &ActiveExecs,
    exec_id: &str,
    run_token: &str,
    cancellation: &Arc<AtomicBool>,
) -> Result<ExecRegistration, WorkerError> {
    let active_exec = ActiveExec {
        run_token: run_token.to_string(),
        cancellation: Arc::downgrade(cancellation),
    };
    let mut active_execs_guard = active_execs
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    match active_execs_guard.entry(exec_id.to_string()) {
        Entry::Occupied(mut entry) if entry.get().cancellation.upgrade().is_none() => {
            entry.insert(active_exec);
        }
        Entry::Occupied(_) => {
            return Err(WorkerError::Rejected(anyhow::anyhow!(
                "exec id {exec_id:?} is already active"
            )));
        }
        Entry::Vacant(entry) => {
            entry.insert(active_exec);
        }
    }
    drop(active_execs_guard);

    Ok(ExecRegistration {
        exec_id: exec_id.to_string(),
        run_token: run_token.to_string(),
        active_execs: Arc::clone(active_execs),
        cancellation: Arc::clone(cancellation),
    })
}

/// A cheap, clonable handle async tasks use to drive the worker thread.
#[derive(Clone)]
pub struct SessionHandle {
    tx: mpsc::UnboundedSender<WorkerCommand>,
    active_execs: ActiveExecs,
}

impl SessionHandle {
    /// Provision a container, returning its minted `sandbox_id`.
    pub async fn provision(&self, config: ProvisionConfig) -> Result<String, WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::Provision { config, reply })?;
        rx.await.map_err(worker_gone)?
    }

    /// Start a provisioned container.
    pub async fn start(&self, config: StartConfig) -> Result<(), WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::Start { config, reply })?;
        rx.await.map_err(worker_gone)?
    }

    /// Admit and run a command in a started container. Awaits the worker's
    /// **admission** decision first: on rejection (unknown/not-started sandbox)
    /// this returns the typed error *before* the caller writes any admission to
    /// the client. On admission it returns an [`ExecStream`] — the completion
    /// receiver (the run's exit code) plus the live-output receiver, which the
    /// caller drains into `Stdout`/`Stderr` frames as bytes arrive. Admission and
    /// the start of the run are atomic on the worker thread, so no lifecycle
    /// command can invalidate the checked state between the two.
    pub async fn exec(&self, config: ExecConfig) -> Result<ExecStream, WorkerError> {
        let (admit, admit_rx) = oneshot::channel();
        let (done, done_rx) = oneshot::channel();
        let (stream_tx, output) = mpsc::channel::<OutputChunk>(LIVE_OUTPUT_CHANNEL_CAPACITY);
        // The sink is invoked from the SDK's I/O callback threads (native OS
        // threads, never the async runtime). Those same threads deliver the
        // process-exit callback, so the sink must never block: [`enqueue_output`]
        // uses a non-blocking `try_send` and, on a full queue, latches
        // `overflowed` and drops further bytes instead of parking the thread.
        // Memory stays bounded by the channel capacity; a slow/non-reading
        // client can no longer wedge exit delivery or teardown for every sandbox
        // on the daemon. The pipe handler reports a set latch as a terminal
        // `Error` frame so truncation is explicit rather than silent.
        let overflowed = Arc::new(AtomicBool::new(false));
        let sink_overflowed = Arc::clone(&overflowed);
        let sink: OutputSink = Box::new(move |kind, bytes| {
            enqueue_output(&stream_tx, &sink_overflowed, kind, bytes);
        });
        let cancellation = Arc::new(AtomicBool::new(false));
        let registration = Arc::new(register_exec(
            &self.active_execs,
            &config.exec_id,
            &config.run_token,
            &cancellation,
        )?);
        self.send(WorkerCommand::Exec {
            config,
            sink,
            cancellation,
            registration: Arc::clone(&registration),
            admit,
            done,
        })?;
        admit_rx.await.map_err(worker_gone)??;
        Ok(ExecStream {
            done: done_rx,
            output,
            overflowed,
            registration,
        })
    }

    /// Signal an admitted exec without waiting for the apartment-affine worker,
    /// which is blocked in that exec until the process exits.
    pub fn cancel_exec(&self, exec_id: &str, run_token: &str) {
        if let Some(cancellation) = self
            .active_execs
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .get(exec_id)
            .filter(|current| current.run_token == run_token)
            .and_then(|current| current.cancellation.upgrade())
        {
            cancellation.store(true, Ordering::Release);
        }
    }

    /// Stop a running container.
    pub async fn stop(&self, config: StopConfig) -> Result<(), WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::Stop { config, reply })?;
        rx.await.map_err(worker_gone)?
    }

    /// Deprovision (delete) a container.
    pub async fn deprovision(&self, config: DeprovisionConfig) -> Result<(), WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::Deprovision { config, reply })?;
        rx.await.map_err(worker_gone)?
    }

    /// Current number of live containers (0 means the daemon is idle).
    pub async fn container_count(&self) -> Result<usize, WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::ContainerCount { reply })?;
        rx.await.map_err(worker_gone)
    }

    /// Stop counting a sandbox that no client can reach, so the idle watchdog
    /// can shut the daemon down.
    pub async fn retire(&self, sandbox_id: String) -> Result<(), WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::Retire { sandbox_id, reply })?;
        rx.await.map_err(worker_gone)
    }

    /// Ask the worker to release everything and stop. Awaits confirmation.
    pub async fn shutdown(&self) -> Result<(), WorkerError> {
        let (reply, rx) = oneshot::channel();
        self.send(WorkerCommand::Shutdown { reply })?;
        rx.await.map_err(worker_gone)
    }

    fn send(&self, cmd: WorkerCommand) -> Result<(), WorkerError> {
        self.tx
            .send(cmd)
            .map_err(|_| WorkerError::Backend(anyhow::anyhow!("WSLc worker thread is gone")))
    }
}

fn worker_gone(_e: oneshot::error::RecvError) -> WorkerError {
    WorkerError::Backend(anyhow::anyhow!("WSLc worker dropped the reply channel"))
}

/// Per-container bookkeeping held by the worker: whether the container is
/// currently started and the live `WslcContainer` handle (kept alive across
/// phases so repeated `exec`s hit a warm container). The sandbox id is the
/// map key.
struct ContainerEntry {
    started: bool,
    quarantined: bool,

    /// Set when a sandbox's provision reply never reached a client, so nobody
    /// can deprovision it.
    ///
    /// Kept in the map rather than dropped so [`Worker::shutdown`] still stops
    /// and deletes the container.
    retired: bool,
    container: WslcContainerGuard,
}

/// A provision waiting on its image to arrive from a registry.
struct PendingProvision {
    config: ProvisionConfig,
    reply: oneshot::Sender<Result<String, WorkerError>>,

    /// Held only so dropping this entry retires the deadline thread.
    _retire_deadline: std::sync::mpsc::Sender<()>,
}

/// The single-threaded WSLc session owner. Constructed and run entirely on the
/// worker thread. Holds the lazily-loaded SDK and the one shared session (the
/// WSL2 utility VM), plus the `sandbox_id -> container` map. The SDK/session/
/// guard handles are `!Send` raw pointers, but they never leave this thread —
/// only [`WorkerCommand`]s cross the channel.
struct Worker {
    logger: Logger,
    // Field order is load-bearing on implicit drop: `containers` and `session`
    // hold handles whose Drop calls into the SDK, so they must drop before `sdk`
    // unloads `wslcsdk.dll`.
    containers: HashMap<String, ContainerEntry>,
    pending: HashMap<u64, PendingProvision>,
    next_pull_token: u64,
    session: Option<WslcSessionGuard>,
    sdk: Option<WslcSdk>,
}

impl Worker {
    fn new() -> Self {
        Self {
            logger: Logger::new(Mode::Console),
            sdk: None,
            session: None,
            containers: HashMap::new(),
            pending: HashMap::new(),
            next_pull_token: 0,
        }
    }

    /// Lazily load the SDK and boot the shared session on first use. Idempotent.
    fn ensure_session(&mut self) -> Result<(), WorkerError> {
        if self.sdk.is_none() {
            // SAFETY: the worker thread is already in the MTA (see `ComApartment`).
            let sdk =
                unsafe { container_steps::load_sdk_checked(&mut self.logger) }.map_err(sr_err)?;
            self.sdk = Some(sdk);
        }
        if self.session.is_none() {
            let storage = default_storage_path();
            let sdk = self.sdk.as_ref().expect("sdk loaded above");
            // SAFETY: `sdk` holds valid pointers and COM is initialised.
            let session = unsafe {
                container_steps::create_daemon_session(
                    sdk,
                    SESSION_NAME,
                    &storage,
                    &mut self.logger,
                )
            }
            .map_err(sr_err)?;
            self.session = Some(session);
        }
        Ok(())
    }

    /// Start a provision, parking it if the image has to be pulled.
    ///
    /// Returning without replying is what keeps this thread free: the pull runs
    /// elsewhere and posts [`WorkerCommand::PullFinished`] when it lands, so
    /// every other sandbox keeps being served while a registry is slow.
    fn begin_provision(
        &mut self,
        config: ProvisionConfig,
        reply: oneshot::Sender<Result<String, WorkerError>>,
        worker: &mpsc::UnboundedSender<WorkerCommand>,
    ) {
        if let Err(e) = self.ensure_session() {
            let _ = reply.send(Err(e));
            return;
        }

        let sdk = self.sdk.as_ref().expect("session ensured");
        let session = self.session.as_ref().expect("session ensured").as_raw();

        // SAFETY: `sdk`/`session` are valid.
        let step = unsafe {
            image::begin_resolve(
                sdk,
                session,
                &config.image,
                config.image_tar_path.as_deref(),
                None,
                match config.network {
                    NetworkMode::None => image::RegistryAccess::Denied,
                    NetworkMode::Bridged => image::RegistryAccess::Allowed,
                },
                "[WSLC][daemon]",
                &mut self.logger,
            )
        };
        let step = match step {
            Ok(step) => step,
            Err(e) => {
                let _ = reply.send(Err(sr_err(e)));
                return;
            }
        };

        match step {
            image::ImageStep::Ready => {
                let _ = reply.send(self.create_provisioned_container(&config));
            }
            image::ImageStep::Pull => {
                let token = self.next_pull_token;
                self.next_pull_token += 1;

                let done = worker.clone();
                let started = unsafe {
                    image::start_pull(
                        sdk,
                        session,
                        &config.image,
                        None,
                        "[WSLC][daemon]",
                        move |outcome| {
                            let _ = done.send(WorkerCommand::PullFinished { token, outcome });
                        },
                    )
                };
                if let Err(e) = started {
                    let _ = reply.send(Err(sr_err(e)));
                    return;
                }

                // Nothing can stop a stalled pull from outside, so the deadline
                // is enforced by giving up on it rather than by ending it.
                let budget = image::daemon_pull_budget();
                let image_name = config.image.clone();
                let expired = worker.clone();
                let (retire_deadline, retired) = std::sync::mpsc::channel::<()>();
                let armed = std::thread::Builder::new()
                    .name("wslc-pull-deadline".to_string())
                    .spawn(move || {
                        // A pull that lands first drops the sender, so this
                        // returns rather than sleeping out the budget.
                        if retired.recv_timeout(budget)
                            != Err(std::sync::mpsc::RecvTimeoutError::Timeout)
                        {
                            return;
                        }
                        let _ = expired.send(WorkerCommand::PullFinished {
                            token,
                            outcome: Err(image::pull_deadline_expired(&image_name, budget)),
                        });
                    });

                if armed.is_err() {
                    // Parking without a deadline is how a provision waits
                    // forever, so refuse instead. The pull carries on and warms
                    // the cache for a retry.
                    let _ = reply.send(Err(WorkerError::Backend(anyhow::anyhow!(
                        "could not arm the pull deadline for image '{}'",
                        config.image
                    ))));
                    return;
                }

                self.pending.insert(
                    token,
                    PendingProvision {
                        config,
                        reply,
                        _retire_deadline: retire_deadline,
                    },
                );
            }
        }
    }

    /// Resume a parked provision once its pull reported, or its deadline did.
    ///
    /// An unknown token is the loser of that race, and has nothing left to do.
    fn finish_provision(&mut self, token: u64, outcome: Result<(), ScriptResponse>) {
        let Some(PendingProvision {
            config,
            reply,
            _retire_deadline: _,
        }) = self.pending.remove(&token)
        else {
            return;
        };

        if let Err(e) = outcome {
            let _ = reply.send(Err(sr_err(e)));
            return;
        }

        let sdk = self.sdk.as_ref().expect("session ensured");
        let session = self.session.as_ref().expect("session ensured").as_raw();

        // SAFETY: `sdk`/`session` are valid.
        if let Err(e) = unsafe {
            image::report_pulled_digest(
                sdk,
                session,
                &config.image,
                "[WSLC][daemon]",
                &mut self.logger,
            )
        } {
            let _ = reply.send(Err(sr_err(e)));
            return;
        }

        let _ = reply.send(self.create_provisioned_container(&config));
    }

    /// Everything after the image is in the store: create the container and
    /// register it under a fresh sandbox id.
    fn create_provisioned_container(
        &mut self,
        config: &ProvisionConfig,
    ) -> Result<String, WorkerError> {
        let sdk = self.sdk.as_ref().expect("session ensured");
        let session = self.session.as_ref().expect("session ensured").as_raw();

        let mounts: Vec<policy_mapping::VolumeMount> = config
            .volumes
            .iter()
            .map(|v| policy_mapping::VolumeMount {
                windows_path: v.host.clone(),
                container_path: v.container.clone(),
                read_only: v.read_only,
            })
            .collect();
        let net_mode = match config.network {
            NetworkMode::None => WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_NONE,
            NetworkMode::Bridged => {
                WslcContainerNetworkingMode::WSLC_CONTAINER_NETWORKING_MODE_BRIDGED
            }
        };

        // SAFETY: `sdk`/`session` are valid; every buffer the SDK stores pointers
        // into is owned by a stationary local (`keepalive`) until create returns.
        let container = unsafe {
            // Merge keeps the keepalive out of `env -i`, so a container whose
            // execs never replace an environment does not need `/usr/bin/env`
            // in its image.
            let mut keepalive = ProcessSettings::build_detached(
                sdk,
                container_steps::KEEPALIVE_SCRIPT,
                &[],
                EnvScope::Merge,
                "",
            )
            .map_err(sr_err)?;

            container_steps::create_daemon_container(
                sdk,
                session,
                &config.image,
                &mounts,
                net_mode,
                &mut keepalive,
                &mut self.logger,
            )
            .map_err(sr_err)?
        };

        let sandbox_id = format!("wslc:{}", uuid::Uuid::new_v4().simple());
        self.containers.insert(
            sandbox_id.clone(),
            ContainerEntry {
                started: false,
                quarantined: false,
                retired: false,
                container,
            },
        );
        Ok(sandbox_id)
    }

    fn start(&mut self, config: StartConfig) -> Result<(), WorkerError> {
        // Existence check first, so an unknown sandbox errors without needing the
        // SDK (keeps the no-WSL unit tests self-contained).
        if !self.containers.contains_key(&config.sandbox_id) {
            return Err(WorkerError::NotProvisioned(config.sandbox_id));
        }
        let sdk = self
            .sdk
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("no active WSLc session"))?;
        let entry = self
            .containers
            .get_mut(&config.sandbox_id)
            .expect("checked above");
        if entry.quarantined {
            return Err(WorkerError::Backend(anyhow::anyhow!(
                "sandbox {} is quarantined after an exec whose termination could not be \
                 confirmed; deprovision it before reuse",
                config.sandbox_id
            )));
        }
        // SAFETY: `sdk` is valid and `entry.container` is a live handle.
        unsafe {
            container_steps::start_daemon_container(sdk, entry.container.as_raw(), &mut self.logger)
        }
        .map_err(sr_err)?;
        entry.started = true;
        Ok(())
    }

    /// Validate that a sandbox exists and is started, returning the live handle
    /// needed to run. Sole owner of the exists+started invariant: [`exec`] trusts
    /// the handle it is given and never re-checks, because the worker services
    /// admission and the run on one thread without yielding between them.
    fn validate_exec(&self, sandbox_id: &str) -> Result<WslcContainer, WorkerError> {
        match self.containers.get(sandbox_id) {
            None => Err(WorkerError::NotProvisioned(sandbox_id.to_string())),
            Some(entry) if entry.quarantined => Err(WorkerError::Backend(anyhow::anyhow!(
                "sandbox {sandbox_id} is quarantined after an exec whose termination could not \
                 be confirmed; deprovision it before reuse"
            ))),
            Some(entry) if !entry.started => Err(WorkerError::NotStarted(sandbox_id.to_string())),
            Some(entry) => Ok(entry.container.as_raw()),
        }
    }

    /// Run a command in a sandbox whose existence/started state was already
    /// confirmed by [`validate_exec`]; `container` is that validated handle.
    /// `sink` streams the run's stdout/stderr live to the pipe handler.
    fn exec(
        &mut self,
        config: ExecConfig,
        container: WslcContainer,
        sink: OutputSink,
        cancellation: &AtomicBool,
    ) -> Result<ExecTerminal, WorkerError> {
        let sdk = self
            .sdk
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("no active WSLc session"))?;

        // ProcessSettings::build expects `NAME=VALUE` env entries.
        let env: Vec<String> = config
            .env
            .iter()
            .map(|(k, v)| format!("{}={}", k, v))
            .collect();

        // SAFETY: `sdk` is valid and `container` is a live, started handle.
        let outcome = unsafe {
            container_steps::exec_in_container(
                sdk,
                container,
                &config.script_code,
                &env,
                config.env_scope,
                &config.working_directory,
                config.timeout_ms,
                cancellation,
                Some(sink),
                &mut self.logger,
            )
        }
        .map_err(sr_err)?;

        match outcome.completion {
            container_steps::ProcessCompletion::TerminationUnconfirmed => {
                let detail = outcome
                    .post_launch_error
                    .map(|error| error.error_message)
                    .unwrap_or_else(|| "process termination could not be confirmed".to_string());
                Err(self.quarantine(&config.sandbox_id, container, &detail))
            }
            container_steps::ProcessCompletion::Confirmed(terminal) => Ok(terminal),
        }
    }

    fn quarantine(
        &mut self,
        sandbox_id: &str,
        container: WslcContainer,
        detail: &str,
    ) -> WorkerError {
        let delete_result = self.sdk.as_ref().map(|sdk| {
            // SAFETY: `sdk` is valid and `container` is the live handle stored
            // for `sandbox_id`.
            unsafe { container_steps::delete_daemon_container(sdk, container, &mut self.logger) }
        });

        match delete_result {
            Some(Ok(())) => {
                self.containers.remove(sandbox_id);
                WorkerError::Backend(anyhow::anyhow!(
                    "exec on sandbox {sandbox_id} could not be confirmed terminated ({detail}); \
                     the container was quarantined and deleted"
                ))
            }
            Some(Err(delete_error)) => {
                if let Some(entry) = self.containers.get_mut(sandbox_id) {
                    entry.quarantined = true;
                }
                WorkerError::Backend(anyhow::anyhow!(
                    "exec on sandbox {sandbox_id} could not be confirmed terminated ({detail}); \
                     quarantine deletion failed and the sandbox remains blocked until \
                     deprovision succeeds: {}",
                    delete_error.error_message
                ))
            }
            None => {
                if let Some(entry) = self.containers.get_mut(sandbox_id) {
                    entry.quarantined = true;
                }
                WorkerError::Backend(anyhow::anyhow!(
                    "exec on sandbox {sandbox_id} could not be confirmed terminated ({detail}); \
                     the sandbox remains quarantined because no active WSLc SDK is available"
                ))
            }
        }
    }

    fn stop(&mut self, config: StopConfig) -> Result<(), WorkerError> {
        if !self.containers.contains_key(&config.sandbox_id) {
            return Err(WorkerError::NotProvisioned(config.sandbox_id));
        }
        let sdk = self
            .sdk
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("no active WSLc session"))?;
        let entry = self
            .containers
            .get_mut(&config.sandbox_id)
            .expect("checked above");
        // SAFETY: `sdk` is valid and `entry.container` is a live handle.
        unsafe {
            container_steps::stop_daemon_container(sdk, entry.container.as_raw(), &mut self.logger)
        }
        .map_err(sr_err)?;
        entry.started = false;
        Ok(())
    }

    /// Stop counting a sandbox that no client can reach.
    fn retire(&mut self, sandbox_id: &str) {
        if let Some(entry) = self.containers.get_mut(sandbox_id) {
            entry.retired = true;
        }
    }

    /// Containers a client could still act on.
    ///
    /// Drives the idle watchdog, which shuts the daemon down only at zero. A
    /// parked provision has no container yet, so counting it keeps the daemon
    /// alive for the client still waiting on its pull.
    fn live_container_count(&self) -> usize {
        self.containers.values().filter(|e| !e.retired).count() + self.pending.len()
    }

    fn deprovision(&mut self, config: DeprovisionConfig) -> Result<(), WorkerError> {
        let container_raw = match self.containers.get(&config.sandbox_id) {
            Some(e) => e.container.as_raw(),
            None => return Err(WorkerError::NotProvisioned(config.sandbox_id)),
        };

        if let Some(sdk) = self.sdk.as_ref() {
            // SAFETY: `sdk` is valid and `container_raw` is a live handle.
            unsafe {
                container_steps::delete_daemon_container(sdk, container_raw, &mut self.logger)
            }
            .map_err(sr_err)?;
        }

        // Delete succeeded (or no SDK loaded): drop the handle now. Keeping the
        // entry on failure above leaves it retryable.
        self.containers.remove(&config.sandbox_id);

        // The shared session (and SDK) stay loaded so a subsequent provision
        // reuses the already-booted WSL2 VM. The idle watchdog releases them via
        // `shutdown` once the container count has stayed at zero for the idle
        // timeout.
        Ok(())
    }

    /// Release every container and the session.
    ///
    /// A parked provision is answered rather than dropped, since a dropped
    /// reply reaches its client as a bare "worker gone".
    fn shutdown(&mut self) {
        for (_, pending) in self.pending.drain() {
            let _ = pending.reply.send(Err(WorkerError::Backend(anyhow::anyhow!(
                "the WSLc daemon shut down while pulling image '{}'",
                pending.config.image
            ))));
        }

        if let Some(sdk) = self.sdk.as_ref() {
            for (_, entry) in self.containers.drain() {
                // SAFETY: `sdk` is valid and `entry.container` is a live handle.
                unsafe {
                    if entry.started {
                        let _ = container_steps::stop_daemon_container(
                            sdk,
                            entry.container.as_raw(),
                            &mut self.logger,
                        );
                    }
                    let _ = container_steps::delete_daemon_container(
                        sdk,
                        entry.container.as_raw(),
                        &mut self.logger,
                    );
                }
                // entry (WslcContainerGuard) drops here, releasing the handle.
            }
        } else {
            self.containers.clear();
        }

        // An abandoned pull is still using this session, so releasing it now
        // would free memory the SDK holds. The leaked handles cost one
        // process's worth of memory until it exits.
        if !image::wait_for_pulls_in_flight(PULL_DRAIN_TIMEOUT) {
            self.logger.log_line(
                "a WSLC image pull is still running; leaking the session rather than \
                 releasing a handle it is using",
            );
            std::mem::forget(self.session.take());
            std::mem::forget(self.sdk.take());
            return;
        }

        // Session guard drops before the SDK unloads the DLL.
        self.session = None;
        self.sdk = None;
    }
}

/// Spawn the WSLc worker thread and return a handle to it.
///
/// The thread joins the MTA for its entire lifetime (WSLc SDK apartment
/// affinity) and processes [`WorkerCommand`]s until a [`WorkerCommand::Shutdown`]
/// is received or the command channel closes.
pub fn spawn() -> Result<SessionHandle> {
    let (tx, mut rx) = mpsc::unbounded_channel::<WorkerCommand>();
    let active_execs = Arc::new(Mutex::new(HashMap::new()));

    // A parked provision resumes by posting back into this queue.
    let worker_tx = tx.clone();

    std::thread::Builder::new()
        .name("wslc-session-worker".to_string())
        .spawn(move || {
            #[cfg(windows)]
            let _com = match ComApartment::enter() {
                Ok(com) => com,
                Err(e) => {
                    eprintln!("[wslc-daemon] worker COM initialisation failed: {e:#}");
                    return;
                }
            };

            let mut worker = Worker::new();
            while let Some(cmd) = rx.blocking_recv() {
                match cmd {
                    WorkerCommand::Provision { config, reply } => {
                        worker.begin_provision(config, reply, &worker_tx);
                    }
                    WorkerCommand::PullFinished { token, outcome } => {
                        worker.finish_provision(token, outcome);
                    }
                    WorkerCommand::Start { config, reply } => {
                        let _ = reply.send(worker.start(config));
                    }
                    WorkerCommand::Exec {
                        config,
                        sink,
                        cancellation,
                        registration: _registration,
                        admit,
                        done,
                    } => {
                        // Validate and run in one handler so admission is atomic
                        // with the start of the run: the worker never yields
                        // between the two, so no Stop/Deprovision can interleave.
                        match worker.validate_exec(&config.sandbox_id) {
                            Err(e) => {
                                let _ = admit.send(Err(e));
                            }
                            Ok(_) if cancellation.load(Ordering::Acquire) => {
                                if admit.send(Ok(())).is_ok() {
                                    let _ = done.send(Ok(ExecTerminal::Cancelled));
                                }
                            }
                            // Only run if the admission receiver is still there:
                            // if the client handler was dropped before it read
                            // admission, the blocking exec would otherwise starve
                            // every other lifecycle command for its full timeout.
                            Ok(container) if admit.send(Ok(())).is_ok() => {
                                let sandbox_id = config.sandbox_id.clone();
                                let outcome = worker.exec(config, container, sink, &cancellation);
                                if let Err(orphaned) = done.send(outcome) {
                                    // The client handler is gone (e.g. its
                                    // post-admission Ok write failed) but the run
                                    // already happened. Record the result so a
                                    // completed exec is never silently lost.
                                    worker.logger.log_line(&format!(
                                        "exec on {sandbox_id} completed after the client \
                                         disconnected; orphaned result: {orphaned:?}"
                                    ));
                                }
                            }
                            Ok(_) => {}
                        }
                    }
                    WorkerCommand::Stop { config, reply } => {
                        let _ = reply.send(worker.stop(config));
                    }
                    WorkerCommand::Deprovision { config, reply } => {
                        let _ = reply.send(worker.deprovision(config));
                    }
                    WorkerCommand::Retire { sandbox_id, reply } => {
                        worker.retire(&sandbox_id);
                        let _ = reply.send(());
                    }
                    WorkerCommand::ContainerCount { reply } => {
                        let _ = reply.send(worker.live_container_count());
                    }
                    WorkerCommand::Shutdown { reply } => {
                        worker.shutdown();
                        let _ = reply.send(());
                        break;
                    }
                }
            }
        })
        .map_err(|e| anyhow::anyhow!("spawn WSLc worker thread: {e}"))?;

    Ok(SessionHandle { tx, active_execs })
}

/// RAII guard that keeps the calling thread in the COM MTA for the WSLc SDK.
#[cfg(windows)]
struct ComApartment;

#[cfg(windows)]
impl ComApartment {
    fn enter() -> Result<Self> {
        use windows::Win32::System::Com::{CoInitializeEx, COINIT_MULTITHREADED};
        // SAFETY: called once at worker-thread startup. On success the matching
        // `CoUninitialize` runs in `Drop`; on failure no guard is produced, so
        // `CoUninitialize` is never called for an apartment we did not enter.
        let hr = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
        if hr.is_err() {
            anyhow::bail!("CoInitializeEx(MTA) failed: {hr:?}");
        }
        Ok(Self)
    }
}

#[cfg(windows)]
impl Drop for ComApartment {
    fn drop(&mut self) {
        use windows::Win32::System::Com::CoUninitialize;
        // SAFETY: balances the CoInitializeEx in `enter`, on the same thread.
        unsafe {
            CoUninitialize();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    async fn count(handle: &SessionHandle) -> usize {
        handle.container_count().await.unwrap()
    }

    // ---- No-WSL unit tests (run everywhere, never touch the SDK) ----

    /// Build a worker entry around a handle that is never dereferenced.
    fn test_entry(retired: bool) -> ContainerEntry {
        unsafe extern "C" fn release_noop(
            _: mxc_sdk::wslc_common::wslc_bindings::WslcContainer,
        ) -> i32 {
            0
        }

        // Non-null only because the guard rejects null; the value is never used
        // as a pointer.
        let sentinel = std::ptr::dangling_mut();
        ContainerEntry {
            started: false,
            quarantined: false,
            retired,
            // SAFETY: `release_noop` never dereferences the handle, so the guard
            // owns a value it can release without touching memory.
            container: unsafe { WslcContainerGuard::from_raw(sentinel, release_noop) },
        }
    }

    /// A parked provision has no container yet, so the watchdog would retire
    /// the daemon out from under the client still waiting on its pull.
    /// A timer that outlived its pull would sit for the rest of the budget, so
    /// sequential cache misses would pile up sleeping threads.
    #[test]
    fn a_pull_that_lands_first_retires_its_deadline_thread() {
        let (retire_deadline, retired) = std::sync::mpsc::channel::<()>();
        let woke = std::thread::spawn(move || {
            retired.recv_timeout(Duration::from_secs(30))
                == Err(std::sync::mpsc::RecvTimeoutError::Disconnected)
        });

        drop(retire_deadline);

        assert!(
            woke.join().expect("timer thread"),
            "dropping the parked provision must wake its deadline immediately"
        );
    }

    #[test]
    fn a_pending_pull_keeps_the_daemon_alive() {
        let mut worker = Worker::new();
        assert_eq!(worker.live_container_count(), 0);

        let (reply, _rx) = oneshot::channel();
        worker.pending.insert(
            7,
            PendingProvision {
                config: ProvisionConfig {
                    image: "alpine:latest".to_string(),
                    image_tar_path: None,
                    volumes: Vec::new(),
                    network: Default::default(),
                },
                reply,
                _retire_deadline: std::sync::mpsc::channel().0,
            },
        );

        assert_eq!(
            worker.live_container_count(),
            1,
            "a provision still waiting on its image must hold the daemon open"
        );
    }

    /// The pull and its deadline race, and both report.
    #[test]
    fn only_the_first_report_of_a_pull_answers_the_client() {
        let mut worker = Worker::new();
        let (reply, mut rx) = oneshot::channel();
        worker.pending.insert(
            3,
            PendingProvision {
                config: ProvisionConfig {
                    image: "alpine:latest".to_string(),
                    image_tar_path: None,
                    volumes: Vec::new(),
                    network: Default::default(),
                },
                reply,
                _retire_deadline: std::sync::mpsc::channel().0,
            },
        );

        worker.finish_provision(
            3,
            Err(image::pull_deadline_expired(
                "alpine:latest",
                PULL_DRAIN_TIMEOUT,
            )),
        );
        assert!(rx.try_recv().is_ok(), "the first report answers the client");

        // The loser of the race: nothing left to answer, and no panic.
        worker.finish_provision(3, Ok(()));
        assert_eq!(worker.live_container_count(), 0);
    }

    #[test]
    fn a_retired_sandbox_stops_holding_the_daemon_open() {
        let mut worker = Worker::new();
        worker
            .containers
            .insert("wslc:orphan".to_string(), test_entry(false));
        assert_eq!(worker.live_container_count(), 1);

        worker.retire("wslc:orphan");

        assert_eq!(
            worker.live_container_count(),
            0,
            "a retired sandbox must not keep the daemon alive"
        );
        assert!(
            worker.containers.contains_key("wslc:orphan"),
            "the handle stays so shutdown can still delete the container"
        );
    }

    #[test]
    fn retiring_one_sandbox_leaves_the_others_counted() {
        let mut worker = Worker::new();
        worker
            .containers
            .insert("wslc:orphan".to_string(), test_entry(false));
        worker
            .containers
            .insert("wslc:live".to_string(), test_entry(false));

        worker.retire("wslc:orphan");

        assert_eq!(worker.live_container_count(), 1);
    }

    /// Retirement is driven by a failed release, which can name a sandbox that
    /// is already gone.
    #[test]
    fn retiring_an_unknown_sandbox_is_a_no_op() {
        let mut worker = Worker::new();
        worker.retire("wslc:never-existed");
        assert_eq!(worker.live_container_count(), 0);
    }

    #[test]
    fn sr_err_carries_the_step_failure_phase() {
        for (phase, expected) in [
            (FailurePhase::BackendUnavailable, ErrKind::Unavailable),
            (FailurePhase::Rejected, ErrKind::Rejected),
            (FailurePhase::LaunchFailed, ErrKind::Backend),
            (FailurePhase::PostLaunchFailed, ErrKind::Backend),
            (FailurePhase::None, ErrKind::Backend),
        ] {
            let resp = ScriptResponse {
                exit_code: -1,
                error_message: "boom".to_string(),
                failure_phase: phase.clone(),
                ..Default::default()
            };
            assert_eq!(sr_err(resp).kind(), expected, "phase {phase:?}");
        }
    }

    #[test]
    fn sr_err_preserves_the_step_message() {
        let resp = ScriptResponse {
            exit_code: -1,
            error_message: "WSLc components are missing".to_string(),
            failure_phase: FailurePhase::BackendUnavailable,
            ..Default::default()
        };
        assert_eq!(sr_err(resp).to_string(), "WSLc components are missing");
    }

    #[tokio::test]
    async fn start_unknown_sandbox_errors() {
        let handle = spawn().unwrap();
        let err = handle
            .start(StartConfig {
                sandbox_id: "wslc:does-not-exist".to_string(),
            })
            .await
            .unwrap_err();
        assert!(err.to_string().contains("unknown sandbox"));
        handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn exec_unknown_sandbox_errors() {
        let handle = spawn().unwrap();
        let err = handle
            .exec(ExecConfig {
                exec_id: "unknown-1".to_string(),
                run_token: "run-unknown-1".to_string(),
                sandbox_id: "wslc:does-not-exist".to_string(),
                script_code: "echo hi".to_string(),
                working_directory: String::new(),
                env: Vec::new(),
                env_scope: EnvScope::Merge,
                timeout_ms: 0,
            })
            .await
            .unwrap_err();
        assert!(err.to_string().contains("unknown sandbox"));
        handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn stop_unknown_sandbox_errors() {
        let handle = spawn().unwrap();
        let err = handle
            .stop(StopConfig {
                sandbox_id: "wslc:does-not-exist".to_string(),
            })
            .await
            .unwrap_err();
        assert!(err.to_string().contains("unknown sandbox"));
        handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn deprovision_unknown_sandbox_errors() {
        let handle = spawn().unwrap();
        let err = handle
            .deprovision(DeprovisionConfig {
                sandbox_id: "wslc:does-not-exist".to_string(),
            })
            .await
            .unwrap_err();
        assert!(err.to_string().contains("unknown sandbox"));
        assert_eq!(count(&handle).await, 0);
        handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn unknown_sandbox_maps_to_not_provisioned_kind() {
        let handle = spawn().unwrap();
        let err = handle
            .start(StartConfig {
                sandbox_id: "wslc:does-not-exist".to_string(),
            })
            .await
            .unwrap_err();
        assert_eq!(err.kind(), ErrKind::NotProvisioned);
        handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn exec_unknown_sandbox_admission_is_not_provisioned() {
        let handle = spawn().unwrap();
        let err = handle
            .exec(ExecConfig {
                exec_id: "unknown-2".to_string(),
                run_token: "run-unknown-2".to_string(),
                sandbox_id: "wslc:does-not-exist".to_string(),
                script_code: "echo hi".to_string(),
                working_directory: String::new(),
                env: Vec::new(),
                env_scope: EnvScope::Merge,
                timeout_ms: 0,
            })
            .await
            .unwrap_err();
        assert_eq!(err.kind(), ErrKind::NotProvisioned);
        handle.shutdown().await.unwrap();
    }

    #[test]
    fn cancel_exec_marks_the_registered_run() {
        let (tx, _rx) = mpsc::unbounded_channel();
        let cancellation = Arc::new(AtomicBool::new(false));
        let active_execs = Arc::new(Mutex::new(HashMap::from([(
            "exec-1".to_string(),
            ActiveExec {
                run_token: "run-1".to_string(),
                cancellation: Arc::downgrade(&cancellation),
            },
        )])));
        let handle = SessionHandle { tx, active_execs };

        handle.cancel_exec("exec-1", "run-1");

        assert!(cancellation.load(Ordering::Acquire));
    }

    #[test]
    fn delayed_cancellation_does_not_target_reused_exec_id() {
        let (tx, _rx) = mpsc::unbounded_channel();
        let cancellation = Arc::new(AtomicBool::new(false));
        let active_execs = Arc::new(Mutex::new(HashMap::new()));
        let registration =
            register_exec(&active_execs, "exec-1", "replacement-run", &cancellation).unwrap();
        let handle = SessionHandle { tx, active_execs };

        handle.cancel_exec("exec-1", "completed-run");
        assert!(!cancellation.load(Ordering::Acquire));

        handle.cancel_exec("exec-1", "replacement-run");
        assert!(cancellation.load(Ordering::Acquire));
        drop(registration);
    }

    #[test]
    fn duplicate_live_exec_id_is_rejected_without_replacing_registration() {
        let active_execs = Arc::new(Mutex::new(HashMap::new()));
        let first = Arc::new(AtomicBool::new(false));
        let second = Arc::new(AtomicBool::new(false));
        let registration = register_exec(&active_execs, "exec-1", "run-1", &first).unwrap();

        let error = register_exec(&active_execs, "exec-1", "run-2", &second).unwrap_err();

        assert_eq!(error.kind(), ErrKind::Rejected);
        let registered = active_execs
            .lock()
            .unwrap()
            .get("exec-1")
            .and_then(|entry| entry.cancellation.upgrade())
            .unwrap();
        assert!(Arc::ptr_eq(&registered, &first));
        drop(registration);
    }

    #[test]
    fn stale_exec_id_can_be_registered_again() {
        let stale = Arc::new(AtomicBool::new(false));
        let active_execs = Arc::new(Mutex::new(HashMap::from([(
            "exec-1".to_string(),
            ActiveExec {
                run_token: "stale-run".to_string(),
                cancellation: Arc::downgrade(&stale),
            },
        )])));
        drop(stale);
        let cancellation = Arc::new(AtomicBool::new(false));

        let registration =
            register_exec(&active_execs, "exec-1", "replacement-run", &cancellation).unwrap();

        let registered = active_execs
            .lock()
            .unwrap()
            .get("exec-1")
            .and_then(|entry| entry.cancellation.upgrade())
            .unwrap();
        assert!(Arc::ptr_eq(&registered, &cancellation));
        drop(registration);
        assert!(!active_execs.lock().unwrap().contains_key("exec-1"));
    }

    #[test]
    fn older_registration_does_not_remove_replacement() {
        let active_execs = Arc::new(Mutex::new(HashMap::new()));
        let first = Arc::new(AtomicBool::new(false));
        let first_registration = register_exec(&active_execs, "exec-1", "run-1", &first).unwrap();
        let second = Arc::new(AtomicBool::new(false));
        active_execs.lock().unwrap().insert(
            "exec-1".to_string(),
            ActiveExec {
                run_token: "run-2".to_string(),
                cancellation: Arc::downgrade(&second),
            },
        );

        drop(first_registration);

        let registered = active_execs
            .lock()
            .unwrap()
            .get("exec-1")
            .and_then(|entry| entry.cancellation.upgrade())
            .unwrap();
        assert!(Arc::ptr_eq(&registered, &second));
    }

    #[test]
    fn cancelling_unknown_or_stale_exec_id_is_a_no_op() {
        let (tx, _rx) = mpsc::unbounded_channel();
        let stale = Arc::new(AtomicBool::new(false));
        let active_execs = Arc::new(Mutex::new(HashMap::from([(
            "stale".to_string(),
            ActiveExec {
                run_token: "stale-run".to_string(),
                cancellation: Arc::downgrade(&stale),
            },
        )])));
        drop(stale);
        let handle = SessionHandle { tx, active_execs };

        handle.cancel_exec("unknown", "unknown-run");
        handle.cancel_exec("stale", "stale-run");
    }

    #[tokio::test]
    async fn large_callback_split_into_frame_safe_chunks() {
        use mxc_sdk::wslc_common::daemon_protocol::{encode_frame, StreamFrame, MAX_FRAME_SIZE};

        let (tx, mut rx) = mpsc::channel::<OutputChunk>(LIVE_OUTPUT_CHANNEL_CAPACITY);
        // A single callback far larger than one chunk (and, unsplit, larger than
        // one frame once number-array-encoded): must arrive as many bounded chunks.
        let payload = vec![b'x'; LIVE_OUTPUT_MAX_CHUNK_BYTES * 3 + 7];
        let producer = tokio::task::spawn_blocking({
            let payload = payload.clone();
            move || {
                let overflowed = AtomicBool::new(false);
                enqueue_output(&tx, &overflowed, OutStream::Stdout, &payload)
            }
        });

        let mut reassembled = Vec::new();
        let mut chunks = 0usize;
        while let Some((kind, data)) = rx.recv().await {
            assert_eq!(kind, OutStream::Stdout);
            assert!(data.len() <= LIVE_OUTPUT_MAX_CHUNK_BYTES);
            let encoded = encode_frame(&StreamFrame::Stdout { data: data.clone() }).unwrap();
            assert!(encoded.len() <= MAX_FRAME_SIZE);
            reassembled.extend_from_slice(&data);
            chunks += 1;
        }
        producer.await.unwrap();
        assert_eq!(reassembled, payload);
        assert!(
            chunks >= 4,
            "expected the callback to be split, got {chunks}"
        );
    }
    //
    // Exercises the real SDK path end to end: provision (boot VM + create
    // container) → start → exec → stop → deprovision → refcount back to 0. It
    // provisions with the default isolated posture, which refuses a registry
    // pull, so `alpine:latest` has to be in the daemon session cache already
    // (`%TEMP%\mxc-wslc-sessions`). It is `#[ignore]`d and run explicitly with
    // `cargo test -p wxc_wslc_daemon -- --ignored`.
    #[tokio::test]
    #[ignore = "requires a WSL2 host with alpine:latest already in the daemon session cache"]
    async fn full_lifecycle_on_wsl_host() {
        let handle = spawn().unwrap();
        assert_eq!(count(&handle).await, 0);

        let id = handle
            .provision(ProvisionConfig {
                image: "alpine:latest".to_string(),
                image_tar_path: None,
                volumes: Vec::new(),
                network: Default::default(),
            })
            .await
            .unwrap();
        assert_eq!(count(&handle).await, 1);

        handle
            .start(StartConfig {
                sandbox_id: id.clone(),
            })
            .await
            .unwrap();

        let mut exec = handle
            .exec(ExecConfig {
                exec_id: "full-lifecycle".to_string(),
                run_token: "full-lifecycle-run".to_string(),
                sandbox_id: id.clone(),
                script_code: "echo hi".to_string(),
                working_directory: String::new(),
                env: Vec::new(),
                env_scope: EnvScope::Merge,
                timeout_ms: 30_000,
            })
            .await
            .unwrap();
        // Drain the live output stream, then await the exit code.
        let mut stdout = Vec::new();
        while let Some((kind, data)) = exec.output.recv().await {
            if kind == OutStream::Stdout {
                stdout.extend_from_slice(&data);
            }
        }
        let code = exec.done.await.unwrap().unwrap();
        assert_eq!(code, ExecTerminal::Exited(0));
        assert_eq!(String::from_utf8_lossy(&stdout).trim(), "hi");

        handle
            .stop(StopConfig {
                sandbox_id: id.clone(),
            })
            .await
            .unwrap();

        handle
            .deprovision(DeprovisionConfig { sandbox_id: id })
            .await
            .unwrap();
        assert_eq!(count(&handle).await, 0);

        handle.shutdown().await.unwrap();
    }

    #[tokio::test]
    #[ignore = "requires a WSL2 host with alpine:latest already in the daemon session cache"]
    async fn cancelled_queued_exec_never_starts_process() {
        let handle = spawn().unwrap();
        let id = handle
            .provision(ProvisionConfig {
                image: "alpine:latest".to_string(),
                image_tar_path: None,
                volumes: Vec::new(),
                network: Default::default(),
            })
            .await
            .unwrap();
        handle
            .start(StartConfig {
                sandbox_id: id.clone(),
            })
            .await
            .unwrap();

        let blocker = handle
            .exec(ExecConfig {
                exec_id: "queue-blocker".to_string(),
                run_token: "queue-blocker-run".to_string(),
                sandbox_id: id.clone(),
                script_code: "sleep 2".to_string(),
                working_directory: String::new(),
                env: Vec::new(),
                env_scope: EnvScope::Merge,
                timeout_ms: 30_000,
            })
            .await
            .unwrap();

        let queued_handle = handle.clone();
        let queued_id = id.clone();
        let queued = tokio::spawn(async move {
            queued_handle
                .exec(ExecConfig {
                    exec_id: "cancelled-queued".to_string(),
                    run_token: "cancelled-queued-run".to_string(),
                    sandbox_id: queued_id,
                    script_code: "touch /tmp/mxc-cancelled-queued-marker".to_string(),
                    working_directory: String::new(),
                    env: Vec::new(),
                    env_scope: EnvScope::Merge,
                    timeout_ms: 30_000,
                })
                .await
        });

        for _ in 0..100 {
            if handle
                .active_execs
                .lock()
                .unwrap()
                .contains_key("cancelled-queued")
            {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert!(
            handle
                .active_execs
                .lock()
                .unwrap()
                .contains_key("cancelled-queued"),
            "queued exec was not registered"
        );
        handle.cancel_exec("cancelled-queued", "cancelled-queued-run");
        assert_eq!(
            blocker.done.await.unwrap().unwrap(),
            ExecTerminal::Exited(0)
        );

        let queued = queued.await.unwrap().unwrap();
        assert_eq!(queued.done.await.unwrap().unwrap(), ExecTerminal::Cancelled);

        let marker_check = handle
            .exec(ExecConfig {
                exec_id: "marker-check".to_string(),
                run_token: "marker-check-run".to_string(),
                sandbox_id: id.clone(),
                script_code: "test ! -e /tmp/mxc-cancelled-queued-marker".to_string(),
                working_directory: String::new(),
                env: Vec::new(),
                env_scope: EnvScope::Merge,
                timeout_ms: 30_000,
            })
            .await
            .unwrap();
        assert_eq!(
            marker_check.done.await.unwrap().unwrap(),
            ExecTerminal::Exited(0)
        );

        handle
            .stop(StopConfig {
                sandbox_id: id.clone(),
            })
            .await
            .unwrap();
        handle
            .deprovision(DeprovisionConfig { sandbox_id: id })
            .await
            .unwrap();
        handle.shutdown().await.unwrap();
    }
}