pelagos 0.24.0

Fast Linux container runtime — OCI-compatible, namespaces, cgroups v2, seccomp, networking, image management
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
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
//! Imperative runtime builtins for the Lisp interpreter.
//!
//! Registered only when the interpreter is created via
//! [`super::Interpreter::new_with_runtime`].  Not available in plain `Interpreter::new()`.
//!
//! # Available functions
//!
//! | Function | Signature | Description |
//! |----------|-----------|-------------|
//! | `container-start`    | `(svc-spec [:env list])` → ContainerHandle | Spawn a container immediately |
//! | `container-start-bg` | `(svc-spec [:env list])` → PendingContainer | Spawn in background; returns immediately |
//! | `container-join`     | `(pending)` → ContainerHandle | Block until background container is ready |
//! | `start`            | `(svc-spec [:needs list] [:env lambda])` → Future | Declare a lazy container start; nothing runs |
//! | `then`           | `(future lambda)` → Future | Compute a value from a future's resolved result |
//! | `then-all`       | `((list fut...) lambda)` → Future | Join multiple futures, then compute |
//! | `run`              | `((list fut...) [:parallel] [:max-parallel N])` → alist | Execute graph; serial or tier-parallel |
//! | `resolve`          | `(future)` → value | Execute a monadic chain depth-first |
//! | `await`            | `(future [:port P] [:timeout T])` → ContainerHandle | Await a single Container future |
//! | `container-stop`   | `(handle)` → `()` | Send SIGTERM to a container |
//! | `container-wait`   | `(handle)` → Int | Wait for a container to exit |
//! | `container-run`    | `(svc-spec)` → Int | Start + wait; returns exit code |
//! | `container-ip`     | `(handle)` → Str\|Nil | Primary IP of container |
//! | `container-status` | `(handle)` → Str | `"running"` or `"exited"` |
//! | `await-port`       | `(host port [timeout-secs])` → Bool | TCP connect loop |
//!
//! ## Executor model
//!
//! `start` returns a [`Value::Future`] — a pure description of work (the
//! service spec) with no side effects.  Two executors are provided:
//!
//! - **`run`** — static graph executor.  Accepts a list of *terminal* futures
//!   (the ones whose results you care about); transitive `:needs` dependencies
//!   are discovered automatically and executed in the correct order.  Pass
//!   `:parallel` to run independent futures within each tier concurrently.
//!   Use `:max-parallel N` to cap threads per tier.  Returns an alist of
//!   `(name . resolved-value)` pairs for the explicitly listed futures only.
//!
//! - **`resolve`** — dynamic (monadic) executor.  Executes a single future
//!   depth-first: resolves all upstreams recursively before calling transforms.
//!   If a `then` lambda returns a new Future, that Future is resolved too
//!   (monadic flatten).  Use this for chains where the next step is only known
//!   after the previous one resolves.

use std::io::Read;
use std::net::TcpStream;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

static FUTURE_ID: AtomicU64 = AtomicU64::new(1);

fn next_future_id() -> u64 {
    FUTURE_ID.fetch_add(1, Ordering::Relaxed)
}

use crate::compose::ServiceSpec;
use crate::container::{Command, Namespace, Stdio, Volume};
use crate::image;
use crate::network::NetworkMode;

use super::env::Env;
use super::value::{LispError, Value};

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Register all imperative runtime builtins into `env`.
///
/// Called by [`super::Interpreter::new_with_runtime`].
pub fn register_runtime_builtins(
    env: &Env,
    registry: Arc<Mutex<Vec<(String, i32)>>>,
    thread_registry: Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>,
    project: String,
    compose_dir: PathBuf,
) {
    let project = Rc::new(project);
    let compose_dir = Rc::new(compose_dir);

    // ── container-start ────────────────────────────────────────────────────
    // Immediately spawns a container and returns a ContainerHandle.
    // Optional :env applies a list of (KEY . value) pairs to the service env.
    {
        let registry = Arc::clone(&registry);
        let thread_registry = Arc::clone(&thread_registry);
        let project = Rc::clone(&project);
        let compose_dir = Rc::clone(&compose_dir);
        native(env, "container-start", move |args| {
            if args.is_empty() {
                return Err(LispError::new(
                    "container-start: expected (service-spec [:env list])",
                ));
            }
            let mut svc = extract_service_spec("container-start", &args[0])?;
            let mut i = 1;
            while i < args.len() {
                match &args[i] {
                    Value::Symbol(s) if s == ":env" => {
                        i += 1;
                        let env_list = args
                            .get(i)
                            .ok_or_else(|| LispError::new("container-start: :env requires a list"))?
                            .clone();
                        apply_inject_env(&mut svc, env_list, "container-start")?;
                        i += 1;
                    }
                    other => {
                        return Err(LispError::new(format!(
                            "container-start: unexpected argument: {}",
                            other
                        )))
                    }
                }
            }
            do_container_start(svc, &project, &compose_dir, &registry, &thread_registry)
        });
    }

    // ── container-start-bg ─────────────────────────────────────────────────
    // Spawns a container in a background thread and returns a PendingContainer
    // immediately.  Call (container-join pending) to block and get a handle.
    // Optional :env applies (KEY . value) pairs before spawning.
    {
        let registry = Arc::clone(&registry);
        let thread_registry = Arc::clone(&thread_registry);
        let project = Rc::clone(&project);
        let compose_dir = Rc::clone(&compose_dir);
        native(env, "container-start-bg", move |args| {
            if args.is_empty() {
                return Err(LispError::new(
                    "container-start-bg: expected (service-spec [:env list])",
                ));
            }
            let mut svc = extract_service_spec("container-start-bg", &args[0])?;
            let mut i = 1;
            while i < args.len() {
                match &args[i] {
                    Value::Symbol(s) if s == ":env" => {
                        i += 1;
                        let env_list = args
                            .get(i)
                            .ok_or_else(|| {
                                LispError::new("container-start-bg: :env requires a list")
                            })?
                            .clone();
                        apply_inject_env(&mut svc, env_list, "container-start-bg")?;
                        i += 1;
                    }
                    other => {
                        return Err(LispError::new(format!(
                            "container-start-bg: unexpected argument: {}",
                            other
                        )))
                    }
                }
            }
            let registry2 = Arc::clone(&registry);
            let thread_registry2 = Arc::clone(&thread_registry);
            let project_str = (*project).clone();
            let compose_dir_path = compose_dir.to_path_buf();
            let (tx, rx) = std::sync::mpsc::channel();
            std::thread::spawn(move || {
                let result = do_container_start_inner(
                    svc,
                    &project_str,
                    &compose_dir_path,
                    &registry2,
                    &thread_registry2,
                )
                .map(|r| (r.name, r.pid, r.ip))
                .map_err(|e| e.message);
                let _ = tx.send(result);
            });
            use crate::lisp::value::{PendingRx, Value as V};
            let pending: PendingRx = std::sync::Arc::new(std::sync::Mutex::new(Some(rx)));
            Ok(V::PendingContainer(pending))
        });
    }

    // ── container-join ─────────────────────────────────────────────────────
    // Blocks until a background container (from container-start-bg) finishes
    // starting and returns a ContainerHandle.  Errors if already joined.
    native(env, "container-join", |args| {
        if args.len() != 1 {
            return Err(LispError::new(
                "container-join: expected 1 argument (pending-container)",
            ));
        }
        match &args[0] {
            Value::PendingContainer(arc) => {
                let rx = arc
                    .lock()
                    .unwrap()
                    .take()
                    .ok_or_else(|| LispError::new("container-join: already joined"))?;
                let (name, pid, ip) = rx
                    .recv()
                    .map_err(|_| LispError::new("container-join: background thread panicked"))?
                    .map_err(LispError::new)?;
                Ok(Value::ContainerHandle {
                    name,
                    pid,
                    ip,
                    deps: vec![],
                })
            }
            other => Err(LispError::new(format!(
                "container-join: expected pending-container, got {}",
                other.type_name()
            ))),
        }
    });

    // ── start ─────────────────────────────────────────────
    // Returns a Future — nothing starts.  Keywords:
    //   :needs  (list fut...)   ordering dependencies
    //   :env    (lambda ...)    called with resolved :needs values; returns
    //                           a list of (key . value) env pairs to merge
    native(env, "start", |args| {
        if args.is_empty() {
            return Err(LispError::new(
                "start: expected (svc [:needs list] [:env lambda])",
            ));
        }
        let svc = extract_service_spec("start", &args[0])?;
        let mut after: Vec<Value> = Vec::new();
        let mut inject: Option<Box<Value>> = None;
        let mut i = 1;
        while i < args.len() {
            match &args[i] {
                Value::Symbol(s) if s == ":needs" => {
                    i += 1;
                    let deps = args
                        .get(i)
                        .ok_or_else(|| LispError::new("start: :needs requires a list"))?
                        .to_vec()
                        .map_err(|_| LispError::new("start: :needs requires a list"))?;
                    for dep in deps {
                        match &dep {
                            Value::Future { .. } => after.push(dep),
                            other => {
                                return Err(LispError::new(format!(
                                    "start: :needs requires futures, got {}",
                                    other.type_name()
                                )))
                            }
                        }
                    }
                    i += 1;
                }
                Value::Symbol(s) if s == ":env" => {
                    i += 1;
                    let f = args
                        .get(i)
                        .ok_or_else(|| LispError::new("start: :env requires a lambda"))?
                        .clone();
                    match &f {
                        Value::Lambda { .. } | Value::Native(_, _) => {}
                        other => {
                            return Err(LispError::new(format!(
                                "start: :env requires a lambda, got {}",
                                other.type_name()
                            )))
                        }
                    }
                    inject = Some(Box::new(f));
                    i += 1;
                }
                other => {
                    return Err(LispError::new(format!(
                        "start: unexpected argument: {}",
                        other
                    )))
                }
            }
        }
        use crate::lisp::value::FutureKind;
        Ok(Value::Future {
            id: next_future_id(),
            name: svc.name.clone(),
            kind: FutureKind::Container {
                spec: Box::new(svc),
                inject,
            },
            after,
        })
    });

    // ── then ───────────────────────────────────────────────────────────────
    // (then upstream-future (lambda (v) computed-value) [:name "label"])
    // Creates a Transform future whose resolved value is the result of
    // applying the lambda to the upstream future's resolved value.
    // The new future declares :needs the upstream automatically.
    //
    // The optional :name "label" argument overrides the auto-generated name
    // ("<upstream>-then").  define-then uses this to name the future after
    // the Lisp binding, so error messages reference the user's variable name.
    native(env, "then", |args| {
        if args.len() < 2 {
            return Err(LispError::new(
                "then: expected (future transform-lambda [:name string])",
            ));
        }
        let upstream_name = match &args[0] {
            Value::Future { name, .. } => name.clone(),
            other => {
                return Err(LispError::new(format!(
                    "then: expected future, got {}",
                    other.type_name()
                )))
            }
        };
        match &args[1] {
            Value::Lambda { .. } | Value::Native(_, _) => {}
            other => {
                return Err(LispError::new(format!(
                    "then: expected lambda, got {}",
                    other.type_name()
                )))
            }
        }
        // Optional :name override.
        let name = if args.len() >= 4 {
            match (&args[2], &args[3]) {
                (Value::Symbol(k), Value::Str(n)) if k == ":name" => n.clone(),
                _ => format!("{}-then", upstream_name),
            }
        } else {
            format!("{}-then", upstream_name)
        };
        use crate::lisp::value::FutureKind;
        let upstream = args[0].clone();
        Ok(Value::Future {
            id: next_future_id(),
            name,
            kind: FutureKind::Transform {
                upstream: Box::new(upstream.clone()),
                transform: Box::new(args[1].clone()),
            },
            after: vec![upstream],
        })
    });

    // ── then-all ───────────────────────────────────────────────────────────
    // (then-all (list f1 f2 ...) (lambda (v1 v2 ...) result))
    // Creates a Join future: waits for all listed futures, then calls the
    // lambda with all their resolved values in order.  If the lambda returns
    // a Future it is flattened automatically (same rule as then).
    native(env, "then-all", |args| {
        if args.len() != 2 {
            return Err(LispError::new(
                "then-all: expected (list-of-futures lambda)",
            ));
        }
        let futures_list = args[0]
            .to_vec()
            .map_err(|_| LispError::new("then-all: first argument must be a list of futures"))?;
        let mut upstreams: Vec<Value> = Vec::new();
        let mut name_parts: Vec<String> = Vec::new();
        for f in futures_list {
            match &f {
                Value::Future { name, .. } => {
                    name_parts.push(name.clone());
                    upstreams.push(f);
                }
                other => {
                    return Err(LispError::new(format!(
                        "then-all: expected futures in list, got {}",
                        other.type_name()
                    )))
                }
            }
        }
        match &args[1] {
            Value::Lambda { .. } | Value::Native(_, _) => {}
            other => {
                return Err(LispError::new(format!(
                    "then-all: expected lambda, got {}",
                    other.type_name()
                )))
            }
        }
        use crate::lisp::value::FutureKind;
        Ok(Value::Future {
            id: next_future_id(),
            name: format!("join({})", name_parts.join(",")),
            kind: FutureKind::Join {
                transform: Box::new(args[1].clone()),
            },
            after: upstreams,
        })
    });

    // ── run ────────────────────────────────────────────────────────────
    // Graph-aware executor.  Topologically sorts futures by :needs, produces
    // tiers of independent futures, then executes serially or (with :parallel)
    // spawns threads for Container futures within each tier.
    //
    // Syntax:
    //   (run futures-list)                    ; serial (default)
    //   (run futures-list :parallel)           ; parallel tiers
    //   (run futures-list :parallel :max-parallel N) ; parallel, ≤N at once
    //   (run futures-list :max-parallel N)    ; :max-parallel implies :parallel
    //
    // Transform/Join futures always execute on the main thread (lambdas capture
    // Rc values which are !Send).  Only the raw container-spawn step runs in
    // worker threads; their results are converted to ContainerHandles on return.
    //
    // Deps not in the list are treated as already satisfied (resolved externally).
    {
        let registry = Arc::clone(&registry);
        let thread_registry = Arc::clone(&thread_registry);
        let project = Rc::clone(&project);
        let compose_dir = Rc::clone(&compose_dir);
        native(env, "run", move |args| {
            if args.is_empty() {
                return Err(LispError::new(
                    "run: expected (futures-list [:parallel] [:max-parallel N])",
                ));
            }
            let future_list = args[0]
                .to_vec()
                .map_err(|_| LispError::new("run: argument must be a list of futures"))?;

            // Parse optional keywords.
            let mut parallel = false;
            let mut max_parallel: Option<usize> = None;
            let mut ki = 1;
            while ki < args.len() {
                match &args[ki] {
                    Value::Symbol(s) if s == ":parallel" => {
                        parallel = true;
                        ki += 1;
                    }
                    Value::Symbol(s) if s == ":max-parallel" => {
                        ki += 1;
                        match args.get(ki) {
                            Some(Value::Int(n)) if *n > 0 => {
                                max_parallel = Some(*n as usize);
                                parallel = true;
                            }
                            _ => {
                                return Err(LispError::new(
                                    "run: :max-parallel requires a positive integer",
                                ))
                            }
                        }
                        ki += 1;
                    }
                    other => {
                        return Err(LispError::new(format!(
                            "run: unexpected argument: {}",
                            other
                        )))
                    }
                }
            }

            use super::eval::eval_apply;
            use crate::lisp::value::FutureKind;

            struct Entry {
                id: u64,
                kind: FutureKind,
                /// Dependency IDs extracted from the `after: Vec<Value>` field.
                after_ids: Vec<u64>,
            }

            // Validate the explicitly listed items up front.
            for v in &future_list {
                if !matches!(v, Value::Future { .. }) {
                    return Err(LispError::new(format!(
                        "run: expected futures, got {}",
                        v.type_name()
                    )));
                }
            }

            // Walk :needs transitively so the caller only needs to list terminal
            // futures; the full dependency graph is discovered automatically.
            fn collect_transitive(
                v: &Value,
                seen: &mut std::collections::HashSet<u64>,
                all: &mut Vec<Value>,
            ) {
                if let Value::Future { id, after, .. } = v {
                    if seen.insert(*id) {
                        for dep in after {
                            collect_transitive(dep, seen, all);
                        }
                        all.push(v.clone());
                    }
                }
            }

            let mut all_futures: Vec<Value> = Vec::new();
            let mut seen_ids: std::collections::HashSet<u64> = std::collections::HashSet::new();
            for v in &future_list {
                collect_transitive(v, &mut seen_ids, &mut all_futures);
            }

            let mut entries: Vec<Entry> = Vec::new();
            for v in all_futures {
                if let Value::Future {
                    id,
                    name,
                    kind,
                    after,
                } = v
                {
                    let after_ids = after.iter().filter_map(Value::future_id).collect();
                    entries.push(Entry {
                        id,
                        kind,
                        after_ids,
                    });
                    let _ = name; // name lives on the Value::Future; not needed in Entry
                }
            }

            // Tier-aware Kahn's topological sort.
            // Each tier contains futures that are independent of each other and
            // depend only on futures in earlier tiers — exactly the set that can
            // be dispatched in parallel.
            let n = entries.len();
            let id_to_idx: std::collections::HashMap<u64, usize> =
                entries.iter().enumerate().map(|(i, e)| (e.id, i)).collect();
            let mut in_degree = vec![0usize; n];
            let mut dependents: Vec<Vec<usize>> = vec![vec![]; n];
            for (i, e) in entries.iter().enumerate() {
                for dep_id in &e.after_ids {
                    if let Some(&dep_idx) = id_to_idx.get(dep_id) {
                        in_degree[i] += 1;
                        dependents[dep_idx].push(i);
                    }
                }
            }
            let mut ready: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
            let mut tiers: Vec<Vec<usize>> = Vec::new();
            while !ready.is_empty() {
                let tier = std::mem::take(&mut ready);
                for &i in &tier {
                    for &j in &dependents[i] {
                        in_degree[j] -= 1;
                        if in_degree[j] == 0 {
                            ready.push(j);
                        }
                    }
                }
                tiers.push(tier);
            }
            if tiers.iter().map(|t| t.len()).sum::<usize>() != n {
                return Err(LispError::new("run: dependency cycle detected"));
            }

            // Execution position of each future (tier * n + slot) — used to
            // compute reverse topological order for dep teardown lists.
            let exec_pos: std::collections::HashMap<u64, usize> = tiers
                .iter()
                .flatten()
                .enumerate()
                .map(|(pos, &idx)| (entries[idx].id, pos))
                .collect();

            // Execute tiers; track resolved values for inject/transform.
            let mut resolved: std::collections::HashMap<u64, Value> =
                std::collections::HashMap::new();

            if !parallel {
                // ── Serial path ──────────────────────────────────────────────
                // Identical to the previous implementation; tiers flatten to the
                // same deterministic topo order.
                for tier in &tiers {
                    for &idx in tier {
                        let e = &entries[idx];
                        let result = match &e.kind {
                            FutureKind::Container { spec, inject } => {
                                let mut spec = *spec.clone();
                                if let Some(inject_fn) = inject {
                                    let dep_vals: Vec<Value> = e
                                        .after_ids
                                        .iter()
                                        .map(|id| resolved.get(id).cloned().unwrap_or(Value::Nil))
                                        .collect();
                                    let env_list = eval_apply(inject_fn, &dep_vals)?;
                                    apply_inject_env(&mut spec, env_list, "run")?;
                                }
                                do_container_start(
                                    spec,
                                    &project,
                                    &compose_dir,
                                    &registry,
                                    &thread_registry,
                                )?
                            }
                            FutureKind::Transform {
                                upstream,
                                transform,
                            } => {
                                let upstream_id = upstream.future_id().unwrap_or(0);
                                let upstream_val =
                                    resolved.get(&upstream_id).cloned().unwrap_or(Value::Nil);
                                let result = eval_apply(transform, &[upstream_val])?;
                                // Monadic flatten: if the lambda returns a Future (conditional
                                // branch), resolve it dynamically so already-computed values
                                // are shared and not re-executed.  This is the bridge between
                                // static and dynamic execution.
                                match result {
                                    Value::Future { .. } => resolve_dynamic(
                                        result,
                                        &mut resolved,
                                        &project,
                                        &compose_dir,
                                        &registry,
                                        &thread_registry,
                                    )?,
                                    other => other,
                                }
                            }
                            FutureKind::Join { transform } => {
                                let upstream_vals: Vec<Value> = e
                                    .after_ids
                                    .iter()
                                    .map(|id| resolved.get(id).cloned().unwrap_or(Value::Nil))
                                    .collect();
                                let result = eval_apply(transform, &upstream_vals)?;
                                match result {
                                    Value::Future { .. } => resolve_dynamic(
                                        result,
                                        &mut resolved,
                                        &project,
                                        &compose_dir,
                                        &registry,
                                        &thread_registry,
                                    )?,
                                    other => other,
                                }
                            }
                        };
                        resolved.insert(e.id, result);
                    }
                }
            } else {
                // ── Parallel path ────────────────────────────────────────────
                // For each tier:
                //   Phase 1 (main thread): evaluate all lambdas (inject, transform,
                //     join).  Lambdas capture Rc values so they must stay on the
                //     main thread.  Container futures with inject produce a prepared
                //     ServiceSpec; Transform/Join futures produce their result directly.
                //   Phase 2 (worker threads): spawn prepared Container futures in
                //     parallel, at most max_parallel at a time.  Each thread gets
                //     owned data (ServiceSpec, String, PathBuf, Arc<Mutex<...>>).
                //   Results are merged in declaration order for a deterministic alist.

                let chunk_size = max_parallel.unwrap_or(0); // 0 = all at once

                for tier in &tiers {
                    let mut tier_results: Vec<(usize, Value)> = Vec::new();
                    let mut container_jobs: Vec<(usize, ServiceSpec)> = Vec::new();

                    // Phase 1: evaluate lambdas on main thread.
                    for &idx in tier {
                        let e = &entries[idx];
                        match &e.kind {
                            FutureKind::Container { spec, inject } => {
                                let mut spec = *spec.clone();
                                if let Some(inject_fn) = inject {
                                    let dep_vals: Vec<Value> = e
                                        .after_ids
                                        .iter()
                                        .map(|id| resolved.get(id).cloned().unwrap_or(Value::Nil))
                                        .collect();
                                    let env_list = eval_apply(inject_fn, &dep_vals)?;
                                    apply_inject_env(&mut spec, env_list, "run")?;
                                }
                                container_jobs.push((idx, spec));
                            }
                            FutureKind::Transform {
                                upstream,
                                transform,
                            } => {
                                let upstream_id = upstream.future_id().unwrap_or(0);
                                let upstream_val =
                                    resolved.get(&upstream_id).cloned().unwrap_or(Value::Nil);
                                let result = eval_apply(transform, &[upstream_val])?;
                                let result = match result {
                                    Value::Future { .. } => resolve_dynamic(
                                        result,
                                        &mut resolved,
                                        &project,
                                        &compose_dir,
                                        &registry,
                                        &thread_registry,
                                    )?,
                                    other => other,
                                };
                                tier_results.push((idx, result));
                            }
                            FutureKind::Join { transform } => {
                                let upstream_vals: Vec<Value> = e
                                    .after_ids
                                    .iter()
                                    .map(|id| resolved.get(id).cloned().unwrap_or(Value::Nil))
                                    .collect();
                                let result = eval_apply(transform, &upstream_vals)?;
                                let result = match result {
                                    Value::Future { .. } => resolve_dynamic(
                                        result,
                                        &mut resolved,
                                        &project,
                                        &compose_dir,
                                        &registry,
                                        &thread_registry,
                                    )?,
                                    other => other,
                                };
                                tier_results.push((idx, result));
                            }
                        }
                    }

                    // Phase 2: spawn container threads.
                    // Use one big chunk (fully parallel) unless max_parallel is set.
                    let effective_chunk = if chunk_size == 0 {
                        container_jobs.len().max(1)
                    } else {
                        chunk_size
                    };
                    for chunk in container_jobs.chunks(effective_chunk) {
                        let mut handles: Vec<(
                            usize,
                            std::thread::JoinHandle<Result<SpawnResult, LispError>>,
                        )> = Vec::new();

                        for (idx, spec) in chunk {
                            let idx = *idx;
                            let spec = spec.clone();
                            let project_owned = (*project).clone();
                            let compose_dir_owned = (*compose_dir).clone();
                            let registry_arc = Arc::clone(&registry);
                            let thread_registry_arc = Arc::clone(&thread_registry);
                            let handle = std::thread::spawn(move || {
                                do_container_start_inner(
                                    spec,
                                    &project_owned,
                                    &compose_dir_owned,
                                    &registry_arc,
                                    &thread_registry_arc,
                                )
                            });
                            handles.push((idx, handle));
                        }

                        for (idx, handle) in handles {
                            match handle.join() {
                                Ok(Ok(r)) => {
                                    let val = Value::ContainerHandle {
                                        name: r.name,
                                        pid: r.pid,
                                        ip: r.ip,
                                        deps: vec![],
                                    };
                                    tier_results.push((idx, val));
                                }
                                Ok(Err(e)) => return Err(e),
                                Err(_) => {
                                    return Err(LispError::new("run: a worker thread panicked"))
                                }
                            }
                        }
                    }

                    // Merge tier results in declaration order (deterministic alist).
                    tier_results.sort_by_key(|(idx, _)| *idx);
                    for (idx, val) in tier_results {
                        resolved.insert(entries[idx].id, val);
                    }
                }
            }

            // ── Post-execution: build output alist with deps ──────────────
            //
            // For each terminal Container future, collect its transitive
            // container dependencies in reverse execution order and attach
            // them as `deps` on the handle.  Transform/Join futures resolve
            // to plain values and carry no deps.
            //
            // "Transitive container deps" means: walk :needs recursively,
            // keep only nodes whose kind is Container, sort in reverse
            // execution order (latest-started first → stopped first).

            fn container_deps(
                id: u64,
                entries: &[Entry],
                id_to_idx: &std::collections::HashMap<u64, usize>,
                exec_pos: &std::collections::HashMap<u64, usize>,
                resolved: &std::collections::HashMap<u64, Value>,
            ) -> Vec<Value> {
                let mut visited: std::collections::HashSet<u64> = std::collections::HashSet::new();
                let mut stack = vec![id];
                let mut dep_ids: Vec<u64> = Vec::new();
                while let Some(cur) = stack.pop() {
                    if !visited.insert(cur) {
                        continue;
                    }
                    if let Some(&idx) = id_to_idx.get(&cur) {
                        for &dep_id in &entries[idx].after_ids {
                            stack.push(dep_id);
                        }
                        // Collect Container futures only (not self, not Transform/Join).
                        if cur != id {
                            if let Some(e) = id_to_idx
                                .get(&cur)
                                .map(|&i| &entries[i])
                                .filter(|e| matches!(e.kind, FutureKind::Container { .. }))
                            {
                                if resolved.contains_key(&e.id) {
                                    dep_ids.push(e.id);
                                }
                            }
                        }
                    }
                }
                // Reverse execution order: latest started is stopped first.
                dep_ids
                    .sort_by_key(|did| std::cmp::Reverse(exec_pos.get(did).copied().unwrap_or(0)));
                dep_ids
                    .into_iter()
                    .filter_map(|did| resolved.get(&did).cloned())
                    .collect()
            }

            let mut pairs: Vec<Value> = Vec::new();
            for v in &future_list {
                if let Value::Future { id, name, kind, .. } = v {
                    if let Some(resolved_val) = resolved.get(id) {
                        let final_val = if matches!(kind, FutureKind::Container { .. }) {
                            let deps =
                                container_deps(*id, &entries, &id_to_idx, &exec_pos, &resolved);
                            // Rebuild the handle with deps populated.
                            match resolved_val {
                                Value::ContainerHandle { name, pid, ip, .. } => {
                                    Value::ContainerHandle {
                                        name: name.clone(),
                                        pid: *pid,
                                        ip: ip.clone(),
                                        deps,
                                    }
                                }
                                other => other.clone(),
                            }
                        } else {
                            resolved_val.clone()
                        };
                        pairs.push(Value::Pair(Rc::new((Value::Str(name.clone()), final_val))));
                    }
                }
            }

            Ok(Value::list(pairs.into_iter()))
        });
    }

    // ── resolve ────────────────────────────────────────────────────────────
    // Dynamic (monadic) executor.  Resolves a single future chain recursively:
    //
    //   1. Container future   → spawn the container, return ContainerHandle.
    //   2. Transform future   → resolve the upstream first, then call the
    //      lambda.  If the lambda returns *another* Future, resolve that too
    //      (monadic flatten / Promise chaining).  Repeat until a non-Future
    //      value is produced.
    //
    // Unlike run-all, the full graph need not be declared upfront: the graph
    // emerges as lambdas execute.  Trade-off: no upfront cycle detection and
    // no tier-based parallel dispatch.  Use run via run when the full graph is
    // known; use resolve for linear pipelines or when the next step depends
    // on the runtime value of the previous one.
    {
        let registry = Arc::clone(&registry);
        let thread_registry = Arc::clone(&thread_registry);
        let project = Rc::clone(&project);
        let compose_dir = Rc::clone(&compose_dir);
        native(env, "resolve", move |args| {
            if args.len() != 1 {
                return Err(LispError::new("resolve: expected (future)"));
            }
            match &args[0] {
                Value::Future { .. } => {}
                other => {
                    return Err(LispError::new(format!(
                        "resolve: expected future, got {}",
                        other.type_name()
                    )))
                }
            }
            let mut resolved = std::collections::HashMap::new();
            resolve_dynamic(
                args[0].clone(),
                &mut resolved,
                &project,
                &compose_dir,
                &registry,
                &thread_registry,
            )
        });
    }

    // ── await ──────────────────────────────────────────────────────────────
    // Single-future serial executor.  Runs a Container future to completion,
    // optionally waiting for a TCP port.  Keywords: :port <int>, :timeout <num>.
    // Transform futures are not supported by await (use run-all or resolve).
    {
        let registry = Arc::clone(&registry);
        let thread_registry = Arc::clone(&thread_registry);
        let project = Rc::clone(&project);
        let compose_dir = Rc::clone(&compose_dir);
        native(env, "await", move |args| {
            if args.is_empty() {
                return Err(LispError::new(
                    "await: expected (future [:port P] [:timeout T])",
                ));
            }
            use crate::lisp::value::FutureKind;
            let svc = match &args[0] {
                Value::Future {
                    kind: FutureKind::Container { spec, .. },
                    ..
                } => *spec.clone(),
                Value::Future {
                    kind: FutureKind::Transform { .. } | FutureKind::Join { .. },
                    ..
                } => {
                    return Err(LispError::new(
                        "await: Transform and Join futures must be executed via run or resolve",
                    ))
                }
                other => {
                    return Err(LispError::new(format!(
                        "await: expected future, got {}",
                        other.type_name()
                    )))
                }
            };

            let mut port: Option<u16> = None;
            let mut timeout_secs = 60.0f64;
            let mut i = 1;
            while i < args.len() {
                match &args[i] {
                    Value::Symbol(s) if s == ":port" => {
                        i += 1;
                        port = Some(match args.get(i) {
                            Some(Value::Int(n)) => *n as u16,
                            _ => return Err(LispError::new("await: :port requires an integer")),
                        });
                        i += 1;
                    }
                    Value::Symbol(s) if s == ":timeout" => {
                        i += 1;
                        timeout_secs = match args.get(i) {
                            Some(Value::Int(n)) => *n as f64,
                            Some(Value::Float(f)) => *f,
                            _ => return Err(LispError::new("await: :timeout requires a number")),
                        };
                        i += 1;
                    }
                    other => {
                        return Err(LispError::new(format!(
                            "await: unexpected argument: {}",
                            other
                        )))
                    }
                }
            }

            let handle =
                do_container_start(svc, &project, &compose_dir, &registry, &thread_registry)?;

            if let Some(p) = port {
                let ip = match &handle {
                    Value::ContainerHandle { ip: Some(ip), .. } => ip.clone(),
                    _ => "127.0.0.1".to_string(),
                };
                let container_name = match &handle {
                    Value::ContainerHandle { name, .. } => name.clone(),
                    _ => "unknown".to_string(),
                };
                let addr = format!("{}:{}", ip, p);
                let deadline = Instant::now() + Duration::from_secs_f64(timeout_secs);
                loop {
                    if TcpStream::connect_timeout(
                        &addr.parse().map_err(|e| {
                            LispError::new(format!("await: invalid address '{}': {}", addr, e))
                        })?,
                        Duration::from_millis(250),
                    )
                    .is_ok()
                    {
                        break;
                    }
                    if Instant::now() >= deadline {
                        return Err(LispError::new(format!(
                            "await: '{}' port {} did not open within {}s",
                            container_name, p, timeout_secs
                        )));
                    }
                    std::thread::sleep(Duration::from_millis(250));
                }
            }

            Ok(handle)
        });
    }

    // ── container-stop ─────────────────────────────────────────────────────
    // Stops the container and cascades through its deps in reverse topo order.
    {
        let registry = Arc::clone(&registry);
        native(env, "container-stop", move |args| {
            if args.len() != 1 {
                return Err(LispError::new(
                    "container-stop: expected 1 argument (container-handle)",
                ));
            }
            stop_cascade(&args[0], &registry)?;
            Ok(Value::Nil)
        });
    }

    // ── container-wait ─────────────────────────────────────────────────────
    // Polls kill(pid, 0) until the process is gone, returns exit code (0),
    // then cascades container-stop through deps in reverse topo order.
    {
        let registry = Arc::clone(&registry);
        native(env, "container-wait", move |args| {
            if args.len() != 1 {
                return Err(LispError::new(
                    "container-wait: expected 1 argument (container-handle)",
                ));
            }
            let (_, pid) = extract_handle("container-wait", &args[0])?;
            loop {
                match nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None) {
                    Err(nix::errno::Errno::ESRCH) => break,
                    Err(_) => break,
                    Ok(()) => std::thread::sleep(Duration::from_millis(100)),
                }
            }
            // Deregister the waited container (it exited naturally) and cascade
            // stop through its deps in reverse topo order.
            if let Value::ContainerHandle { name, deps, .. } = &args[0] {
                registry.lock().unwrap().retain(|(n, _)| n != name);
                for dep in deps {
                    stop_cascade(dep, &registry)?;
                }
            }
            Ok(Value::Int(0))
        });
    }

    // ── container-run ──────────────────────────────────────────────────────
    {
        let registry = Arc::clone(&registry);
        let thread_registry = Arc::clone(&thread_registry);
        let project = Rc::clone(&project);
        let compose_dir = Rc::clone(&compose_dir);
        native(env, "container-run", move |args| {
            if args.len() != 1 {
                return Err(LispError::new(
                    "container-run: expected 1 argument (service-spec)",
                ));
            }
            let svc = extract_service_spec("container-run", &args[0])?;
            let handle =
                do_container_start(svc, &project, &compose_dir, &registry, &thread_registry)?;
            let (name, pid) = extract_handle("container-run", &handle)?;
            // Wait for process to exit.
            loop {
                match nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None) {
                    Err(nix::errno::Errno::ESRCH) => break,
                    _ => std::thread::sleep(Duration::from_millis(100)),
                }
            }
            registry.lock().unwrap().retain(|(n, _)| n != &name);
            Ok(Value::Int(0))
        });
    }

    // ── container-ip ───────────────────────────────────────────────────────
    native(env, "container-ip", |args| {
        if args.len() != 1 {
            return Err(LispError::new(
                "container-ip: expected 1 argument (container-handle)",
            ));
        }
        match &args[0] {
            Value::ContainerHandle { ip, .. } => match ip {
                Some(s) => Ok(Value::Str(s.clone())),
                None => Ok(Value::Nil),
            },
            a => Err(LispError::new(format!(
                "container-ip: expected container, got {}",
                a.type_name()
            ))),
        }
    });

    // ── container-status ───────────────────────────────────────────────────
    native(env, "container-status", |args| {
        if args.len() != 1 {
            return Err(LispError::new(
                "container-status: expected 1 argument (container-handle)",
            ));
        }
        let (_, pid) = extract_handle("container-status", &args[0])?;
        let alive = nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid), None).is_ok();
        Ok(Value::Str(if alive { "running" } else { "exited" }.into()))
    });

    // ── await-port ─────────────────────────────────────────────────────────
    native(env, "await-port", |args| {
        if args.len() < 2 || args.len() > 3 {
            return Err(LispError::new(
                "await-port: expected (host port [timeout-secs])",
            ));
        }
        let host = match &args[0] {
            Value::Str(s) => s.clone(),
            a => {
                return Err(LispError::new(format!(
                    "await-port: expected string host, got {}",
                    a.type_name()
                )))
            }
        };
        let port = match &args[1] {
            Value::Int(n) => *n as u16,
            a => {
                return Err(LispError::new(format!(
                    "await-port: expected integer port, got {}",
                    a.type_name()
                )))
            }
        };
        let timeout_secs = if args.len() == 3 {
            match &args[2] {
                Value::Int(n) => *n as f64,
                Value::Float(f) => *f,
                a => {
                    return Err(LispError::new(format!(
                        "await-port: expected number timeout, got {}",
                        a.type_name()
                    )))
                }
            }
        } else {
            60.0
        };

        let addr = format!("{}:{}", host, port);
        let deadline = Instant::now() + Duration::from_secs_f64(timeout_secs);
        loop {
            if TcpStream::connect_timeout(
                &addr.parse().map_err(|e| {
                    LispError::new(format!("await-port: invalid address '{}': {}", addr, e))
                })?,
                Duration::from_millis(250),
            )
            .is_ok()
            {
                return Ok(Value::Bool(true));
            }
            if Instant::now() >= deadline {
                return Ok(Value::Bool(false));
            }
            std::thread::sleep(Duration::from_millis(250));
        }
    });
}

// ---------------------------------------------------------------------------
// Dynamic executor
// ---------------------------------------------------------------------------

/// Recursively resolve `future` using a work-list deduplication map.
///
/// - Container futures spawn a container and return its [`Value::ContainerHandle`].
/// - Transform futures resolve their upstream first, then apply the lambda.
///   If the lambda returns another `Future`, that future is resolved too
///   (monadic flatten): this is what enables Promise-style chain syntax where
///   `(then ...)` lambdas return further `(container-start-async ...)` calls.
/// - Plain (non-Future) values are returned as-is.
///
/// The `resolved` map acts as a memo table: a future whose ID is already in
/// the map is not executed again, enabling shared upstreams without redundant
/// work.
fn resolve_dynamic(
    future: Value,
    resolved: &mut std::collections::HashMap<u64, Value>,
    project: &str,
    compose_dir: &std::path::Path,
    registry: &Arc<Mutex<Vec<(String, i32)>>>,
    thread_registry: &Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>,
) -> Result<Value, LispError> {
    use super::eval::eval_apply;
    use crate::lisp::value::FutureKind;

    match future {
        Value::Future {
            id, kind, after, ..
        } => {
            // Deduplication: if already resolved, return cached value.
            if let Some(cached) = resolved.get(&id) {
                return Ok(cached.clone());
            }

            // Resolve :needs deps first (needed for :env).
            let mut after_vals: Vec<Value> = Vec::new();
            for dep_fut in after {
                let val = resolve_dynamic(
                    dep_fut,
                    resolved,
                    project,
                    compose_dir,
                    registry,
                    thread_registry,
                )?;
                after_vals.push(val);
            }

            let result = match kind {
                FutureKind::Container { spec, inject } => {
                    let mut spec = *spec;
                    if let Some(inj) = inject {
                        let env_list = eval_apply(&inj, &after_vals)?;
                        apply_inject_env(&mut spec, env_list, "resolve")?;
                    }
                    do_container_start(spec, project, compose_dir, registry, thread_registry)?
                }
                FutureKind::Transform {
                    upstream,
                    transform,
                } => {
                    let upstream_val = resolve_dynamic(
                        *upstream,
                        resolved,
                        project,
                        compose_dir,
                        registry,
                        thread_registry,
                    )?;
                    let result = eval_apply(&transform, &[upstream_val])?;
                    // Monadic flatten: lambda may return a Future — resolve it.
                    match result {
                        Value::Future { .. } => resolve_dynamic(
                            result,
                            resolved,
                            project,
                            compose_dir,
                            registry,
                            thread_registry,
                        )?,
                        other => other,
                    }
                }
                FutureKind::Join { transform } => {
                    // after_vals holds resolved values for all upstreams in order.
                    let result = eval_apply(&transform, &after_vals)?;
                    match result {
                        Value::Future { .. } => resolve_dynamic(
                            result,
                            resolved,
                            project,
                            compose_dir,
                            registry,
                            thread_registry,
                        )?,
                        other => other,
                    }
                }
            };

            resolved.insert(id, result.clone());
            Ok(result)
        }
        // Plain value — already resolved, return as-is.
        other => Ok(other),
    }
}

// ---------------------------------------------------------------------------
// Core container-start logic
// ---------------------------------------------------------------------------

/// Thread-safe result of spawning a container.
///
/// Unlike [`Value::ContainerHandle`], this struct is `Send` (no `Rc` fields),
/// so it can be returned from worker threads in the parallel executor.
struct SpawnResult {
    name: String,
    pid: i32,
    ip: Option<String>,
}

/// Spawn a container and return a [`Value::ContainerHandle`].
///
/// This is a thin wrapper around [`do_container_start_inner`] for callers on
/// the main thread that need a `Value` directly.
fn do_container_start(
    svc: ServiceSpec,
    project: &str,
    compose_dir: &std::path::Path,
    registry: &Arc<Mutex<Vec<(String, i32)>>>,
    thread_registry: &Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>,
) -> Result<Value, LispError> {
    let r = do_container_start_inner(svc, project, compose_dir, registry, thread_registry)?;
    Ok(Value::ContainerHandle {
        name: r.name,
        pid: r.pid,
        ip: r.ip,
        deps: vec![],
    })
}

/// Core container spawn logic.  Returns a [`SpawnResult`] that is `Send`,
/// enabling use from worker threads in the parallel executor.
fn do_container_start_inner(
    svc: ServiceSpec,
    project: &str,
    compose_dir: &std::path::Path,
    registry: &Arc<Mutex<Vec<(String, i32)>>>,
    thread_registry: &Arc<Mutex<Vec<std::thread::JoinHandle<()>>>>,
) -> Result<SpawnResult, LispError> {
    // Resolve image.
    let image_ref = &svc.image;
    let (_, manifest) = resolve_image(image_ref)?;
    let layers = image::layer_dirs(&manifest);
    if layers.is_empty() {
        return Err(LispError::new(format!(
            "container-start: service '{}': image has no layers",
            svc.name
        )));
    }
    let layer_dirs = layers.clone();

    // Determine command.
    let exe_and_args = if let Some(ref cmd) = svc.command {
        cmd.clone()
    } else {
        let mut cmd_vec = manifest.config.entrypoint.clone();
        cmd_vec.extend(manifest.config.cmd.clone());
        if cmd_vec.is_empty() {
            vec!["/bin/sh".to_string()]
        } else {
            cmd_vec
        }
    };
    let exe = &exe_and_args[0];
    let rest = &exe_and_args[1..];
    let container_name = format!("{}-{}", project, svc.name);

    let mut cmd = Command::new(exe).args(rest).with_image_layers(layers);

    // Apply image config env.
    for env_str in &manifest.config.env {
        if let Some((k, v)) = env_str.split_once('=') {
            cmd = cmd.env(k, v);
        }
    }

    // Apply image config workdir.
    if !manifest.config.working_dir.is_empty() && svc.workdir.is_none() {
        cmd = cmd.with_cwd(&manifest.config.working_dir);
    }

    // Apply image config user as default.
    if svc.user.is_none() && !manifest.config.user.is_empty() {
        if let Ok((uid, gid)) = parse_user_in_layers(&manifest.config.user, &layer_dirs) {
            cmd = cmd.with_uid(uid);
            if let Some(g) = gid {
                cmd = cmd.with_gid(g);
            }
        }
    }

    // Networks: service declares them; scope to project.
    let svc_network_names: Vec<String> = svc
        .networks
        .iter()
        .map(|n| scoped_network_name(project, n))
        .collect();

    // Ensure each network exists — create on demand, same as volumes.
    for net_name in &svc_network_names {
        crate::network::ensure_network(net_name).map_err(|e| {
            LispError::new(format!(
                "container-start: failed to ensure network '{}': {}",
                net_name, e
            ))
        })?;
    }

    if let Some(primary) = svc_network_names.first() {
        cmd = cmd.with_network(NetworkMode::BridgeNamed(primary.clone()));
    }
    for additional in svc_network_names.iter().skip(1) {
        cmd = cmd.with_additional_network(additional);
    }

    // NAT for internet access.
    if !svc_network_names.is_empty() {
        cmd = cmd.with_nat();
    }

    // Volumes.
    for vol in &svc.volumes {
        let scoped = format!("{}-{}", project, vol.name);
        let v = Volume::open(&scoped)
            .or_else(|_| Volume::create(&scoped))
            .map_err(|e| LispError::new(format!("container-start: volume '{}': {}", scoped, e)))?;
        cmd = cmd.with_volume(&v, &vol.mount_path);
    }

    // Bind mounts.
    for bm in &svc.bind_mounts {
        let host = if std::path::Path::new(&bm.host_path).is_relative() {
            compose_dir
                .join(&bm.host_path)
                .canonicalize()
                .map_err(|e| {
                    LispError::new(format!(
                        "container-start: bind-mount host path '{}': {}",
                        bm.host_path, e
                    ))
                })?
                .to_string_lossy()
                .into_owned()
        } else {
            bm.host_path.clone()
        };
        if bm.read_only {
            cmd = cmd.with_bind_mount_ro(&host, &bm.container_path);
        } else {
            cmd = cmd.with_bind_mount(&host, &bm.container_path);
        }
    }

    // tmpfs mounts.
    for path in &svc.tmpfs_mounts {
        cmd = cmd.with_tmpfs(path, "");
    }

    // Environment variables.
    for (k, v) in &svc.env {
        cmd = cmd.env(k, v);
    }
    let image_sets_path = manifest.config.env.iter().any(|e| e.starts_with("PATH="));
    if !image_sets_path {
        cmd = cmd.env(
            "PATH",
            "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
        );
    }

    // Port forwards.
    for port in &svc.ports {
        cmd = cmd.with_port_forward(port.host, port.container);
    }

    // Resource limits.
    if let Some(ref mem) = svc.memory {
        if let Ok(bytes) = parse_memory(mem) {
            cmd = cmd.with_cgroup_memory(bytes);
        }
    }
    if let Some(ref cpus) = svc.cpus {
        if let Ok((quota, period)) = parse_cpus(cpus) {
            cmd = cmd.with_cgroup_cpu_quota(quota, period);
        }
    }

    // User override.
    if let Some(ref u) = svc.user {
        if let Ok((uid, gid)) = parse_user_in_layers(u, &layer_dirs) {
            cmd = cmd.with_uid(uid);
            if let Some(g) = gid {
                cmd = cmd.with_gid(g);
            }
        }
    }

    // Workdir override.
    if let Some(ref w) = svc.workdir {
        cmd = cmd.with_cwd(w);
    }

    // ── Container hardening ──────────────────────────────────────────────────
    //
    // Applied last so we OR with any namespace flags already accumulated (e.g.
    // MOUNT from with_image_layers, NET from Loopback mode).

    // Namespaces: PID isolates the process tree so orphaned sub-processes
    // (e.g. postgres workers) are killed by the kernel when PID 1 exits.
    // UTS gives each container its own hostname; IPC isolates SysV/POSIX IPC.
    let ns = cmd.namespaces();
    cmd = cmd
        .with_namespaces(ns | Namespace::PID | Namespace::UTS | Namespace::IPC)
        .with_hostname(&container_name);

    // Security: seccomp + capabilities + no-new-privileges + masked paths.
    //
    // Start from DEFAULT_CAPS, apply (cap-drop ...) then (cap-add ...).
    // (cap-drop "ALL") zeros the baseline before any cap-add is applied.
    {
        use crate::container::Capability;
        let drop_all = svc.cap_drop.iter().any(|c| c.eq_ignore_ascii_case("ALL"));
        let mut effective = if drop_all {
            Capability::empty()
        } else {
            Capability::DEFAULT_CAPS
        };
        if !drop_all {
            for name in &svc.cap_drop {
                let n = name.to_uppercase().replace('-', "_");
                let n = n.trim_start_matches("CAP_");
                match Capability::from_name(n) {
                    Some(cap) => effective &= !cap,
                    None => log::warn!("cap-drop: unknown capability '{}' — skipping", name),
                }
            }
        }
        for name in &svc.cap_add {
            let n = name.to_uppercase().replace('-', "_");
            let n = n.trim_start_matches("CAP_");
            match Capability::from_name(n) {
                Some(cap) => effective |= cap,
                None => log::warn!("cap-add: unknown capability '{}' — skipping", name),
            }
        }
        cmd = cmd
            .with_seccomp_default()
            .with_capabilities(effective)
            .with_no_new_privileges(true)
            .with_masked_paths_default();
    }

    // Spawn with log capture.
    cmd = cmd
        .stdin(Stdio::Null)
        .stdout(Stdio::Piped)
        .stderr(Stdio::Piped);

    let mut child = cmd.spawn().map_err(|e| {
        LispError::new(format!(
            "container-start: spawn '{}' failed: {}",
            svc.name, e
        ))
    })?;

    let pid = child.pid();
    let ip = child.container_ip();

    // Register DNS entries.
    let all_ips: Vec<(String, String)> = child
        .container_ips()
        .into_iter()
        .map(|(name, ip)| (name.to_string(), ip))
        .collect();

    for (net_name, ip_str) in &all_ips {
        let ip_addr: std::net::Ipv4Addr = match ip_str.parse() {
            Ok(ip) => ip,
            Err(_) => continue,
        };
        let net_def = match crate::network::load_network_def(net_name) {
            Ok(d) => d,
            Err(_) => continue,
        };
        if let Err(e) = crate::dns::dns_add_entry(
            net_name,
            &svc.name,
            ip_addr,
            net_def.gateway,
            &["8.8.8.8".to_string(), "1.1.1.1".to_string()],
        ) {
            log::warn!(
                "container-start: dns: failed to register '{}' on {}: {}",
                svc.name,
                net_name,
                e
            );
        }
    }

    // Spawn log sink threads (discard output — no log files in imperative mode).
    let mut stdout_handle = child.take_stdout();
    let mut stderr_handle = child.take_stderr();
    let svc_name_log = svc.name.clone();

    let t_stdout = std::thread::spawn(move || {
        if let Some(mut src) = stdout_handle.take() {
            let mut buf = [0u8; 4096];
            while matches!(src.read(&mut buf), Ok(n) if n > 0) {}
        }
    });

    let t_stderr = std::thread::spawn(move || {
        if let Some(mut src) = stderr_handle.take() {
            let mut buf = [0u8; 4096];
            while matches!(src.read(&mut buf), Ok(n) if n > 0) {}
        }
    });

    // Spawn waiter that cleans up DNS when the container exits.
    let all_ips_wait = all_ips.clone();
    let t_waiter = std::thread::spawn(move || {
        let _ = child.wait();
        for (net_name, _) in &all_ips_wait {
            let _ = crate::dns::dns_remove_entry(net_name, &svc_name_log);
        }
    });

    // Register the waiter thread so Drop can join it before calling exit().
    // The waiter calls dns_remove_entry (which writes log messages), so we
    // must ensure it finishes before exit() flushes stderr.
    //
    // The log-sink threads (t_stdout, t_stderr) are intentionally NOT joined:
    // they block on read() until the container's write-end of the pipe closes,
    // which may not happen if the container forked children that inherited the
    // fd (e.g. postgres autovacuum workers that outlive the postmaster after
    // SIGKILL).  Since the log sinks never write to stderr they cannot cause
    // glibc's IO-lock deadlock; glibc's own _exit() will kill them at the end.
    drop(t_stdout);
    drop(t_stderr);
    thread_registry.lock().unwrap().push(t_waiter);

    // Register in interpreter's cleanup registry.
    registry.lock().unwrap().push((container_name.clone(), pid));

    log::info!(
        "container-start: '{}' started (pid {}, ip {:?})",
        container_name,
        pid,
        ip
    );

    Ok(SpawnResult {
        name: container_name,
        pid,
        ip,
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Apply an `(inject ...)` result — a list of `(key . value)` pairs — to a
/// `ServiceSpec`'s env map.  Used in both the serial and parallel executor
/// paths to avoid duplicating the pair-parsing logic.
fn apply_inject_env(
    spec: &mut ServiceSpec,
    env_list: Value,
    caller: &str,
) -> Result<(), LispError> {
    for pair in env_list.to_vec()? {
        match pair {
            Value::Pair(p) => {
                let k = match &p.0 {
                    Value::Str(s) => s.clone(),
                    Value::Symbol(s) => s.clone(),
                    other => {
                        return Err(LispError::new(format!(
                            "{}: inject env key must be string, got {}",
                            caller,
                            other.type_name()
                        )))
                    }
                };
                let v = match &p.1 {
                    Value::Str(s) => s.clone(),
                    other => format!("{}", other),
                };
                spec.env.insert(k, v);
            }
            other => {
                return Err(LispError::new(format!(
                    "{}: inject must return (key . value) pairs, got {}",
                    caller,
                    other.type_name()
                )))
            }
        }
    }
    Ok(())
}

/// Stop a container and cascade through its `deps` in order.
///
/// Used by both `container-stop` and `container-wait` to implement
/// topology-aware teardown: stopping a terminal container automatically
/// stops everything it depended on, in reverse topological order.
fn stop_cascade(
    handle: &Value,
    registry: &Arc<Mutex<Vec<(String, i32)>>>,
) -> Result<(), LispError> {
    match handle {
        Value::ContainerHandle {
            name, pid, deps, ..
        } => {
            let _ = nix::sys::signal::kill(
                nix::unistd::Pid::from_raw(*pid),
                nix::sys::signal::Signal::SIGTERM,
            );
            registry.lock().unwrap().retain(|(n, _)| n != name);
            for dep in deps {
                stop_cascade(dep, registry)?;
            }
            Ok(())
        }
        other => Err(LispError::new(format!(
            "container-stop: expected container handle, got {}",
            other.type_name()
        ))),
    }
}

/// Register a native function closure into `env`.
fn native<F>(env: &Env, name: &str, f: F)
where
    F: Fn(&[Value]) -> Result<Value, LispError> + 'static,
{
    use super::value::NativeFn;
    env.borrow_mut().define(
        name,
        Value::Native(name.to_string(), Rc::new(f) as NativeFn),
    );
}

fn extract_service_spec(fn_name: &str, v: &Value) -> Result<ServiceSpec, LispError> {
    match v {
        Value::ServiceSpec(s) => Ok(*s.clone()),
        other => Err(LispError::new(format!(
            "{}: expected service-spec, got {}",
            fn_name,
            other.type_name()
        ))),
    }
}

fn extract_handle(fn_name: &str, v: &Value) -> Result<(String, i32), LispError> {
    match v {
        Value::ContainerHandle { name, pid, .. } => Ok((name.clone(), *pid)),
        other => Err(LispError::new(format!(
            "{}: expected container handle, got {}",
            fn_name,
            other.type_name()
        ))),
    }
}

/// Resolve an image reference to `(normalized_ref, manifest)`.
fn resolve_image(image_ref: &str) -> Result<(String, image::ImageManifest), LispError> {
    if let Ok(m) = image::load_image(image_ref) {
        return Ok((image_ref.to_string(), m));
    }
    let normalised = normalise_image_reference(image_ref);
    let m = image::load_image(&normalised).map_err(|e| {
        LispError::new(format!(
            "image '{}' not found locally (run 'pelagos image pull {}'): {}",
            image_ref, image_ref, e
        ))
    })?;
    Ok((normalised, m))
}

/// Normalize short image references (e.g. `alpine` → `docker.io/library/alpine:latest`).
fn normalise_image_reference(r: &str) -> String {
    let (name, tag) = r.split_once(':').map_or((r, "latest"), |(n, t)| (n, t));
    if name.contains('/') {
        if name.contains('.') || name.contains(':') {
            format!("{}:{}", name, tag)
        } else {
            format!("docker.io/{}:{}", name, tag)
        }
    } else {
        format!("docker.io/library/{}:{}", name, tag)
    }
}

/// Scope a network name to a project (mirrors the binary's `scoped_network_name`).
fn scoped_network_name(project: &str, net: &str) -> String {
    let name = format!("{}-{}", project, net);
    if name.len() > 12 {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        name.hash(&mut hasher);
        let h = hasher.finish();
        format!("{}{:04x}", &name[..8], h as u16)
    } else {
        name
    }
}

/// Parse a `"128m"` / `"1g"` memory string to bytes.
fn parse_memory(s: &str) -> Result<i64, String> {
    let s = s.trim();
    let (num, unit) = s
        .find(|c: char| c.is_alphabetic())
        .map(|i| (&s[..i], &s[i..]))
        .unwrap_or((s, ""));
    let base: i64 = num.parse().map_err(|_| format!("invalid memory: {}", s))?;
    let mult = match unit.to_lowercase().as_str() {
        "" | "b" => 1,
        "k" | "kb" => 1024,
        "m" | "mb" => 1024 * 1024,
        "g" | "gb" => 1024 * 1024 * 1024,
        _ => return Err(format!("unknown memory unit: {}", unit)),
    };
    Ok(base * mult)
}

/// Parse a `"0.5"` / `"1.5"` CPU string to `(quota_us, period_us)`.
fn parse_cpus(s: &str) -> Result<(i64, u64), String> {
    let cpus: f64 = s
        .trim()
        .parse()
        .map_err(|_| format!("invalid cpus: {}", s))?;
    let period: u64 = 100_000;
    let quota = (cpus * period as f64) as i64;
    Ok((quota, period))
}

/// Parse a `"uid[:gid]"` or `"username"` string against the image layers.
fn parse_user_in_layers(
    user: &str,
    layer_dirs: &[std::path::PathBuf],
) -> Result<(u32, Option<u32>), String> {
    // Fast path: numeric uid[:gid]
    if let Some((uid_s, gid_s)) = user.split_once(':') {
        if let (Ok(uid), Ok(gid)) = (uid_s.parse::<u32>(), gid_s.parse::<u32>()) {
            return Ok((uid, Some(gid)));
        }
    }
    if let Ok(uid) = user.parse::<u32>() {
        return Ok((uid, None));
    }
    // Username lookup: search /etc/passwd in the top-most layer.
    for layer in layer_dirs.iter().rev() {
        let passwd = layer.join("etc/passwd");
        if let Ok(contents) = std::fs::read_to_string(&passwd) {
            for line in contents.lines() {
                let fields: Vec<&str> = line.split(':').collect();
                if fields.len() >= 4 && fields[0] == user {
                    let uid = fields[2].parse::<u32>().unwrap_or(0);
                    let gid = fields[3].parse::<u32>().ok();
                    return Ok((uid, gid));
                }
            }
        }
    }
    Err(format!("user '{}' not found in image", user))
}